Printing ArrayList values in SpringBoot - json

I created an ArrayList with the json values from an Rest API.
This is the code to read the Rest API:
#RestController
public class exemploclass {
#RequestMapping(value="/vectors")
//#Scheduled(fixedRate = 5000)
public ArrayList<StateVector> getStateVectors() throws Exception {
ArrayList<StateVector> vectors = new ArrayList<>();
String url = "https://opensky-network.org/api/states/all?lamin=41.1&lomin=6.1&lamax=43.1&lomax=8.1";
//String url = "https://opensky-network.org/api/states/all?lamin=45.8389&lomin=5.9962&lamax=47.8229&lomax=10.5226";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// optional default is GET
con.setRequestMethod("GET");
//add request header
con.setRequestProperty("User-Agent", "Mozilla/5.0");
int responseCode = con.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
JSONObject myResponse = new JSONObject(response.toString());
JSONArray states = myResponse.getJSONArray("states");
System.out.println("result after Reading JSON Response");
for (int i = 0; i < states.length(); i++) {
JSONArray jsonVector = states.getJSONArray(i);
String icao24 = jsonVector.optString(0);
String callsign = jsonVector.optString(1);
String origin_country = jsonVector.optString(2);
Boolean on_ground = jsonVector.optBoolean(8);
//System.out.println("icao24: " + icao24 + "| callsign: " + callsign + "| origin_country: " + origin_country + "| on_ground: " + on_ground);
//System.out.println("\n");
StateVector sv = new StateVector(icao24, callsign, origin_country, on_ground);
vectors.add(sv);
}
System.out.println("Size of data: " + vectors.size());
return vectors;
}
}
The last line " return vectors;" returns a list with the values i parsed and returns it like this:
But i want this more "pretty", i want it to be one Array in each line, how can i achieve this?
P.S. Its on the .html page, not on console

Your return value seems a valid Json Object. If you want it more pretty so you can read it clearly then pass it through an application that makes that json pretty.
If you call your API from Postman, it will give you a pretty Json Object which will be better formatted. This will be because you have annotated your controller with #RestController so it will deliver an application/json response which Postman will know and then it will try to make it prettier.
P.S. Its on the .html page, not on console
So you hit your API from a browser. Most browsers don't expect a Json object to be returned, so they will not make it pretty. You can't force that from your Service either.
Just hit your API from Postman, it will understand it and make it pretty.

Related

In Unity, using UnityWebRequest, I cant print the body of the object I want

I used to do a post request using native C#'s library
var httpWebRequest = (HttpWebRequest)WebRequest.Create(djangoApi + user);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "{\"wallet_id\":\""+wallet+"\"," +
"\"token\":\"foo\"}";
streamWriter.Write(json);
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
but that doesn't work on mobile. So, I need to use UnityWebRequest
Following the example, https://docs.unity3d.com/Manual/UnityWebRequest-SendingForm.html, my functions look almost identical. Here is the coroutine function
IEnumerator SendPostCoroutine()
{
WWWForm form = new WWWForm();
form.AddField("user_id", "0x241477cE189fa014292d99e0807cB449b878");
form.AddField("token", "foo");
using (UnityWebRequest www = UnityWebRequest.Post(djangoApi + user, form))
{
Debug.Log(www.downloadHandler.text);
yield return www.SendWebRequest();
if (www.isNetworkError)
{
Debug.Log(www.error);
}
else
{
Debug.Log("POST successful!");
StringBuilder sb = new StringBuilder();
foreach (KeyValuePair<string, string> dict in www.GetResponseHeaders())
{
sb.Append(dict.Key).Append(": \t[").Append(dict.Value).Append("]\n");
}
// Print Headers
Debug.Log(sb.ToString());
string response = Encoding.UTF8.GetString(www.downloadHandler.data);
Debug.Log(response);
Debug.Log(www.downloadHandler.text);
}
}
}
When I do
string response = Encoding.UTF8.GetString(www.downloadHandler.data);
Debug.Log(response);
Debug.Log(www.downloadHandler.text);
neither prints out the body of the object I want. Instead, all I get is
<!DOCTYPE html>
<html lang="en">
What can I do to get the values within the json?
I just used
IEnumerator Post(string url, string bodyJsonString)
{
var request = new UnityWebRequest(url, "POST");
byte[] bodyRaw = Encoding.UTF8.GetBytes(bodyJsonString);
request.uploadHandler = (UploadHandler) new UploadHandlerRaw(bodyRaw);
request.downloadHandler = (DownloadHandler) new DownloadHandlerBuffer();
request.SetRequestHeader("Content-Type", "application/json");
yield return request.Send();
Debug.Log("Status Code: " + request.responseCode);
}
taken from https://forum.unity.com/threads/posting-json-through-unitywebrequest.476254/. That way, I can post my raw json

Parsing json in apex

Hello I have created a RESTful web services which returns the responce in below format :
[
{"empId":1,"empName":"A"},
{"empId":2,"empName":"B"},
{"empId":3,"empName":"C"},
{"empId":4,"empName":"D"},
{"empId":5,"empName":"E"}
]
I have written the simple visualforce page to call the method named 'lookup' on button click action. My Apex class is given below.
public class REST {
public PageReference lookup()
{
string resp;
// Note this version of the API is only for the US
string endpoint ='http://localhost:8080/RESTfulExample/rest/json/metallica/get';
HttpRequest req = new HttpRequest();
HttpResponse res = new HttpResponse();
Http http = new Http();
req.setMethod('GET');
req.setEndpoint(endpoint);
try {
res = http.send(req);
} catch (Exception e) {
system.debug(LoggingLevel.Error, 'Error HTTP response code = '+res.getStatusCode()+'; calling '+endpoint );
return null;
}
resp = res.getBody();
JSONParser parser = JSON.createParser(resp);
// Parsing The JSON & set the list of values to the variables 'empid' & 'empname'
return null;
}
}
Can anyone help me how I can use JSON parser to parse the JSON and to store the values to the variables.
Thank You !!!
If you would like to use JSONParser here is an example from the Salesforce documentation on JSONParser(https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_json_jsonparser.htm):
public class JSONParserUtil {
#future(callout=true)
public static void parseJSONResponse() {
Http httpProtocol = new Http();
// Create HTTP request to send.
HttpRequest request = new HttpRequest();
// Set the endpoint URL.
String endpoint = 'https://docsample.herokuapp.com/jsonSample';
request.setEndPoint(endpoint);
// Set the HTTP verb to GET.
request.setMethod('GET');
// Send the HTTP request and get the response.
// The response is in JSON format.
HttpResponse response = httpProtocol.send(request);
System.debug(response.getBody());
/* The JSON response returned is the following:
String s = '{"invoiceList":[' +
'{"totalPrice":5.5,"statementDate":"2011-10-04T16:58:54.858Z","lineItems":[' +
'{"UnitPrice":1.0,"Quantity":5.0,"ProductName":"Pencil"},' +
'{"UnitPrice":0.5,"Quantity":1.0,"ProductName":"Eraser"}],' +
'"invoiceNumber":1},' +
'{"totalPrice":11.5,"statementDate":"2011-10-04T16:58:54.858Z","lineItems":[' +
'{"UnitPrice":6.0,"Quantity":1.0,"ProductName":"Notebook"},' +
'{"UnitPrice":2.5,"Quantity":1.0,"ProductName":"Ruler"},' +
'{"UnitPrice":1.5,"Quantity":2.0,"ProductName":"Pen"}],"invoiceNumber":2}' +
']}';
*/
// Parse JSON response to get all the totalPrice field values.
JSONParser parser = JSON.createParser(response.getBody());
Double grandTotal = 0.0;
while (parser.nextToken() != null) {
if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) &&
(parser.getText() == 'totalPrice')) {
// Get the value.
parser.nextToken();
// Compute the grand total price for all invoices.
grandTotal += parser.getDoubleValue();
}
}
system.debug('Grand total=' + grandTotal);
}
}
Although from what you say in your question I think it would be simpler to do JSON Deserialization.
Here is an example on how to do it:
Wrapper Class
public class EmployeeWrapper {
public Integer empId {get;set;}
public String empName {get;set;}
}
JSON Deserialization
String jsonContent = '[{"empId": 1,"empName": "A"}, {"empId": 2,"empName": "B"}, {"empId": 3,"empName": "C"}, {"empId": 4,"empName": "D"}, {"empId": 5,"empName": "E"}]';
List<EmployeeWrapper> employeeWrapperList = (List<EmployeeWrapper>)JSON.deserialize(jsonContent, List<EmployeeWrapper>.class);
System.debug(employeeWrapperList);
//Do actions to WrapperList

Video Uploading Status in Vimeo

I am uploading video in Vimeo using my Application,But some of my videos status are not getting updated
I have followed the api document provided in this link: https://developer.vimeo.com/api/upload/videos:
I am using below code:
public boolean sendVideo(String file1, String completeURi, String endpoint, String id) throws FileNotFoundException, IOException {
File file = new File(file1);
long contentLength = file.length();
String contentLengthString = Long.toString(contentLength);
FileInputStream is = new FileInputStream(file);
int bufferSize = 20485760;
byte[] bytesPortion = new byte[bufferSize];
int byteNumber = 0;
while (is.read(bytesPortion, 0, bufferSize) != -1) {
String contentRange = Integer.toString(byteNumber);
boolean success = false;
int bytesOnServer = 0;
while (!success) {
long bytesLeft = contentLength - (bytesOnServer);
System.out.println(newline + newline + "Bytes Left: " + bytesLeft);
if (bytesLeft < bufferSize) {
//copy the bytesPortion array into a smaller array containing only the remaining bytes
bytesPortion = Arrays.copyOf(bytesPortion, (int) bytesLeft);
//This just makes it so it doesn't throw an IndexOutOfBounds exception on the next while iteration. It shouldn't get past another iteration
bufferSize = (int) bytesLeft;
}
bytesOnServer = sendVideoBytes("Vimeo Video upload", endpoint, contentLengthString, "video/mp4", contentRange, bytesPortion, first,isuploaded);
AppLog.e("bytesOnServer", "===contentLength===" + bytesOnServer +"&&=="+contentLengthString);
if (bytesOnServer >= Integer.parseInt(contentLengthString)) {
System.out.println("Success is true!");
return true;
} else {
contentRange = (bytesOnServer + 1) + "-" + (Integer.parseInt(contentLengthString)) + "/" + (Integer.parseInt(contentLengthString));
System.out.println(bytesOnServer + " != " + contentLength);
System.out.println("Success is not true!"+contentRange);
success=false;
first = true;
}
}
}
return true;
}
/**
* Sends the given bytes to the given endpoint
*
* #return the last byte on the server (from verifyUpload(endpoint))
*/
private static int sendVideoBytes(String videoTitle, String endpoint, String contentLength, String fileType, String contentRange, byte[] fileBytes, boolean addContentRange,boolean isuploaded) throws FileNotFoundException, IOException {
OAuthRequest request = new OAuthRequest(Verb.PUT, endpoint);
request.addHeader("Content-Length", contentLength);
request.addHeader("Content-Type", fileType);
if (addContentRange) {
request.addHeader("Content-Range", "bytes " + contentRange);
}
request.addPayload(fileBytes);
Response response = signAndSendToVimeo(request, "sendVideo with file bytes " + videoTitle, false);
if (response.getCode() != 200 && !response.isSuccessful()) {
return -1;
}
return verifyUpload(endpoint, contentLength, contentRange,isuploaded);
}
/**
* Verifies the upload and returns whether it's successful
*
* #param
* #param contentLength
* #param endpoint to verify upload to #return the last byte on the server
*/
public static int verifyUpload(String endpoint, String contentLength, String contentRange,boolean isuploaded) {
// Verify the upload
OAuthRequest request = new OAuthRequest(Verb.PUT, endpoint);
request.addHeader("Content-Length", "0");
request.addHeader("Content-Range", "bytes */*");
Response response = signAndSendToVimeo(request, "verifyUpload to " + endpoint, true);
AppLog.e("verifyUpload", "" + response.getCode());
if (response.getCode() != 308 || !response.isSuccessful()) {
return -1;
}
String range = response.getHeader("Range");
AppLog.e("After verify","==range header contains"+Integer.parseInt(range.substring(range.lastIndexOf("-") + 1)));
//range = "bytes=0-10485759"
return Integer.parseInt(range.substring(range.lastIndexOf("-") + 1)); //+1 remove
//return Integer.parseInt(range.substring(range.lastIndexOf("-") + 1)) + 1;
//The + 1 at the end is because Vimeo gives you 0-whatever byte where 0 = the first byte
}
public static Response signAndSendToVimeo(OAuthRequest request, String description, boolean printBody) throws org.scribe.exceptions.OAuthException {
String newline = "\n";
System.out.println(newline + newline
+ "Signing " + description + " request:"
+ ((printBody && !request.getBodyContents().isEmpty()) ? newline + "\tBody Contents:" + request.getBodyContents() : "")
+ ((!request.getHeaders().isEmpty()) ? newline + "\tHeaders: " + request.getHeaders() : ""));
service.signRequest(OAuthConstants.EMPTY_TOKEN, request);
Response response = request.send();
// AppLog.e("Uplaod Video aftre Response", "" + response.getCode());
return response;
}
Can anyone help with a working code for Android??
Thanks in advance!!
I recently had the same problem with vimeo. The api returns the state VIMUploadState_Succeeded for the upload process, but if you try to watch the video at vimeo.com it is stucked in the uploading state and it shows a black screen in the app when you try to reproduce the video.
I got the following answers from their support team:
It looks like this specific video
didn't change from the uploaded state to a failure state.
Sorry but the videos provided in those links never finished uploading
and are lost. They will need to be re-uploaded.
In our platform there are several videos uploaded everyday and it seems to have no pattern to identify when this uploading problem will happen. If it is not a problem for you to re-upload the video, vimeo can be a good solution since its price is really good in comparison to other video platforms, otherwise you should look for another video storage/playback solution.
It is difficult to check up your code without proper debugging.
Here's the workaround for your code with a little more functions added
You can check the code here

RestClient sends null data from winphone 8 to Wcf rest service

string URL="https://sampleservicebus.servicebus.windows.net/WinPhoneService/"
RestClient client = new RestClient(URL);
RestRequest request = new RestRequest("getkpimeasuredata", Method.POST);
KpiDomainData kpidata = new KpiDomainData();
kpidata.KPIId = 1006;
kpidata.ScorecardId = 3;
kpidata.EngineeringOrgId = 11;
kpidata.DataValuetypeId = 1;
kpidata.CumulativeMonth = 463;
kpidata.BusinessOrgId = 1;
string json = Newtonsoft.Json.JsonConvert.SerializeObject(kpidata);
json = "{\"kpidata\" : " + json + "}";
request.AddParameter("application/json; charset=utf-8", json, ParameterType.RequestBody);
request.RequestFormat = DataFormat.Json;
ObservableCollection<KpiMeasureData> kpiDetailsList = await client.ExecuteTaskAsync<ObservableCollection<KpiMeasureData>>(request);
client.ExecuteAsync(request, response =>
{
if (response.StatusCode == HttpStatusCode.OK)
{
}
});
When I debugged the wcf service code i came to know that the json data sent to getkpimeasuredata webmethod is null, I mean all the property values of the composite type were null even though I'm passing the data with values
And the Restcall works when I use Webclient instead of Restclient. But I need to use Restclient only. Please help.

badrequest error while requesting bing microsofttranslate api?

The following code returns bad request exception.Not sure what's wrong here .
string appId = "956vaQc49TdepGpsywiM+BRqfxfgOTeCr/514=";
//go to http://msdn.microsoft.com/en-us/library/ff512386.aspx to obtain AppId.
string text = "translate this";
string language = "en";
System.Uri uri = new Uri("http://api.microsofttranslator.com/v2/Http.svc/Speak?&appId=" + appId + "&text=" + text + "&language=" + language);
try
{
HttpClient client = new HttpClient();
HttpResponseMessage response = await client.GetAsync(uri);
response.EnsureSuccessStatusCode();
Stream responseBody = await response.Content.ReadAsStreamAsync();
// meTextToSpeeach.Source = uri;
string strResponse;
using (Stream responseStream = responseBody)
{
using (StreamReader sr = new StreamReader(responseStream, System.Text.Encoding.Unicode))
{
strResponse = sr.ReadToEnd();
}
}
}
catch (Exception)
{
}
You are not encoding the parameters (appId, text, language). You should be doing "..." + WebUtility.UrlEncode(appId) + "..." ...