I am facing issue while getting json data from Response and creating JSONobject.
Issue : Getting delay to create JSONObject. [Approx. 1-2 min ]
This is the code I am using to create the JOSNObject.
Representation rep = response.getEntity();
rep.setCharacterSet(CharacterSet.UTF_8); JsonRepresentation
jsonRep = new JsonRepresentation(rep);
JSONObject jsonObj = jsonRep.getJsonObject();
Jar Details : 1.6 (org.restlet.jar)
Please help me.
Related
I am trying to enable web api to support both JSON and XML as return type. While serializing complex datattype to XML I got circular reference errors, so I decorated my main class with DataContract(IsReference = true), now XML serialization is working and json serialization not working.
thanks in advance.
PS: i am able to serialize simple dto classes to both xml and json, but for complex datatypes the problem is coming.
Set the followings in App_Start/WebApiConfig.cs
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
GlobalConfiguration.Configuration.Formatters.Clear();
GlobalConfiguration.Configuration.Formatters.Add(new JsonMediaTypeFormatter());
GlobalConfiguration.Configuration.Formatters.Add(new XmlMediaTypeFormatter());
Set application/json or application/xml to Accept header in request-side.
Result will be decided based on result type formatter. Hence I wrote 2 different methods for each return type. To solve, circular reference errors while generating xml i followed below steps.
Serialize class result
Deserialize class result.
Write it to xml.
var json = JsonConvert.SerializeObject(result);
var rO = JsonConvert.DeserializeObject<TClass>(json);
return Ok(ReturnAsXml(rO), Configuration.Formatters.XmlFormatter);
protected virtual XElement ReturnAsXml<T>(T data)
{
Type t = data.GetType();
DataContractSerializer serializer = new DataContractSerializer(t);//, extraTypes);
StringWriter sw = new StringWriter();
XmlTextWriter xw = new XmlTextWriter(sw);
serializer.WriteObject(xw, data);
var o = XElement.Parse(sw.ToString());
return o;
}
I'm trying to pull a 20MB file from MFP server. So, I wrote the following code in my client application.
var resourceRequest = new WLResourceRequest("/adapters/AdapterExample/users/getUpdate",WLResourceRequest.POST);
resourceRequest.send().then(function(result){
Logger("Hello Im here ! : " + result.responseJSON.isSuccessful);
},function(error){
Logger("Im error ! : " + error);
});
Unfortunately, it shows the following error in JSON format:
JSON Result :{"isSuccessful":false,"errors":["Data size exceeds maximum permitted value of 10Mb."]}
Is there any data size limitation for Java adapter which data size cannot more than 10 MB?
Remarks: Code below is my Java Adapter sample code:
#POST
#Path("/getUpdate")
public String getUpdate() throws IOException{
JSONObject obj = new JSONObject();
java.nio.file.Path path = Paths.get("/Users/abc/Documents/example.zip");
byte[] fileData = Files.readAllBytes(path);
obj.put("fileName", path.getFileName().toString());
obj.put("size", Base64.encodeBase64String(fileData).length());
return obj.toString();
}
From MobileFirst-perspective, Java adapters impose no such file size limits. I suggest to consider a network issue, such as some vendor your request is going through that imposes this limitation.
I am using Google diff-match-patch JAVA plugin to create patch between two JSON strings and storing the patch to database.
diff_match_patch dmp = new diff_match_patch();
LinkedList<Patch> diffs = dmp.patch_make(latestString, originalString);
String patch = dmp.patch_toText(diffs); // Store patch to DB
Now is there any way to use this patch to re-create the originalString by passing the latestString?
I google about this and found this very old comment # Google diff-match-patch Wiki saying,
Unpatching can be done by just looping through the diff, swapping
DIFF_INSERT with DIFF_DELETE, then applying the patch.
But i did not find any useful code that demonstrates this. How could i achieve this with my existing code ? Any pointers or code reference would be appreciated.
Edit:
The problem i am facing is, in the front-end i am showing a revisions module that shows all the transactions of a particular fragment (take for example an employee details), like which user has updated what details etc. Now i am recreating the fragment JSON by reverse applying each patch to get the current transaction data and show it as a table (using http://marianoguerra.github.io/json.human.js/). But some JSON data are not valid JSON and I am getting JSON.parse error.
I was looking to do something similar (in C#) and what is working for me with a relatively simple object is the patch_apply method. This use case seems somewhat missing from the documentation, so I'm answering here. Code is C# but the API is cross language:
static void Main(string[] args)
{
var dmp = new diff_match_patch();
string v1 = "My Json Object;
string v2 = "My Mutated Json Object"
var v2ToV1Patch = dmp.patch_make(v2, v1);
var v2ToV1PatchText = dmp.patch_toText(v2ToV1Patch); // Persist text to db
string v3 = "Latest version of JSON object;
var v3ToV2Patch = dmp.patch_make(v3, v2);
var v3ToV2PatchTxt = dmp.patch_toText(v3ToV2Patch); // Persist text to db
// Time to re-hydrate the objects
var altV3ToV2Patch = dmp.patch_fromText(v3ToV2PatchTxt);
var altV2 = dmp.patch_apply(altV3ToV2Patch, v3)[0].ToString(); // .get(0) in Java I think
var altV2ToV1Patch = dmp.patch_fromText(v2ToV1PatchText);
var altV1 = dmp.patch_apply(altV2ToV1Patch, altV2)[0].ToString();
}
I am attempting to retrofit this as an audit log, where previously the entire JSON object was saved. As the audited objects have become more complex the storage requirements have increased dramatically. I haven't yet applied this to the complex large objects, but it is possible to check if the patch was successful by checking the second object in the array returned by the patch_apply method. This is an array of boolean values, all of which should be true if the patch worked correctly. You could write some code to check this, which would help check if the object can be successfully re-hydrated from the JSON rather than just getting a parsing error. My prototype C# method looks like this:
private static bool ValidatePatch(object[] patchResult, out string patchedString)
{
patchedString = patchResult[0] as string;
var successArray = patchResult[1] as bool[];
foreach (var b in successArray)
{
if (!b)
return false;
}
return true;
}
I am making a call to splunk and then I am trying to use the ResultsReaderJson class to get my results.
InputStream results = jobSavedSearch.getResults();
ResultsReaderJson resultsReader = new ResultsReaderJson(results);
And I keep getting this error.
com.google.gson.stream.MalformedJsonException: Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 6
I have no access to the JsonReader from this class. Does anybody have any ideas of what I can do to get around this?
You have not asked for the results stream to return you JSON. The default is XML. To fix this you could use:
Args outputArgs = new Args();
outputArgs.put("output_mode","json");
InputStream results = jobSavedSearch.getResults(outputArgs);
In Splunk 1.3.0 API you can do:
JobExportArgs jobargs = new JobExportArgs();
jobargs.setOutputMode(JobExportArgs.OutputMode.JSON);
InputStream exportSearch = jobSavedSearch.getResults(jobargs);
MultiResultsReaderJson multiResultsReader = new MultiResultsReaderJson(exportSearch);
I am trying to query my local Solr server using HttpClient and I cannot figure out why the parameters are not being added to the GET call.
My code for doing this is:
HttpRequestBase request = new HttpGet("http://localhost:8080/solr/select");
HttpParams params = new BasicHttpParams();
params.setParameter("q", query);
params.setParameter("start", String.valueOf(start));
params.setParameter("rows", String.valueOf(rows));
request.setParams(params);
HttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(request);
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
return stringToStreamConversion(is); //500 error, NullPointerException, response is empty
I have tried to return several things in hopes of seeing what I would get and trying to figure out where the problem was. I have finally realized that I was only getting back the http://localhost:8080/solr/select when I returned
return request.getURI().toURL().toString();
I cannot figure out why the parameters are not getting added. If I do
return request.getQuery();
I get nothing back...any ideas? Thanks for the help in advance!
From what I have seen you are not able to associate your paeans with the request.
So, instead of creating a new HttpParams object and associating it with request, can you try the following approach ?
httpCclient.getParams().setParameter("q", query");
....
The simpler option is to use the approach I used in HTTPPostScheduler, like this:
URL url = new URL(completeUrl);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("type", "submit");
conn.setDoOutput(true);
// Send HTTP POST
conn.connect();