I have some Java code that takes an XML (SOAP) message and returns the deserialized object:
public static <T> T deserializeObject(String xml, Class<T> clazz) throws AxisFault, Exception {
assert xml != null : "xml != null";
assert clazz != null : "clazz != null";
T result = null;
try {
Message message = new Message(SOAP_START + xml + SOAP_END);
result = (T)message.getSOAPEnvelope().getFirstBody().getObjectValue(clazz);
} catch (Exception e) {
// most likely namespace error due to removed namespaces
Message message = new Message(SOAP_START_XSI + xml + SOAP_END);
result = (T)message.getSOAPEnvelope().getFirstBody().getObjectValue(clazz);
}
return result;
}
However this code only works with Axis 1.4 :-( Could someone Help me have that code work with Axis 2?
In fact, I might just need to know what to replace the import org.apache.axis.Message with?
Thanks in advance.
Every message within the Axis2 engine is wrapped inside a MessageContext object. When a SOAP message arrives into the system or is prepared to be sent out, we create an AXIOM object model of the SOAP message.
(Please read the AXIOM article series for more information on AXIOM). This AXIOM model is then included inside the message context object. Let's see how to access this SOAP message inside Axis2.
// if you are within a handler, reference to the message context
MessageContext messageContext;
object will be passed to you through Handler.invoke(MessageContext) method.
SOAPEnvelope soapEnvelope = messageContext.getEnvelope();
please see :
javax.xml.soap
Interface SOAPEnvelope
Processing Axis2 message
Related
I'm new to Java and to backend development, and I really could use some help.
I am currently using Vert.x to develop a server that takes in a Json request that tells this server which file to analyze, and the server analyzes the file and gives a response in a Json format.
I have created an ImageRecognition class where there is a method called "getNum" which gets a json as an input and outputs a json containing the result.
But I am currently having trouble getting the Json file from the request.
public void start(Promise<Void> startPromise) throws Exception {
JsonObject reqJo = new JsonObject();
Router router = Router.router(vertx);
router.get("/getCall").handler(req ->{
JsonObject subJson = req.getBodyAsJson();
reqJo.put("name", subJson.getValue("name"));
req.end(reqJo.encodePrettily());
});
router.post("/getCall").produces("*/json").handler(plateReq ->{
plateReq.response().putHeader("content-tpye", "application/json");
JsonObject num = imageRecogService.getNum(reqJo);
plateReq.end(num.encodePrettily());
});
vertx.createHttpServer().requestHandler(router).listen(8080)
.onSuccess(ok -> {
log.info("http server running on port 8080");
startPromise.complete();
})
.onFailure(startPromise::fail);
}
}
Any feedback or solution to the code would be deeply appreciated!!
Thank you in advance!!
You have several errors in your code:
1:
JsonObject reqJo = new JsonObject();
Router router = Router.router(vertx);
router.get("/getCall").handler(req ->{
reqJo.put("name", subJson.getValue("name"));
});
You are modifying the reqJo object in handlers. I am not sure if this is thread safe, but a more common practice is to allocate the JsonObject object inside of request handlers and pass them to consequent handlers using RoutingContext.data().
2:
Your two handlers are not on the same method (the first one is GET, while the second is POST). I assume you want them both be POST.
3:
In order to extract multipart body data, you need to use POST, not GET.
4:
You need to append a BodyHandler before any of your handlers that reads the request body. For example:
// Important!
router.post("/getCall").handler(BodyHandler.create());
// I changed to posts
router.post("/getCall").handler(req ->{
JsonObject subJson = req.getBodyAsJson();
reqJo.put("name", subJson.getValue("name"));
req.end(reqJo.encodePrettily());
});
Otherwise, getBodyAsJson() will return null.
According to the Document of RoutingContext#getBodyAsJson, "the context must have first been routed to a BodyHandler for this to be populated."
Read more: BodyHandler.
I am implementing invoking of a soap web service in java
I have a wsdl file that I have imported using the embedded wsdl2java in axis2
then I was able to call the web service and it is working fine
util the size of the request exceed a 30 mega in size
the output request consist of the following parameters:
<param1>some value</param1>
<array>
recored1
recored2
.
.
.
</array>
I was able to send 500000 recodes but when exceed this number I stuck in getting "java heap space error"
question is is there any way to send the soap request in small chunks ...and does importing the WSDL using xmlbeans affect the performance
for rest APIs I was able to add transfer encoding for chunk and provide the body of it in small chunks but for soap services I found no solutions, please if there is any example of that I will be grateful.. thanks in advance
Streaming one transaction require all pipeline involved steps are in a streaming fashion. If one of them collapse the stream (i.e. myStream.collect(toList())) then, the streaming process will be broken and, at that point, all the input stream will be into memory (maybe filtered, reducted, ...).
In general, to process a XML input in a streaming fashion (under axis2) you could use Axiom, a simple example to process in streaming is (from here):
public void processFragments(InputStream in) throws XMLStreamException {
// Create an XMLStreamReader without building the object model
XMLStreamReader reader =
OMXMLBuilderFactory.createOMBuilder(in).getDocument().getXMLStreamReader(false);
while (reader.hasNext()) {
if (reader.getEventType() == XMLStreamReader.START_ELEMENT &&
reader.getName().equals(new QName("tag"))) {
// A matching START_ELEMENT event was found. Build a corresponding OMElement.
OMElement element =
OMXMLBuilderFactory.createStAXOMBuilder(reader).getDocumentElement();
// Make sure that all events belonging to the element are consumed so
// that the XMLStreamReader points to a well defined location (namely the
// event immediately following the END_ELEMENT event).
element.build();
// Now process the element.
processFragment(element);
} else {
reader.next();
}
}
}
Although you can open a HTTP stream and use this snippet, unfortunately translate it to your autogenerated client is not easy.
Create an AXIOM client is much less comfortable since you must to deal with AXIOM objects, from the documentation:
private static EndpointReference targetEPR =
new EndpointReference("http://localhost:8080/axis2/services/StockQuoteService");
public static OMElement getPricePayload(String symbol) {
OMFactory fac = OMAbstractFactory.getOMFactory();
OMNamespace omNs = fac.createOMNamespace("http://axiom.service.quickstart.samples/xsd", "tns");
OMElement method = fac.createOMElement("getPrice", omNs);
OMElement value = fac.createOMElement("symbol", omNs);
value.addChild(fac.createOMText(value, symbol));
method.addChild(value);
return method;
}
public static OMElement updatePayload(String symbol, double price) {
OMFactory fac = OMAbstractFactory.getOMFactory();
OMNamespace omNs = fac.createOMNamespace("http://axiom.service.quickstart.samples/xsd", "tns");
OMElement method = fac.createOMElement("update", omNs);
OMElement value1 = fac.createOMElement("symbol", omNs);
value1.addChild(fac.createOMText(value1, symbol));
method.addChild(value1);
OMElement value2 = fac.createOMElement("price", omNs);
value2.addChild(fac.createOMText(value2,
Double.toString(price)));
method.addChild(value2);
return method;
}
public static void main(String[] args) {
try {
OMElement getPricePayload = getPricePayload("WSO");
OMElement updatePayload = updatePayload("WSO", 123.42);
Options options = new Options();
options.setTo(targetEPR);
options.setTransportInProtocol(Constants.TRANSPORT_HTTP);
ServiceClient sender = new ServiceClient();
sender.setOptions(options);
sender.fireAndForget(updatePayload);
System.err.println("price updated");
OMElement result = sender.sendReceive(getPricePayload);
String response = result.getFirstElement().getText();
System.err.println("Current price of WSO: " + response);
} catch (Exception e) {
e.printStackTrace();
}
}
then you can digest the response in a streaming fashion way:
result.getFirstElement().getText()
if your WSDL definition is complex may be suitable write an AXIOM client only for big transactions but if you can split the call will be a much better approach.
I'm trying to create a dynamic Rest client, where I can set the HTTP Method(GET-POST-PUT-DELETE), Query Params and body(Json, plain, XML), this is basically what I need, for the request I think i know how I can do it, but my concern is for reading the answer, since I know what I should get ( format) but I dont know how to read it properly, so far I return an object, below the code (only for POST, but the idea is the same):
Response responseRest = null;
Client client = null;
try {
client = new ResteasyClientBuilder().establishConnectionTimeout(TIME_OUT, TimeUnit.MILLISECONDS).socketTimeout(TIME_OUT, TimeUnit.MILLISECONDS).build();
WebTarget target = client.target(request.getUrlTarget());
MediaType type = assignResponseType(request.getTypeResponse());
switch (request.getProtocol()) {
case POST: {
if (request.getParamQuery() != null) {
for (VarRequestDTO varRequest : request.getParamQuery()) {
target = target.queryParam(varRequest.getName(), varRequest.getValue());
}
}
responseRest = target.request().post(Entity.entity(new ResponseWrapper(), type));
break;
}
default:
//HTTP METHOD No supported
}
Object result = responseRest.readEntity(Object.class);
}
catch (Exception e) {
response.setError(Boolean.TRUE);
response.setMessage(e.getMessage());
e.printStackTrace();
} finally {
if (responseRest != null) {
responseRest.close();
}
if (client != null) {
client.close();
}
}
What I basically I need is to return the object in the format needed, and where is called it's supposed to do a cast to the correct format, I just need it to be dynamic and used for any service.
Thanks
Every request that a ReST client makes to a ReST service, it passes an "Accept" header.
This is to indicate to the service the MIME-type of the resource the client is willing to accept.
In the above case, what are the acceptable formats (json/ plain text/ etc.) for you?
Depending on the "accept" format you choose, and the "Content-type" header that you receive, you can write a deserializer to accept that data and process.
Also, instead of returning an Object which is too generic, consider returning a readable Stream to the caller.
I'm looking at the HttpStaticFileServerHandler example at Netty Github. On messageRecieved, if the decoder result is not success, bad request is thrown. So the response code goes as 400. I would like to send 414 when the request uri is too long.
I've tried,
Throwable cause = requestMessage.getDecoderResult().cause();
String message = cause != null ? cause.getMessage() : "";
HttpResponseStatus responseStatus = cause instanceof TooLongFrameException?
HttpResponseStatus.REQUEST_URI_TOO_LONG : HttpResponseStatus.BAD_REQUEST;
Is there a better way? I believe TooLongFrameException is thrown for other cases as well. So in those cases it may not be right. Parsing the error message also doesn't look good. Wondering if this can be done in a better/elegant way.
A bit further down in that handler is the code block:
final String uri = request.uri();
final String path = sanitizeUri(uri);
if (path == null) {
sendError(ctx, FORBIDDEN);
return;
}
Could you use this block with a uri.length() check and relevant sendError?
This may be one of the insane / stupid / dumb / lengthy questions as I am newbie to web services.
I want to write a web service which will return answer in XML format (I am using my service for YUI autocomplete). I am using Eclipse and Axis2 and following http://www.softwareagility.gr/index.php?q=node/21
I want response in following format
<codes>
<code value="Pegfilgrastim"/>
<code value="Peggs"/>
<code value="Peggy"/>
<code value="Peginterferon alfa-2 b"/>
<code value="Pegram"/>
</codes>
Number of code elements may vary depending on response.
Till now I tried following ways
1) Create XML using String buffer and return the string.(I am providing partial code to avoid confusion)
public String myService ()
{
// Some other stuff
StringBuffer outputXML = new StringBuffer();
outputXML.append("<?xml version='1.0' standalone='yes'?>");
outputXML.append("<codes>");
while(SOME_CONDITION)
{
// Some business logic
outputXML.append("<code value=\""+tempStr+"\">"+"</code>");
}
outputXML.append("</codes>");
return (outputXML.toString());
}
It gives following response with unwanted <ns:myServiceResponse> and <ns:return> element.
<ns:myServiceResponse>
<ns:return>
<?xml version='1.0' standalone='yes'?><codes><code value="Peg-shaped teeth"></code><code value="Pegaspargase"></code><code value="Pegfilgrastim"></code><code value="Peggs"></code><code value="Peggy"></code><code value="Peginterferon alfa-2 b"></code><code value="Pegram"></code></codes>
</ns:return>
</ns:findTermsResponse>
But it didnt work with YUI autocomplete (May be because it required response in format mentioned above)
2) Using DocumentBuilderFactory :
Like
public Element myService ()
{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = factory.newDocumentBuilder();
Document doc = docBuilder.newDocument();
Element codes = doc.createElement("codes");
while(SOME_CONDITION)
{
// Some business logic
Element code = doc.createElement("code");
code.setAttribute("value", tempStr);
codes.appendChild(code);
}
return(codes);
}
Got following error
org.apache.axis2.AxisFault: Mapping qname not fond for the package: com.sun.org.apache.xerces.internal.dom
3) Using servlet : I tried to get same response using simple servlet and it worked. Here is my servlet
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
StringBuffer outputXML = new StringBuffer();
response.setContentType("text/xml");
PrintWriter out = response.getWriter();
outputXML.append("<?xml version='1.0' standalone='yes'?>");
outputXML.append("<codes>");
while(SOME_CONDITION)
{
// Some business logic
outputXML.append("<code value=\"" + tempStr + "\">" + "</code>");
}
outputXML.append("</codes>");
out.println(outputXML.toString());
}
It gave response same as mentioned above and it worked with YUI autocomplete without any extra tag.
Please can you tell how can I get XML response without any unwanted elements ?
Thanks.
Axis2 is for delivering Objects back to the caller. Thats why it adds extra stuff to the response even it is a simple String object.
Using the second approach your service returns a complex Java object (Element instance) that is for describing an XML fragment. This way the caller has to be aware of this object to be able to deserialize it and restore the Java object that contains XML data.
The third approach is the simplest and best in your case regarding the return type: it doesn't return a serialized Java object, only the plain xml text. Of course you could use DocumentBuilder to prepare the XML, but in the end you have to make String of it by calling the appropriate getXml(), asXml() method (or kind of...)
Finally got it work though I am not able to remove unwanted element. (I don't bother till all things are in place). I used AXIOM to generate response.
public OMElement myService ()
{
OMFactory fac = OMAbstractFactory.getOMFactory();
OMNamespace omNs = fac.createOMNamespace("", "");
OMElement codes = fac.createOMElement("codes", omNs);
while(SOME_CONDITION)
{
OMElement code = fac.createOMElement("code", null, codes);
OMAttribute value = fac.createOMAttribute("value", null, tempStr);
code.addAttribute(value);
}
return(codes);
}
Links : 1) http://songcuulong.com/public/html/webservice/create_ws.html
2) http://sv.tomicom.ac.jp/~koba/axis2-1.3/docs/xdocs/1_3/rest-ws.html
I think you cannot return your custom xml with Axis. It will wrap it into its envelope anyways.