How can I convert String to HttpInputMessage?
or HttpResponse to HttpInputMessage
Post (return json):
HttpResponse<String> jsonResponse = null;
try {
jsonResponse = Unirest.post(targetURL).header("Accept", "application/json")
.header("Content-Type", "application/json;").body(urlParameters).asString();
} catch (UnirestException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String str = jsonResponse.toString();
HttpInputMessage inputMessage = null;
return inputMessage;
I want convert json to Object
RoutesList routes = new RoutesList();
Post post = new Post(this.url + allRoutes, depoId.toString());
HttpInputMessage inputMessage = null;
try {
inputMessage = post.getResult();
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
converter.read(routes.getClass(), RoutesList.class, inputMessage);
} catch (HttpMessageNotReadableException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
You can wrap the HttpResponse using this class HttpComponentsAsyncClientHttpResponse:
HttpComponentsAsyncClientHttpResponse(HttpResponse httpResponse)
And return it as HttpInputMessag, for example:
return new HttpComponentsAsyncClientHttpResponse(jsonResponse)
this class implement the interface HttpInputMessage.
Related
My actual class accepting URL as input and calling url.openStream(),this should return InputStream.
public static Map<String, Object> parseA(URL url) throws Exception {
byte[] readData = new byte[25*1024*1024];
// Here url.openStream() returning null
InputStream is = url.openStream();
while((readLength = is.read(readData, 0, 25*1024*1024)) != -1){
br = new BufferedReader(new InputStreamReader(new
ByteArrayInputStream(readData)));
// All CW_* strings are collected first
}
My test class is
#Rule
public TemporaryFolder folder= new TemporaryFolder();
#Test(enabled = true)
public void parseATest() {
File file=null;
try {
file =folder.newFile("testingData.txt");
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
final URLConnection mockConnection = EasyMock.createMock(URLConnection.class);
final URLStreamHandler handler = new URLStreamHandler() {
#Override
protected URLConnection openConnection(final URL arg0)
throws IOException {
return mockConnection;
}
};
URL url=null;
try {
url = new URL("http://foo.bar", "foo.bar", 80, "", handler);
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
InputStream is=null;
try {
is = new FileInputStream(file);
} catch (FileNotFoundException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
try {
EasyMock.expect(url.openStream()).andReturn(is).anyTimes();
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
// imageHeaderParser is object of actual class
imageHeaderParser.parseA(url);
} catch (IfmSwimParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Here TemporaryFolder used to create temp file.And I dont want URL to go network.It can be just dummy URL and when i call url.openStream(),it should return stream of temp file i mentioned.
A file can be converted to an URL, so just do that :
Url testUrl = Paths.get("folder",("testingData.txt").toUri().toURL();
Map<String, Object> map = parseA(testUrl);
// assert map content
Besides you don't need any mock if you want to test with the file processing behavior.
I am working on a multi threaded application where i get some request from JMS, threads are running to receive the message. Here how my thread is working:
Model mapper in the try block is causing the issue i think:
patientAdder.addPatient(patientAddMessage, authResult, queueSender, baseUrl, modelMapper);
here is complete code:
Executors.newSingleThreadExecutor().execute(new Runnable() {
public void run() {
while (true) {
SonicQueueMessageSender queueSender = null;
try {
queueSender = new SonicQueueMessageSender(queueConnProvider);
} catch (JMSException e3) {
// TODO Auto-generated catch block
e3.printStackTrace();
}
String patientAddMessage = null;
try {
patientAddMessage = new SonicMessageReceiver(connectionProvider)
.getAddJsonMessage("MirthMessage");
} catch (JMSException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
final AuthModel auth = new AuthModel();
String authResult = null;
final PatientAdder patientAdder = new PatientAdder();
SecurityTokenModel securityToken = null;
String authPostString = null;
try {
authPostString = new ObjectMapper()
.writeValueAsString(auth);
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Auth post string is: "+ authPostString);
System.out.println("base url is: " + baseUrl);
String authPostOutput = client
.doGetAuthRestPost(authPostString, url);
try {
securityToken = getAuth(authPostOutput);
} catch (JsonParseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (JsonMappingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
authResult = securityToken.getAccessToken();
try {
patientAdder.addPatient(patientAddMessage, authResult, queueSender, baseUrl, modelMapper);
} catch (JsonParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JsonMappingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// poster.postMessage(patientAddMessage, authResult);
catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}
}
}
});
I need to map the message i'm getting in request to a bean class and for that i'm creating a ModelMapper class object that has a function to map properties but when i try to create new object of my mapper class i'm getting a NPE:
Exception in thread "pool-1-thread-1" java.lang.NullPointerException
at com.prnreferral.util.commons.ModelMapper.mapCanonicalMessageToPatientModel(ModelMapper.java:82)
at com.prnreferral.patientprocess.add.PatientAdder.addPatient(PatientAdder.java:52)
at com.prnreferral.patientprocess.add.PIXSAddPatient$1.run(PIXSAddPatient.java:148)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
at java.lang.Thread.run(Thread.java:722)
I'm sure that object is created as i checked it by adding some conditions, but there is something that i'm missing causing this issue
I also tried to add a new function to check if there is any issue with this function, but getting
Exception in thread "pool-1-thread-1" java.lang.NoSuchMethodError: com.prnreferral.util.commons.ModelMapper.printString()V
at com.prnreferral.patientprocess.add.PatientAdder.addPatient(PatientAdder.java:49)
at com.prnreferral.patientprocess.add.PIXSAddPatient$2.run(PIXSAddPatient.java:173)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
at java.lang.Thread.run(Thread.java:722)
I'm stuck on this issue, no idea what to do, can anyone help me. Thanks in advance.
I am currently writing a client to access rest service, the server rest call accepts one parameter of type java object with #BeanParam annotated.
How do i send data from Apache HTTP client to achieve this.
Below is my server and client code
Server code
#Override
#POST
#Path("/generate_verify_otp/{issuername}")
#Produces("application/x-www-form-urlencoded")
#Consumes("application/x-www-form-urlencoded")
public MultivaluedMap<String, Object> generateVerifyOTP(#BeanParam QPayOTPRequest qpayOTPRequest, #PathParam("issuername")) {
some business logic
}
Client code
public void getOtp(HttpServletRequest request){
QPayOTPRequest qpayOTPRequest = formatDataForOtp(request);
StringWriter writer = new StringWriter();
JsonGenerator jgen;
try {
jgen = new JsonFactory().createJsonGenerator(writer);
jgen.setCodec(new ObjectMapper());
jgen.writeObject(qpayOTPRequest);
jgen.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(writer.toString());
String url = "sdfghjklfghjk;
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
try {
HttpPost post = new HttpPost(url);
StringEntity entiry = new StringEntity(writer.toString());
post.addHeader("content-type", "application/x-www-form-urlencoded");
post.setEntity(entiry);
HttpResponse response = httpClient.execute(post);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
How to i send parameters from client so that it maps to #beanparam object.
I'm trying to parse json (steam webchat) which looks like that (I've changed response cause I don't wanna show the data):
/**/({
"pollid": 00,
"messages": [
{
"type": "personastate",
"timestamp": 0000000000,
"utc_timestamp": 000000000,
"steamid_from": "000000000000",
"status_flags": 0000000,
"persona_state": 0,
"persona_name": "asd"
}
]
,
"messagelast": 00,
"timestamp": 0000000000,
"utc_timestamp": 000000000000,
"messagebase": 00,
"sectimeout": 0,
"error": "OK"
})
And my parsing class looks like that:
package jsonRequest;
import java.io.IOException;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
public class NewMessageJson {
public Integer poollid;
private String lastMessageId;
private String error;
private String messageBase;
public NewMessageJson(String response) {
response = response.substring(response.indexOf("{"),
response.indexOf("}") + 1); // cut off comment block
JsonFactory factory = new JsonFactory();
JsonParser jp = null;
try {
jp = factory.createJsonParser(response);
} catch (JsonParseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
if (jp.nextToken() != JsonToken.START_OBJECT) {
throw new IOException("Server didn't return any data");
}
while (jp.nextToken() != JsonToken.END_OBJECT) {
String fieldName = jp.getCurrentName();
jp.nextToken();
if (fieldName.equals("messagelast")) {
setLastMessageId(jp.getText());
} else if (fieldName.equals("pollid")) {
setPoollid(jp.getIntValue());
} else if (fieldName.equals("messagebase")) {
setMessageBase(jp.getText());
} else if (fieldName.equals("error")) {
setError(jp.getText());
}
}
jp.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NullPointerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
jp.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public Integer getPoollid() {
return poollid;
}
public void setPoollid(Integer poollid) {
this.poollid = poollid;
}
public String getLastMessageId() {
return lastMessageId;
}
public void setLastMessageId(String lastMessageId) {
this.lastMessageId = lastMessageId;
}
public String getError() {
return error;
}
public void setError(String error) {
this.error = error;
}
public String getMessageBase() {
return messageBase;
}
public void setMessageBase(String messageBase) {
this.messageBase = messageBase;
}
}
And when it comes to the line
if (fieldName.equals("messagelast")) {
It crashes and returns NPE.
I have 3 other classes looking exactly like this one and everything works perfectly.
I am pretty sure the reason you are getting the NPE is because you initially instantiate JsonParser jp as null. You assign it to factory.createJsonParser(response) in your try block but do not deal with the error in any way besides printing the stack trace. If there was an error executing factory.createJsonParser(response), you need to make sure nothing else runs.
I would suggest changing your code to this:
...
JsonFactory factory = new JsonFactory();
JsonParser jp = null;
try {
jp = factory.createJsonParser(response);
} catch (JsonParseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
System.out.println("There was an error while setting jp to factory.createJsonParser(response). Error message is: " + e1.getMessage());
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
System.out.println("There was an error while setting jp to factory.createJsonParser(response). Error message is: " + e1.getMessage());
}
if(jp != null) {
try {
if (jp.nextToken() != JsonToken.START_OBJECT) {
throw new IOException("Server didn't return any data");
}
while (jp.nextToken() != JsonToken.END_OBJECT) {
String fieldName = jp.getCurrentName();
jp.nextToken();
if (fieldName.equals("messagelast")) {
setLastMessageId(jp.getText());
} else if (fieldName.equals("pollid")) {
setPoollid(jp.getIntValue());
} else if (fieldName.equals("messagebase")) {
setMessageBase(jp.getText());
} else if (fieldName.equals("error")) {
setError(jp.getText());
}
}
jp.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NullPointerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
jp.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
...
This way, you can avoid all NPEs!
EDIT: You should also implement what peeskillet suggested
I have a response String from an API service like this :
{"id":"login","status":"true"}
and This is the way to parse Response String to get Value from Key "Status"
JSONObject jsonObj = null;
try{
jsonObj = new JSONObject(responseString);
}
catch(JSONException e){
e.printStackTrace();
}
JSONArray innerJsonArray = null;
try {
innerJsonArray = jsonObj.getJSONArray("status");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JSONObject jsonObject = null;
try {
jsonObject = innerJsonArray.getJSONObject(0);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
System.out.println(jsonObject.getString("status"));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
and I've got error
"org.json.JSONArray cannot be converted to JSONObject"
Anyone can give me suggestion?
JSONObject jsonObj = null;
try{
jsonObj = new JSONObject(responseString);
System.out.println(jsonObj.getString("status"));
}
catch(JSONException e){
e.printStackTrace();
}
You do not need to bother with any other arrays.
In which line you get the exception ? In any way may be you should use
jsonObj =JSONObject.fromObject(responseString);
Kindly try the snippet code below. Try this link for gaining better knowledge about parsing an JSON response.
JSONObject jObj;
try {
jObj = new JSONObject(responseString);
Log.i("id==", jObj.getString("id"));
Log.i("status==", jObj.getString("status"));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}