Best way to send a JSon object from Servlet - java

The question can seem simple, but I didn't find a good answer yet. I need to send a JSon structure (build with an unspecified libretry I'm currently developing) from a Servlet to a remote page.
I'm interested in the best way to send the structure.
I mean, in my Servlet, inside the doPost() event, how should I manage the send?
I was thinking about 2 scenarios:
try (PrintWriter out = response.getWriter()) {
out.print(myJSon.toString(); // <- recursive function that overrides
// toString() and returns the entire JSon
// structure
} (...)
or
try (OutputStream os = response.getOutputStream()) {
myJSon.write(os, StandardCharsets.UTF8); // <- function that
// recursively writes chunk of my JSon structure
// in a BufferWriter created inside the root write function
// forcing UTF-8 encoding
} (...)
Or something different, if there's a better approch.
Note that the JSon structure contains an array of objects with long text fields (descriptions with more than 1000 characterd), so it can be quite memory consuming.
For why I'm not using standard JSon libreries, it's because I don't know them and I don't know if I can trust them yet. And also I don't know if I will be able to install them on the production server.
Thanks for your answers.

From your question i see multiple points to adress:
How to send your JSon
What JSon library can you use
How to use the library in production
How to send your JSon
From your code this seems to be an HTTP response rather than a POST on your Servlet so you need to know how to send a JSON string as an HTTP response's body
Do you use a framework for your web server or are you handling everything manually ? If you use a framework it usually does it for you, just pass the JSON String
If your doing it manually:
try (PrintWriter pw = response.getWriter()) {
pw.write(myJson.toString());
}
or
try (OutputStream os = response.getOutputStream()) {
os.write(myJson.toString().getBytes());
}
Both are valid, see Writer or OutputStream?
Your JSON's size shouldn't matter given what your saying, it's just text so it won't be big enough to matter.
What libraries can you use
There are a lot of JSON libraries for Java, mainly:
Jackson
GSon
json-io
Genson
Go for the one you prefer, there will be extensive documentation and resources all over google
How to use in production
If you are not sure you are able to install dependencies on the production server, you can always create an uber-jar (See #Premraj' answer)
Basically, you bundle the dependency in your Jar

Using Gson is good way to send json
Gson gson = new Gson();
String jsonData = gson.toJson(student);
PrintWriter out = response.getWriter();
try {
out.println(jsonData);
} finally {
out.close();
}
for detail json response from servlet in java

Related

Get EC2 Instance XML Description using AWS Java SDK?

We have a scenario in which we need to retrieve the description info for EC2 instances running on AWS. To accomplish this, we are using the AWS Java SDK. In 90% of our use case, the com.amazonaws.services.ec2.model.Instance class is exactly what we need. However, there is also a small use-case where it would be beneficial to get the raw XML describing the instance. That is, the XML data before it is converted into the Instance object. Is there any way to obtain both the Instance object and the XML string using the AWS Java SDK? Is there a way to manually convert from one to the other? Or, would we be forced to make a separate call using HttpClient or something similar to get the XML data?
Make an EC2Client by adding request handler and override the beforeUnmarshalling() method like below
AmazonEC2ClientBuilder.standard().withRegion("us-east-1")
.withRequestHandlers(
new RequestHandler2() {
#Override
public HttpResponse beforeUnmarshalling(Request<?> request, HttpResponse httpResponse) {
// httpResponse.getContent() is the raw xml response from AWS
// you either save it to a file or to a XML document
return new HTTPResponse(...);
// if you consumed httpResponse.getContent(), you need to provide new HTTPResponse
}
}
).build():
If you have xml (e.g. from using AWS rest API directly), then you can use com.amazonaws.services.ec2.model.transform.* classes to convert xml to java objects. Unfortunately, it only provides classes required for SDK itself. So you, for example, can convert raw XML to an Instance using InstanceStaxUnmarshaller, but can't convert Instance to XML unless you write such converter.
Here is an example how to parse an Instance XML:
XMLEventReader eventReader = XMLInputFactory.newInstance().createXMLEventReader(new StringReader(instanceXml));
StaxUnmarshallerContext suc = new StaxUnmarshallerContext(eventReader, new TreeMap<>());
InstanceStaxUnmarshaller isu = new InstanceStaxUnmarshaller();
Instance i = isu.unmarshall(suc);
System.out.println(i.toString());
You probably can try to intercept raw AWS response, so that you can keep raw XML while still using SDK most of the time. But I wouldn't call that easy as it will require quite a bit of coding.
You could use JAXB.marshal like following. JAXB (Java Architecture for XML Binding) could convert Java object to / from XML file.
StringWriter sw = new StringWriter();
JAXB.marshal(instance, sw);
String xmlString = sw.toString();
You can use AWS rest API to replace Java SDK. A bonus will be slight performance gain because you'll not send statistic data to Amazon as the SDK does.

How to read external JSON file from JMeter

Is there a way (any jmeter plugin) by which we can have the JMeter script read all the contents(String) from external text file ?
I have a utility in java which uses Jackson ObjectMapper to convert a arraylist to string and puts it to a text file in the desktop. The file has the JSON info that i need to send in the jmeter Post Body.
I tried using ${__FileToString()} but it was unable to deserialize the instance of java.util.ArrayList. It was also not reading all the values properly.
I am looking for something like csv reader where i just give the file location. I need all the json info present in the file. Need to extract it and assign to the post body.
Thanks for your help !!!
If your question is about how to deserialize ArrayList in JMeter and dynamically build request body, you can use i.e. Beanshell PreProcessor for it.
Add a Beanshell PreProcessor as a child of your request
Put the following code into the PreProcessor's "Script" area:
FileInputStream in = new FileInputStream("/path/to/your/serialized/file.ser");
ObjectInput oin = new ObjectInputStream(in);
ArrayList list = (ArrayList) oin.readObject();
oin.close();
in.close();
for (int i = 0; i < list.size(); i++) {
sampler.addArgument("param" + i, list.get(i).toString());
}
The code will read file as ArrayList, iterate through it and add request parameter like:
param1=foo
param2=bar
etc.
This is the closest answer I'm able to provide, if you need more exact advice - please elaborate your question. In the meantime I recommend you to get familiarized with How to use BeanShell: JMeter's favorite built-in component guide to learn about scripting in JMeter and what do pre-defined variables like "sampler" in above code snippet mean.

Object Sereialization, JAVA, Javascript

I have n object whose properties are being sent to a front end using REST protocols. There the object is taken in as an XML file and then parsed to JSON using JSON.parser. Now my target is to save this JSON file for some specified time on the disk. I tried serializing the object and storing it but it gets stored in binary/hex format. I need it to be in xml or JSON format.
Can anybody help me with this ?
Front-end is in JavaScript and the back-end is in Java.
Why you need to save JSON file on client side disk, it is not recommended practice. Rather you should use HTML5 web storage.
are you using JSON.simple? if so, there are several examples on their page for converting a string to json and back. in this case you already have a deserialized object so you would just need to serialize it to a string see https://code.google.com/p/json-simple/wiki/DecodingExamples
if you have your json object as a map you can
String jsonString = JSONValue.toJSONString(json);
or if it is already a JSONObject then simply
String jsonString = json.toJSONString();
then write the jsonString to your .json file.
FileWriter file = new FileWriter("/path/to/file.json");
file.write(jsonString);
file.flush();
file.close();
apologies if that is not the library you are using.

Extjs file upload and return message using JSONObject

I tried uploading an excel file and it worked well but the return message doesn't show. For the return message I use the below code as shown here:
JSONObject myObj = new JSONObject();
//sets success to true
myObj.put("success", true);
//convert the JSON object to string and send the response back
out.println(myObj.toString());
out.close();
For using this class I used the json-lib.jar. Further it asks for dependent jars like ezmorph-1.0.jar which I am doubtful of using.
Has anyone used the above method to return a message to the front end?
If so, what were the jars used in the process? Please help
I resolved the above by using json-simple-1.1.jar instead of json-lib.jar.
This created a JSONObject without the need of any other jar.

Adding elements to an JSON object in a external JSON file?

(After months of surfing the internet, talking to the school's computing department and try code out, I still don't get how to do it, but I do know more specific about what I trying to do)
Previously I said I want to "Add lines" to a existing JSON file.
What I want to do is simply add an element to an JSON object from a file, then save the file.
However I am still confused about how to do it.
The process I am guessing is to use ajax to load the content of the file (the JSON code in the file) into a variable then add the new element into the object then save the file.
I have seen a lot of code but are all just too confusing and looks like its for webpages. I am trying to edit a file on the computer as a program which I think webpage related code such as xmlhttp requests are irrelevant as the file is in a folder in appdata.
I have been confused and thought Java and Javascript were the same thing, I know now they're not.
What code or functions would I look for and how would it be used in the code?
(Please don't post pseudocode because I have no idea how to write the code for them since I have literally no idea how to code anything other than a html webpage and some php. Other coding language like Java, Javascript and Python I have little knowledge with but not enough to write a program alone.)
I think it would be best to use code that somebody else has already written to manipulate the JSON. There are plenty of libraries for that, and the best would be the officially specified one, JSON-P. What you would do is this:
Go to http://jsonp.java.net/ and download JSON-P. (You will have to examine the page carefully to find the link to "JSON Processing RI jar".) You will need to include this JAR in your class path while you write your program.
Add imports to your program for javax.json.*.
Write this code to do the job (you will have to catch JsonExceptions and IOExceptions):
JsonReader reader = Json.createReader(new FileReader("launcher_profiles.json"));
JsonObject file = reader.readObject();
reader.close();
JsonObject profiles = file.getJsonObject("profiles");
JsonObject newProfile = Json.createObjectBuilder()
.add("name", "New Lines")
.add("gameDir", "New Lines")
.add("lastVersionId", "New Lines")
.add("playerUUID", "")
.build();
JsonObjectBuilder objectBuilder = Json.createObjectBuilder()
.add("New Profile Name", newProfile);
for (java.util.Map.Entry<String, JsonValue> entry : profiles.entrySet())
objectBuilder.add(entry.getKey(), entry.getValue());
JsonObject newProfiles = objectBuilder.build();
// Now, figure out what I have done so far and write the rest of the code yourself! At the end, use this code to write out the new file:
JsonWriter writer = Json.createWriter(new FileWriter("launcher_profiles.json"));
writer.writeObject(newFile);
writer.close();

Categories