Java SAAJ memory leak - java

I have a developED a REST Api with Java and one of the service needs to make a SOAP call to an endpoint. For this I implemented SAAJ client to create the whole xml message. However each time a call consume extra 1 MB of memory.
import javax.xml.soap.*;import javax.xml.transform.* import javax.xml.transform.stream.*;
public class SOAPClientSAAJ {
public void makeCall() {
try {
// Create SOAP Connection
SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
SOAPConnection soapConnection = soapConnectionFactory.createConnection();
// Send SOAP Message to SOAP Server
String url = "http://ws.cdyne.com/emailverify/Emailvernotestemail.asmx";
SOAPMessage soapResponse = soapConnection.call(createSOAPRequest(), url);
// Process the SOAP Response
printSOAPResponse(soapResponse);
soapConnection.close();
} catch (Exception e) {
System.err.println("Error occurred while sending SOAP Request to Server");
e.printStackTrace();
}
}
private static SOAPMessage createSOAPRequest() throws Exception {
MessageFactory messageFactory = MessageFactory.newInstance();
SOAPMessage soapMessage = messageFactory.createMessage();
SOAPPart soapPart = soapMessage.getSOAPPart();
String serverURI = "http://ws.cdyne.com/";
// SOAP Envelope
SOAPEnvelope envelope = soapPart.getEnvelope();
envelope.addNamespaceDeclaration("example", serverURI);
// SOAP Body
SOAPBody soapBody = envelope.getBody();
SOAPElement soapBodyElem = soapBody.addChildElement("VerifyEmail", "example");
SOAPElement soapBodyElem1 = soapBodyElem.addChildElement("email", "example");
soapBodyElem1.addTextNode("mutantninja#gmail.com");
SOAPElement soapBodyElem2 = soapBodyElem.addChildElement("LicenseKey", "example");
soapBodyElem2.addTextNode("123");
MimeHeaders headers = soapMessage.getMimeHeaders();
headers.addHeader("SOAPAction", serverURI + "VerifyEmail");
soapMessage.saveChanges();
/* Print the request message */
System.out.print("Request SOAP Message = ");
soapMessage.writeTo(System.out);
System.out.println();
return soapMessage;
}
/**
* Method used to print the SOAP Response
*/
private static void printSOAPResponse(SOAPMessage soapResponse) throws Exception {
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
Source sourceContent = soapResponse.getSOAPPart().getContent();
System.out.print("\nResponse SOAP Message = ");
StreamResult result = new StreamResult(System.out);
transformer.transform(sourceContent, result);
}}
When a call this SOAP service in my rest object and run piece of memory detector ;
public void restService(){
SOAPClientSAAJ test= new SOAPClientSAAJ();
test.makeCall();
Runtime runtime = Runtime.getRuntime();
runtime.gc();
long memory = runtime.totalMemory() - runtime.freeMemory();
System.out.println("Used memory is bytes: " + memory);
}
It shows each call consume 1 MB memory and at the end the Rest application crush. I debug it many times and saw that SOAPMessage soapResponse = soapConnection.call(createSOAPRequest(), url); this part highly is the cause of the leak but I couldn't find a solution. Any help about that would be great.

Related

SAAJ java client - add authentication

i'm making a webservice client with SAAJ java.
I'n the client i ask info of the webservice. But the webservice is protected with a username and password.
And i don't no how i must add these 2.
I tried it in my code ( see commands ) but no results ..
// SAAJ - SOAP Client Testing
public static void main(String args[]) {
String soapEndpointUrl = "https://gtstvs01:8443/aeosws";
String soapAction = "";
callSoapWebService(soapEndpointUrl, soapAction);
}
private static void createSoapEnvelope(SOAPMessage soapMessage) throws SOAPException {
SOAPPart soapPart = soapMessage.getSOAPPart();
String myNamespace = "sch";
String myNamespaceURI = "http://www.nedap.com/aeosws/schema";
// SOAP Envelope
SOAPEnvelope envelope = soapPart.getEnvelope();
envelope.addNamespaceDeclaration(myNamespace, myNamespaceURI);
//SOAPFactory soapFactory = SOAPFactory.newInstance();
// SOAPElement authHeaderElement = soapFactory.createElement("AuthenticationHeader", "administrator", "aeosrules");
//SOAPElement sessionIdElement = soapFactory.createElement("SessionID", "nsprefix", "nsuri");
//sessionIdElement.addTextNode(MY_SESSION_ID);
//authHeaderElement.addChildElement(sessionIdElement);
//SOAPHeader soapHeader = envelope.addHeader();
//soapHeader.addChildElement(authHeaderElement);
// SOAP Body
SOAPBody soapBody = envelope.getBody();
SOAPElement soapBodyElem = soapBody.addChildElement("EmployeeSearchInfo", myNamespace);
SOAPElement soapBodyElem1 = soapBodyElem.addChildElement("EmployeeInfo", myNamespace);
SOAPElement soapBodyElem2 = soapBodyElem1.addChildElement("FirstName", myNamespace);
soapBodyElem2.addTextNode("Jens");
}
private static void callSoapWebService(String soapEndpointUrl, String soapAction) {
try {
// Create SOAP Connection
SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
SOAPConnection soapConnection = soapConnectionFactory.createConnection();
// Send SOAP Message to SOAP Server
SOAPMessage soapResponse = soapConnection.call(createSOAPRequest(soapAction), soapEndpointUrl);
// Print the SOAP Response
System.out.println("Response SOAP Message:");
soapResponse.writeTo(System.out);
System.out.println();
soapConnection.close();
} catch (Exception e) {
System.err.println("\nError occurred while sending SOAP Request to Server!\nMake sure you have the correct endpoint URL and SOAPAction!\n");
e.printStackTrace();
}
}
private static SOAPMessage createSOAPRequest(String soapAction) throws Exception {
MessageFactory messageFactory = MessageFactory.newInstance();
SOAPMessage soapMessage = messageFactory.createMessage();
createSoapEnvelope(soapMessage);
MimeHeaders headers = soapMessage.getMimeHeaders();
headers.addHeader("SOAPAction", soapAction);
soapMessage.saveChanges();
/* Print the request message, just for debugging purposes */
System.out.println("Request SOAP Message:");
soapMessage.writeTo(System.out);
System.out.println("\n");
return soapMessage;
}
From what I understand, you have to add it to the header.
In your code for CreateSoapRequest you need 3 additional lines.
MimeHeaders headers = soapMessage.getMimeHeaders();
String encoded = new sun.misc.BASE64Encoder().encode((username+":"+password).getBytes());
String authString = "Basic " + encoded;
headers.addHeader("Authorization", authString);
headers.addHeader("SOAPAction", soapAction);
I think it matters what type of encoding the site has. So this probably won't work in a cut and paste you have to figure out what it requires.

Adding content to soap message(basic)

The code below is what I have been using to understand the concept of soap messages etc. However, in this code there are 2 lines which state-
MimeHeaders headers = soapMessage.getMimeHeaders();
headers.addHeader("SOAPAction", serverURI + "VerifyEmail");
Why is this not viewable when printed? Also I would like to add the header "<?xml version="1.0" encoding="utf-8"?>" How can this be done? and how can I get the entire output/view of what it looks like sent. Header and everything? Thank You.
import javax.xml.soap.*;
import javax.xml.transform.*;
import javax.xml.transform.stream.*;
public class SOAPClientSAAJ {
/**
* Starting point for the SAAJ - SOAP Client Testing
*/
public static void main(String args[]) {
try {
// Create SOAP Connection
SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
SOAPConnection soapConnection = soapConnectionFactory.createConnection();
// Send SOAP Message to SOAP Server
String url = "http://ws.cdyne.com/emailverify/Emailvernotestemail.asmx";
SOAPMessage soapResponse = soapConnection.call(createSOAPRequest(), url);
// Process the SOAP Response
printSOAPResponse(soapResponse);
soapConnection.close();
} catch (Exception e) {
System.err.println("Error occurred while sending SOAP Request to Server");
e.printStackTrace();
}
}
private static SOAPMessage createSOAPRequest() throws Exception {
MessageFactory messageFactory = MessageFactory.newInstance();
SOAPMessage soapMessage = messageFactory.createMessage();
SOAPPart soapPart = soapMessage.getSOAPPart();
String serverURI = "http://ws.cdyne.com/";
// SOAP Envelope
SOAPEnvelope envelope = soapPart.getEnvelope();
envelope.addNamespaceDeclaration("example", serverURI);
/*
Constructed SOAP Request Message:
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:example="http://ws.cdyne.com/">
<SOAP-ENV:Header/>
<SOAP-ENV:Body>
<example:VerifyEmail>
<example:email>mutantninja#gmail.com</example:email>
<example:LicenseKey>123</example:LicenseKey>
</example:VerifyEmail>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
*/
// SOAP Body
SOAPBody soapBody = envelope.getBody();
SOAPElement soapBodyElem = soapBody.addChildElement("VerifyEmail", "example");
SOAPElement soapBodyElem1 = soapBodyElem.addChildElement("email", "example");
soapBodyElem1.addTextNode("mutantninja#gmail.com");
SOAPElement soapBodyElem2 = soapBodyElem.addChildElement("LicenseKey", "example");
soapBodyElem2.addTextNode("123");
MimeHeaders headers = soapMessage.getMimeHeaders();
headers.addHeader("SOAPAction", serverURI + "VerifyEmail");
soapMessage.saveChanges();
/* Print the request message */
System.out.print("Request SOAP Message = ");
soapMessage.writeTo(System.out);
System.out.println();
return soapMessage;
}
/**
* Method used to print the SOAP Response
*/
private static void printSOAPResponse(SOAPMessage soapResponse) throws Exception {
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
Source sourceContent = soapResponse.getSOAPPart().getContent();
System.out.print("\nResponse SOAP Message = ");
StreamResult result = new StreamResult(System.out);
transformer.transform(sourceContent, result);
}
}
I'm not certain whether or not there is a way to print them directly from DOM or SOAP, but you can parse out the values and print them separately:
SOAPHeader header = message.getSOAPHeader();
if (header == null) {
// Throw an exception
}
NodeList headerPartNode = header.getChildNodes();
String headerPart = headerPartNode.item(0).getChildNodes().item(0).getNodeValue();
You can iterate over that NodeList, parse out each header part, and then print them individually for example.

how sent soap request with parameter to server via java

I need to send following soap request on server:
<CallengeState xmlns="http://app.test.com/ws/schema">
<number>0008</number>
<previousState>Stopped</previousState>
<currentState>Activated</currentState>
<dateChanged>2014-06-09</dateChanged>
</CallengeState >
I know how to do it via Soap Ui, but I need to do this via java. In Soap UI I also specify additional parameter, here is screenshot:
I have found in google and tried following:
package com.oberthur.tests.util;
import javax.xml.soap.*;
import javax.xml.transform.*;
import javax.xml.transform.stream.*;
public class SOAPClientSAAJ {
/**
* Starting point for the SAAJ - SOAP Client Testing
*/
public static void main(String args[]) {
try {
// Create SOAP Connection
SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
SOAPConnection soapConnection = soapConnectionFactory.createConnection();
// Send SOAP Message to SOAP Server
String url = "myserver";
SOAPMessage soapResponse = soapConnection.call(createSOAPRequest(), url);
// Process the SOAP Response
printSOAPResponse(soapResponse);
soapConnection.close();
} catch (Exception e) {
System.err.println("Error occurred while sending SOAP Request to Server");
e.printStackTrace();
}
}
private static SOAPMessage createSOAPRequest() throws Exception {
MessageFactory messageFactory = MessageFactory.newInstance();
SOAPMessage soapMessage = messageFactory.createMessage();
SOAPPart soapPart = soapMessage.getSOAPPart();
// SOAP Envelope
SOAPEnvelope envelope = soapPart.getEnvelope();
SOAPBody soapBody = envelope.getBody();
SOAPElement soapBodyElem = soapBody.addChildElement("CallengeState");
SOAPElement soapBodyElem1 = soapBodyElem.addChildElement("number");
soapBodyElem1.addTextNode("00008");
SOAPElement soapBodyElem2 = soapBodyElem.addChildElement("previousState");
soapBodyElem2.addTextNode("Stoped");
SOAPElement soapBodyElem3 = soapBodyElem.addChildElement("currentState");
soapBodyElem3.addTextNode("Activated");
SOAPElement soapBodyElem4 = soapBodyElem.addChildElement("dateChanged");
soapBodyElem4.addTextNode("2014-06-09");
soapMessage.saveChanges();
/* Print the request message */
System.out.print("Request SOAP Message = ");
soapMessage.writeTo(System.out);
System.out.println();
return soapMessage;
}
/**
* Method used to print the SOAP Response
*/
private static void printSOAPResponse(SOAPMessage soapResponse) throws Exception {
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
Source sourceContent = soapResponse.getSOAPPart().getContent();
System.out.print("\nResponse SOAP Message = ");
StreamResult result = new StreamResult(System.out);
transformer.transform(sourceContent, result);
}
}
But I don't know how to set in this code my parameter and I got following error:
Response SOAP Message = [Fatal Error] :2:6: The processing instruction target matching "[xX][mM][lL]" is not allowed.
Error occurred while sending SOAP Request to Server

How to add parameters to the SOAP Request

I want to call RFC function in SAP, I already could make request from Java and get the WSDL response. But I want to send a parameter with the SOAP request ? How to do that ?
The class below, I used it to create the request and get response :
public class SOAPClientSAAJ {
public static void main(String args[]) throws Exception {
// Create SOAP Connection
SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
SOAPConnection soapConnection = soapConnectionFactory.createConnection();
// Send SOAP Message to SOAP Server
String url = "http://10.130.105.8:8000/sap/bc/.....client=520";
SOAPMessage soapResponse = soapConnection.call(createSOAPRequest(), url);
// print SOAP Response
System.out.print("Response SOAP Message:");
soapResponse.writeTo(System.out);
soapConnection.close();
}
private static SOAPMessage createSOAPRequest() throws Exception {
MessageFactory messageFactory = MessageFactory.newInstance();
SOAPMessage soapMessage = messageFactory.createMessage();
SOAPPart soapPart = soapMessage.getSOAPPart();
String serverURI = "http://ws.cdyne.com/";
// SOAP Envelope
SOAPEnvelope envelope = soapPart.getEnvelope();
envelope.addNamespaceDeclaration("example", serverURI);
// SOAP Body
SOAPBody soapBody = envelope.getBody();
SOAPElement soapBodyElem = soapBody.addChildElement("pernr","example");
soapBodyElem.addTextNode("10001001");
String authorization = new String(Base64.encodeBase64(("hr_develop:unrwa2013").getBytes()));
soapMessage.getMimeHeaders().addHeader("Authorization","Basic " + authorization);
soapMessage.saveChanges();
/* Print the request message */
soapMessage.writeTo(System.out);
System.out.println();
return soapMessage;
}
}

Web service call with Java using SOAP

I am provided with the following example request, but I don't know how to actually execute it.
POST /InfoTransit/userservices.asmx HTTP/1.1
Host: 10.0.2.52
Content-Type: text/xml; charset=utf-8
Content-Length: length
SOAPAction: "http://miz.it/infotransit/GetBusStopsList"
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<GetBusStopsList xmlns="http://miz.it/infotransit">
<auth>
<user>..of course, I have this..</user>
<password>..and this..</password>
</auth>
</GetBusStopsList>
</soap:Body>
</soap:Envelope>
I have tried to write a Java client...
import javax.xml.soap.*;
import javax.xml.transform.*;
import javax.xml.transform.stream.*;
public class SOAPClientSAAJ {
/**
* Starting point for the SAAJ - SOAP Client Testing
*/
public static void main(String args[]) {
try {
// Create SOAP Connection
SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
SOAPConnection soapConnection = soapConnectionFactory.createConnection();
// Send SOAP Message to SOAP Server
String url = "http://miz.it/InfoTransit/userservices.asmx";
SOAPMessage soapResponse = soapConnection.call(createSOAPRequest(), url);
// Process the SOAP Response
printSOAPResponse(soapResponse);
soapConnection.close();
} catch (Exception e) {
System.err.println("Error occurred while sending SOAP Request to Server");
e.printStackTrace();
}
}
private static SOAPMessage createSOAPRequest() throws Exception {
MessageFactory messageFactory = MessageFactory.newInstance();
SOAPMessage soapMessage = messageFactory.createMessage();
SOAPPart soapPart = soapMessage.getSOAPPart();
String serverURI = "http://miz.it/infotransit/GetBusStopsList";
// SOAP Envelope
SOAPEnvelope envelope = soapPart.getEnvelope();
// SOAP Body
SOAPBody soapBody = envelope.getBody();
SOAPElement getBusStopsList = soapBody.addChildElement("GetBusStopsList xmlns='http://miz.it/infotransit'");
SOAPElement auth = getBusStopsList.addChildElement("auth");
SOAPElement user = auth.addChildElement("user");
user.addTextNode(" .... ");
SOAPElement password = auth.addChildElement("password");
password.addTextNode(" ... ");
MimeHeaders headers = soapMessage.getMimeHeaders();
headers.addHeader("SOAPAction", serverURI);
headers.addHeader("Content-Type:", "text/xml; charset=uft-8");
soapMessage.saveChanges();
/* Print the request message */
System.out.print("Request SOAP Message = ");
soapMessage.writeTo(System.out);
System.out.println();
return soapMessage;
}
/**
* Method used to print the SOAP Response
*/
private static void printSOAPResponse(SOAPMessage soapResponse) throws Exception {
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
Source sourceContent = soapResponse.getSOAPPart().getContent();
System.out.print("\nResponse SOAP Message = ");
StreamResult result = new StreamResult(System.out);
transformer.transform(sourceContent, result);
}
}
However, I get a connection time-out. Also, the output SOAP message has an envelope that does'nt completely match the envelope of the example request.
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
Is something wrong with the client? Or is it the service provider?
Can you try this in your code:
SOAPElement getBusStopsList = soapBody.addChildElement("GetBusStopsList", "", "http://miz.it/infotransit");
EDIT: The first letter is lower case in getBusStopsList. So, please try GetBusStopsList.
Here is new code:
SOAPElement GetBusStopsList = soapBody.addChildElement("GetBusStopsList", "", "http://miz.it/infotransit");

Categories

Resources