Get response JSON object webservice RESTful java - java

When I access my URL http://localhost:8081/projectName/pathh/param to show me the JSON Object created
"Employee": [{
"id": "param"
}]
This is my code in Java. I use Eclipse + Tom Cat Server.
#Path("/pathh")
#GET
#Path("{parameter}")
public Response getJSONObj(#PathParam("parameter") String parameter) {
JSONObject jsonObj = new JSONObject();
JSONArray jsonarray = new JSONArray();
jsonObj.put("id", parameter);
jsonarray.put(jsonObj);
System.out.println(jsonarray);
JSONObject jsonMain = new JSONObject();
jsonMain.put("Employee", jsonarray);
System.out.println(jsonMain.toString());
System.out.println(Response.status(200).entity(jsonMain).build());
return Response.status(200).entity(jsonMain).build();
}
I get that error :
HTTP Status 500 - java.lang.IllegalArgumentException: wrong number of
arguments
type Exception report
message java.lang.IllegalArgumentException: wrong number of arguments
description The server encountered an internal error that prevented it
from fulfilling this request.

package com.tests;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Response;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
#Path("/path/{parameter}")
public class Test1 {
#GET
public Response getJSONObj(#PathParam("parameter") String parameter) {
JsonObject jsonObj = new JsonObject();
JsonArray jsonarray = new JsonArray();
jsonObj.addProperty("id", parameter);
jsonarray.add(jsonObj);
System.out.println(jsonarray);
JsonObject jsonMain = new JsonObject();
jsonMain.add("Employee", jsonarray);
System.out.println(jsonMain.toString());
System.out.println(Response.status(200).entity(jsonMain).build());
return Response.status(200).entity(jsonMain.toString()).build();
}
}
I have used Jersey as the Jax-RS API implementation. jersey-server and jersey-servlet are included as dependencies and web.xml has an entry for the jersey servlet mapping.

It would help if you could debug it and find the line it's failing on, or whether it never makes it into the method and you have a problem with your application wiring/annotations.
That said, I suspect that if you delete or comment out the line
System.out.println(Response.status(200).entity(jsonMain).build());
it will work.

Related

why does this AWS Lambda code in Java return "internal server error" when invoked via an API gateway?

From my understanding, if you return the following json string: {"headers":{"Content-Type":"application/json"},"body":"hello world","statusCode":200}
then when visiting the page https://....eu-west-2.amazonaws.com/prod/, you should see the phrase "hello world" written. Instead, I get {"message": "Internal server error"}
Below is the JAVA code I am using to return the above json string:
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
import org.json.simple.JSONObject;
import java.util.Map;
public class Handler implements RequestHandler<Map<String, String>, JSONObject>{
#Override
public JSONObject handleRequest(Map<String, String> stringStringMap, Context context) {
JSONObject obj = new JSONObject();
JSONObject obj2 = new JSONObject();
obj2.put("Content-Type", "application/json");
obj.put("statusCode", 200);
obj.put("headers", obj2);
obj.put("body", "hello world");
return obj;
}
}
What am I doing wrong? It works fine on the console when I test the function, but when I go to the page of the API it gives me an internal server error.
The error message you posted in the comment has already explained what the problem is. Basically, lambda handler is not able to convert the input object to String. You can solve this by changing Map<String, String> to Map<String, Object> or general Object.
Also, as #david pointed out in the comment, you should return a JSON String instead of a JSONObject. So the fully working code could be something like this:
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
import org.json.simple.JSONObject;
import java.util.Map;
public class Handler implements RequestHandler<Map<String, Object>, String>{
#Override
public String handleRequest(Map<String, Object> stringStringMap, Context context) {
JSONObject obj = new JSONObject();
JSONObject obj2 = new JSONObject();
obj2.put("Content-Type", "application/json");
obj.put("statusCode", 200);
obj.put("headers", obj2);
obj.put("body", "hello world");
return obj.toString();
}
}
For anyone interested, the following code worked fine for me:
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestStreamHandler;
import org.json.simple.JSONObject;
import java.io.*;
public class Handler implements RequestStreamHandler{
#Override
public void handleRequest(InputStream inputStream, OutputStream outputStream,
Context context) throws IOException {
JSONObject obj = new JSONObject();
JSONObject obj2 = new JSONObject();
obj2.put("Content-Type", "application/json");
obj.put("statusCode", 200);
obj.put("headers", obj2);
obj.put("body", "hello world");
OutputStreamWriter writer = new OutputStreamWriter(outputStream, "UTF-8");
writer.write(obj.toString());
writer.close();
}
}

Sending HTTP POST request with custom JSON file in the request body

I'm facing with some issue in my java code:
package com.automation.com.automation.<name>;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.junit.Test;
import static com.jayway.restassured.RestAssured.*;
import java.io.FileNotFoundException;
import java.io.FileReader;
public class SendDCandidateDate {
#Test
public void sendCandidateData() throws FileNotFoundException {
String accessToken = "<your access token comes here>";
String apiUrl = "<your API url comes here>";
JSONParser parser = new JSONParser();
try {
Object object = parser.parse(new FileReader("src/main/resources/Full_List.json"));
JSONObject jsonObject = (JSONObject) object;
given().auth().preemptive().oauth2(accessToken);
given().body(jsonObject).when().post(apiUrl).then().assertThat().statusCode(200);
}catch (Exception ex) {
System.out.println(ex);
}
}
}
I have no exception, however the assertion comes back with error 404 instead of 200. (Error 401 is also acceptable for now, which means the accessToken is expired it would be also an expected behaviour).
I think I have a logical issue in my code, can anyone help me with it?

how to send response in json to a tree structure in servlet

i am new to servlet and i succeeded to send a json format to the client using json-simple package/jar file; and import it like-
import org.json.simple.JSONObject;
and to get response in json i have following code-
response.setContentType("application/json");
JSONObject obj = new JSONObject();
obj.put("name", "veshraj joshi");
obj.put("id",request.getParameter("id"));
obj.put("num", new Integer(100));
obj.put("balance", new Double(1000.21));
out.println(obj);
and its format is like:
{"name":"veshraj joshi","id":"","num":"100","balance":"1000.21"}
and works fine,
but i need json format like-
{ status:"ok",
message:"record has been added successfully",
data:{
name:"veshraj joshi",
email:"email#gmail.com",
address:"kathmandu, Nepal"
}
}
and dont have any idea how to achieve this in servlet;
It works fine while try to make nested json and new code become-
response.setContentType("application/json");
JSONObject obj = new JSONObject();
JSONObject obj1 = new JSONObject();
obj1.put("email",'email#gmail.com');
obj1.put("name", "veshraj joshi");
obj1.put("id",request.getParameter("id"));
obj1.put("num", new Integer(100));
obj1.put("balance", new Double(1000.21));
obj.put("status","ok");
obj.put("message","record has been added successfully");
obj.put("data",obj1);
out.println(obj);

Unsupported Media Type (415) for POST request to Restlet service

I POST to an endpoint like following:
import java.util.logging.Level;
import org.json.JSONException;
import org.json.JSONObject;
import org.restlet.ext.json.JsonRepresentation;
import org.restlet.representation.Representation;
import org.restlet.resource.Post;
import org.restlet.resource.ServerResource;
try {
JSONObject jsonToCallback = AcceptorManager.getJsonFromClient();
String test = jsonToCallback.getString("test");
String st2 = jsonToCallback.getString("st2");
ClientResource clientResource = new ClientResource(callback);
clientResource.setMethod(Method.POST);
Form form = new Form ();
form.add("key1", val1);
form.add("key2", "stat");
Representation representation = clientResource.post(form, MediaType.APPLICATION_JSON);
} catch (Exception e) {
//Here I get "Unsupported Media Type (415) - Unsupported Media Type"
}
And this is the endpoint:
public class test extends ServerResource{
#Post
public JSONObject testPost(JSONObject autoStackRep) throws JSONException, AcceptorException {
JSONObject json=new JSONObject();
try {
json.put("result",false);
json.put("id",1);
} catch (JSONException e) {
e.printStackTrace();
}
return json;
}
}
How can I fix this issue?
Passing JSONObject as input parameter of your POST method doesn't make it accept appication/json. Restlet has several ways of specifying accepted Media-Type. You can specify it in #Post annotation like this:
#Post("json")
public Representation testPost(Representation autoStackRep)
If only one extension is provided, the extension applies to both request and response entities. If two extensions are provided, separated by a colon, then the first one is for the request entity and the second one for the response entity. Note that parameter type is now Representation. You can use Representation.getText() method to retrieve content of response entity. You may also specify POJO as parameter type:
#Post("json")
public MyOutputBean accept(MyInputBean input)
In this case you need Jackson extension to be able to map JSON to POJO and vice versa. Just make sure org.restlet.ext.jackson.jar is in your classpath. You may omit media type declaration when using POJO as parameter, in this case Restlet will try to apply all available converters to input stream to map it to your POJO.

Server GET json in jersey, JAVA

im not sure how to get a json object and output it in jersey using rest GET from a ajax json post, im using grizzly server, server has been set, heres the code that supposed to get the json, correct me please, thanks!
import java.io.IOException;
import java.io.InputStream;
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;
import org.apache.commons.io.IOUtils;
import javax.ws.rs.*;
#Path("/helloworld")
public class GetData {
#GET
#Consumes("application/json")
public String getResource(JSONObject obj) throws IOException {
InputStream in = (InputStream) obj.values();
String data = IOUtils.toString(in);
JSONObject out = (JSONObject) JSONSerializer.toJSON(data);
String result = out.getString("name");
return result;
}
}
You need to find out, what is your JSON object should be deserialized to. If it's just a JSONObject and you want to parse it manually:
#Consumes("application/json")
public String getResource(JSONObject obj) {
...
}
If it is some kind of custom object:
#Consumes("application/json")
public String getResource(CustomObj customObj) {
...
}
But then you should take care about marshalling/unmarshalling of that object to JSON by Jackson.

Categories