How to convert soap response to string in java? - java

I am using WebServiceTemplate to consume SOAP response. For logging purpose i need to get the SOAP response in string.
For example , "<envelope><body><name>xyz</name></body></envelope>"

You can achive it like below with WebServiceTemplate:
ByteArrayOutputStream bytArrayOutputStream = new ByteArrayOutputStream();
StreamResult result = new StreamResult(bytArrayOutputStream);
wsTemplate.sendSourceAndReceiveToResult(defautUri, source, result);
final String reply = new String(bytArrayOutputStream.toByteArray())

If you using spring, you can add log using log4j in interceptor. Log4j can write to file or even db. I hope its help you.

Related

In java 9 how to send JSON data through websocket

In Java 9 new features are added and one of them is WebSocket, I have found articles related to sending text(string)/binary messages only. So, how to send JSON data over websocket using Java 9.
You can treat JSON similar to text. just deserialize it and send it as a plain text.
Write your data in StringWriter
StringWriter writer = new StringWriter();
ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(writer, object);
String jsonText = writer.toString;
Now you have a String with your JSON.

Traffic Junky API usage in Java and sample code

Can anyone tell me about Traffic Junky API. Can I use it with Java?
http://api.trafficjunky.com/api/doc/
A web based API does not depend on a specific language. You can use it in any language.
APIs have endpoints which you can use. Some have JSON, XML and other endpoints.
https://api.trafficjunky.com/api/doc/
There is also a sandbox feature in the documentation.
You can use it to see how the query has to look like.
This gives a hint that the api_key parameter can be used for the API key:
https://api.trafficjunky.com/api/campaigns/stats.json?api_key=123
Maybe you can also define the api_key parameter using the header fields. Just insert your API details and test it using the sandbox.
Making API calls in Java should be easy using the URLConnection class or some library like Apache Commons HttpComponents https://hc.apache.org/ and some JSON library like json-simple, gson and Jackson.
Just some example code without using a library:
String api_key = "123";
HttpsURLConnection conn4 = (HttpsURLConnection)(new URL("https://api.trafficjunky.com/api/campaigns/stats.json?api_key="+api_key).openConnection());
conn4.setConnectTimeout(60000); // you may not need this or just a lower value
conn4.setReadTimeout(60000); // you may not need this or just a lower value
conn4.connect();
InputStream in = conn4.getInputStream();
InputStreamReader is3 = new InputStreamReader(in);
StringBuilder sb2=new StringBuilder();
BufferedReader br2 = new BufferedReader(is3);
String read2 = br2.readLine();
while(read2 != null) {
sb2.append(read2);
read2 =br2.readLine();
}
String json_string = sb2.toString();
// do something with the result in json_string, better use some JSON library

How to transform java object to XML with axis 1.4?

We are using axis 1.4 for our WS implementation.
Whenever the WS request fails we would like to add to our logging the XML of the actual request that was sent.
To do that we of course need to be able to transform the request object into its XML representation, same as it will be sent later to the server.
In most cases this is to be able later copy-paste it to some other tool, for debug, so it is important to have exactly same XML string as it would be sent to the server.
Hope that was clear enough.
Thank you.
OK, answering my own question:
To do so for Axis-1.4, according to the example posted by NJSC, need to replace SerializationContextImpl with just a org.apache.axis.encoding.SerializationContext.
qname = removeNamespaces ? new QName(lname) : new QName(qname.getNamespaceURI(), lname);
final AxisServer server = new AxisServer();
final BeanSerializer ser = new BeanSerializer(obj.getClass(), qname, typeDesc);
final SerializationContext ctx = new SerializationContext(outStr, new MessageContext(server));
ctx.setSendDecl(false);
ctx.setDoMultiRefs(false);
ctx.setPretty(prettyPrint);

ClientProtocolException when calling createAttachment using Ektorp to interface with CouchDB

I am using Ektorp (Java API for CouchDB) to store documents in my CouchDB instance. I am having trouble attaching images to documents. Every time I call createAttachment() it throws an ClientProtocolException.
Code Sample:
AttachmentInputStream attachment =
new AttachmentInputStream(attachmentId,
fileInputStream,
contentType,
file.length());
String rev = db.createAttachment(doc.getId(), attachment));
Does anyone know what's going wrong?
I had a similar problem using Ektorp. I resolved the issue by passing the latest revision number into the overloaded createAttachment method (db.createAttachment(doc.getId(), doc.getRevision(), attachment))). You could probably do the following:
AttachmentInputStream attachment =
new AttachmentInputStream(attachmentId,
fileInputStream,
contentType,
file.length());
String rev = db.createAttachment(doc.getId(), doc.getRevision(), attachment));
Good luck!

In httpclient what is the most elegant/correct way to turn HttpEntity to a String?

I'm fetching a web page using the Apache httpcomponents Java library. After connecting the result I get is an HttpEntity which has a method getContent() which returns an InputStream and also has a method writeTo() which writes to an OutputStream.
I want to turn the result into a String for extracting information. What is the most elegant (and safe) way to do this?
Some possible solutions:
Write to a ByteArrayOutputStream and then convert those bytes to a String with a String constructor
use InputStreamReader to read straight from the stream, and put into a StringBuilder
Both of these feel a bit ugly. Would you recommend choosing one of these or something else?
System.out.println( EntityUtils.toString(httpResponse.getEntity()) );
What about (pseudo):
BasicResponseHandler handler = new org.apache.http.impl.client.BasicResponseHandler ();
String str = httpClient.execute(request, handler);
You would have to handle exceptions on your own in this case.
It may be ugly, but I think that's the only way to do it. You can use IOUtils.toString() from Commons-IO though without having to write your own code.

Categories