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?
Related
I'm trying to create a servlet in AEM which uses the parameter from ajax and sends the response from URL back to ajax request
but when I hit button its throws an internal server error along with unable to create a node at /bin/searchServlet.
response from URL is in json format
here is my servlet
package com.community.aem.core.servlets;
import org.osgi.framework.Constants;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.servlets.HttpConstants;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.HttpResponse;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.sling.jcr.api.SlingRepository;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.rmi.ServerException;
import java.util.Base64;
import java.io.IOException;
import javax.servlet.Servlet;
import com.google.gson.Gson;
import com.google.gson.*;
#Component(service=Servlet.class,
property={
Constants.SERVICE_DESCRIPTION + "=Simple Demo Servlet",
"sling.servlet.methods=" + HttpConstants.METHOD_POST,
"sling.servlet.paths="+ "/bin/searchServlet"
})
public class slingdemo2 extends
org.apache.sling.api.servlets.SlingAllMethodsServlet {
private static final long serialVersionUID = 2598426539166789515L;
private SlingRepository repository;
#Reference
public void bindRepository(SlingRepository repository){
this.repository = repository;
}
public void unbindRepository(SlingRepository repository) {
this.repository = repository;
}
#Override
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response)
throws ServerException, IOException {
try
{
// Get the submitted form data that is sent from the
String query = request.getParameter("query");
//sending HTTP request and reading content using buffered reader
HttpResponse response1 = httpClient.execute(getRequest);
BufferedReader br = new BufferedReader(new InputStreamReader((response1.getEntity().getContent())));
String output;
String myJson = " ";
while ((output = br.readLine()) != null) {
myJson = myJson + output;
}
Gson gson = new Gson();
String jsonArray = gson.toJson(myJson);
response.getWriter().write(jsonArray);
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
and here is my ajax query
$(document).ready(function(){
$('body').hide().fadeIn(1000);
$('#submit').click(function() {
var query= $('query').val() ;
$.ajax({
type: 'POST',
url:'/bin/searchServlet',
data:query,
success: function(responseText){
$('#result').val(responseText);
}
});
});
});
Maybe it would help if your Post(!) servlet would have code for post requests and not only for get requests.
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();
}
}
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.
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.
I want to use the Google Shortener API. I want to use the google api java client library to post a request and parse the JSON response.
Next, I post the code I have tried:
import java.io.IOException;
import net.sf.json.JSONObject;
import com.google.api.client.googleapis.GoogleHeaders;
import com.google.api.client.googleapis.GoogleTransport;
import com.google.api.client.googleapis.json.JsonCParser;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonHttpContent;
import com.google.api.client.util.GenericData;
public class GoogleShortener {
public static final String GOOGL_URL = "https://www.googleapis.com/urlshortener/v1/url";
public static void main(String[] args) {
// setup up the HTTP transport
HttpTransport transport = GoogleTransport.create();
// add default headers
GoogleHeaders defaultHeaders = new GoogleHeaders();
transport.defaultHeaders = defaultHeaders;
transport.defaultHeaders.put("Content-Type", "application/json");
transport.addParser(new JsonCParser());
// build the HTTP GET request and URL
GenericData data = new GenericData();
data.put("longUrl", "http://www.google.com/");
JsonHttpContent content = new JsonHttpContent();
content.data = data;
HttpRequest request = transport.buildPostRequest();
request.content = content;
request.setUrl(GOOGL_URL);
HttpResponse response;
try {
JSONObject json = request.execute().parseAs(JSONObject.class);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
When I execute the above code, I get the next output:
Exception in thread "main" java.lang.IllegalArgumentException: data key not found
at com.google.api.client.googleapis.json.JsonCParser.parserForResponse(JsonCParser.java:77)
at com.google.api.client.googleapis.json.JsonCParser.parse(JsonCParser.java:47)
at com.google.api.client.http.HttpResponse.parseAs(HttpResponse.java:261)
at GoogleShortener.main(GoogleShortener.java:43)
Any idea how to set the JsonCParser properly?
ERROR PATH
In the beginning I was not setting properly the request content. As pointed by #dwb, the request content should be set:
GenericData data = new GenericData();
data.put("longUrl", "http://www.google.com/");
JsonHttpContent content = new JsonHttpContent();
content.data = data;
request.content = content;
If you do not set the content properly, you will get the next error
com.google.api.client.http.HttpResponseException:
411 Length Required at
com.google.api.client.http.HttpRequest.execute(HttpRequest.java:209)
at
GoogleShortener.main(GoogleShortener.java:32)
You need to add JSON content to the request body like this:
GenericData data = new GenericData();
data.put("longUrl", "http://www.google.com/");
JsonHttpContent content = new JsonHttpContent();
content.data = data;
request.content = content;
For the response, try using the JsonHttpParser instead of JsonCParser. You'll need to create a subclass of GenericJson that contains fields with a #Key annotation for every JSON property you want to retrieve. You can use response.parseAsString() to see all of the properties available.
Here's a full working example:
import com.google.api.client.googleapis.GoogleHeaders;
import com.google.api.client.googleapis.GoogleTransport;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.GenericJson;
import com.google.api.client.json.JsonHttpContent;
import com.google.api.client.json.JsonHttpParser;
import com.google.api.client.util.GenericData;
import com.google.api.client.util.Key;
public class Shortener {
public static final String GOOGL_URL = "https://www.googleapis.com/urlshortener/v1/url";
/**
* #param args
*/
public static void main(String[] args) throws Exception {
// setup up the HTTP transport
HttpTransport transport = GoogleTransport.create();
// add default headers
GoogleHeaders defaultHeaders = new GoogleHeaders();
transport.defaultHeaders = defaultHeaders;
transport.defaultHeaders.put("Content-Type", "application/json");
transport.addParser(new JsonHttpParser());
// build the HTTP GET request and URL
HttpRequest request = transport.buildPostRequest();
request.setUrl(GOOGL_URL);
GenericData data = new GenericData();
data.put("longUrl", "http://www.google.com/");
JsonHttpContent content = new JsonHttpContent();
content.data = data;
request.content = content;
HttpResponse response = request.execute();
Result result = response.parseAs(Result.class);
System.out.println(result.shortUrl);
}
public static class Result extends GenericJson {
#Key("id")
public String shortUrl;
}
}
The code given by dwb is correct but it is using deprecated methods of the google client api.
Implementation with current library support is as follows :
import java.util.HashMap;
import java.util.Map;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpContent;
import com.google.api.client.http.HttpHeaders;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.json.JsonHttpContent;
import com.google.api.client.json.GenericJson;
import com.google.api.client.json.JsonObjectParser;
import com.google.api.client.json.jackson.JacksonFactory;
import com.google.api.client.util.Key;
public class ShortenUrl {
/**
* #param args
*/
public static void main(String[] args) throws Exception {
HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
HttpHeaders headers = new HttpHeaders();
JsonObjectParser parser = new JsonObjectParser(new JacksonFactory());
GenericUrl url = new GenericUrl("https://www.googleapis.com/urlshortener/v1/url");
Map<String, String> json = new HashMap<String, String>();
json.put("longUrl", "http://www.google.com/");
final HttpContent content = new JsonHttpContent(new JacksonFactory(), json);
HttpRequest request = httpTransport.createRequestFactory().buildPostRequest(url, content);
try {
HttpResponse response = request.execute();
Result result = response.parseAs(Result.class);
System.out.println(result.shortUrl);
} catch (Exception e) {
e.printStackTrace();
}
}
public static class Result extends GenericJson {
#Key("id")
public String shortUrl;
}
}
Note : You should use your Oauth 2.0 credentials to use google api services.