Using SoapUI with Axis2 work ok and java code no work - axis2

the soupui requeset is working ok, but when I try the java code no work, I really confused by the issuse.
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:port="http://service.composit.unic.capsa.com/UNICService/port" xmlns:sch="http://www.ibm.com/mdm/schema">
<soapenv:Header><wsse:Security soapenv:mustUnderstand="1" xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"><wsse:UsernameToken><wsse:Username>mdmadmin</wsse:Username><wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">mdmadmin</wsse:Password></wsse:UsernameToken></wsse:Security></soapenv:Header>
<soapenv:Body>
<port:checkHeartBeatInfo>
<sch:RequestControl>
<sch:requestID>112</sch:requestID>
<sch:DWLControl>
<sch:requesterName>111</sch:requesterName>
<sch:requesterLanguage>100</sch:requesterLanguage>
<sch:clientSystemName>DCS_test</sch:clientSystemName>
</sch:DWLControl>
</sch:RequestControl>
<sch:InputCheckHeartBeatInfoBObj/>
</port:checkHeartBeatInfo>
</soapenv:Body>
</soapenv:Envelope>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
<soapenv:Body>
<port:checkHeartBeatInfoResponse xmlns:port="http://service.composit.unic.capsa.com/UNICService/port">
<ResponseControl xmlns="http://www.ibm.com/mdm/schema">
<ResultCode>SUCCESS</ResultCode>
<ServiceTime>58</ServiceTime>
<DWLControl>
<requesterName>mdmadmin</requesterName>
<requesterLanguage>100</requesterLanguage>
<requesterLocale>en</requesterLocale>
<clientSystemName>DCS_test</clientSystemName>
<userRole>mdm_admin</userRole>
<requestID>112</requestID>
</DWLControl>
</ResponseControl>
<TxResult xmlns="http://www.ibm.com/mdm/schema">
<ResultCode>SUCCESS</ResultCode>
</TxResult>
<OutputCheckHeartBeatInfoBObj xmlns="http://www.ibm.com/mdm/schema">
<ComponentID>2000172</ComponentID>
<Rtn_code>Success!</Rtn_code>
</OutputCheckHeartBeatInfoBObj>
</port:checkHeartBeatInfoResponse>
</soapenv:Body>
</soapenv:Envelope>
my client test code is follow:
UNICServiceServiceStub stub = new UNICServiceServiceStub();
CheckHeartBeatInfoDocument checkHeartBeatInfo18 = CheckHeartBeatInfoDocument.Factory.newInstance();
CheckHeartBeatInfoInputType checkHeartBeatInfo = CheckHeartBeatInfoInputType.Factory.newInstance();
DWLControl oDWLContorl = DWLControl.Factory.newInstance();
oDWLContorl.setRequesterLanguage("100");
oDWLContorl.setRequesterName("111");
oDWLContorl.setClientSystemName("DCS_test");
RequestControl requestControl = RequestControl.Factory.newInstance();
requestControl.setRequestID("112");
requestControl.setDWLControl(oDWLContorl);
checkHeartBeatInfo.setRequestControl(requestControl);
OMFactory omFactory = OMAbstractFactory.getOMFactory();
OMNamespace namespaceWSSE = omFactory.createOMNamespace("http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd", "wsse");
OMElement header = omFactory.createOMElement("Security", namespaceWSSE);
OMAttribute attribute = omFactory.createOMAttribute("soapenv:mustUnderstand", null, "1");
header.addAttribute(attribute);
OMElement omusertoken = omFactory.createOMElement("UsernameToken", namespaceWSSE);
header.addChild(omusertoken);
OMElement omuserName = omFactory.createOMElement("Username", namespaceWSSE);
omuserName.setText("mdmadmin");
OMElement omPassword = omFactory.createOMElement("Password", namespaceWSSE);
omPassword.addAttribute("Type","http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText", null );
omPassword.setText("mdmadmin");
omusertoken.addChild(omuserName);
omusertoken.addChild(omPassword);
stub._getServiceClient().addHeader(header);
checkHeartBeatInfo18.setCheckHeartBeatInfo(checkHeartBeatInfo);
CheckHeartBeatInfoResponseDocument response = CheckHeartBeatInfoResponseDocument.Factory.newInstance();
response = stub.checkHeartBeatInfo(checkHeartBeatInfo18);
System.out.println(response.toString());
I don't know why it throw exception? appreciate your help, thanks.

I solved. The key to done is comparing the xml of your code genarate with the soapui's.
public class Test
{
public static void main(String[] args)
{
try
{
UNICServiceServiceStub stub = new UNICServiceServiceStub();
DWLControl oDWLContorl = DWLControl.Factory.newInstance();
oDWLContorl.setRequesterLanguage("100");
oDWLContorl.setRequesterName("111");
oDWLContorl.setClientSystemName("DCS_test");
RequestControl requestControl = RequestControl.Factory.newInstance();
requestControl.setRequestID("112");
requestControl.setDWLControl(oDWLContorl);
SOAPFactory omFactory = OMAbstractFactory.getSOAP11Factory();
OMNamespace namespaceWSSE = omFactory.createOMNamespace("http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd", "wsse");
OMElement omSecurityElement = omFactory.createOMElement("Security", namespaceWSSE);
OMAttribute attribute = omFactory.createOMAttribute("soapenv:mustUnderstand", null, "1");
omSecurityElement.addAttribute(attribute);
OMElement omusertoken = omFactory.createOMElement("UsernameToken", namespaceWSSE);
OMElement omuserName = omFactory.createOMElement("Username", namespaceWSSE);
omuserName.setText("mdmadmin");
OMElement omPassword = omFactory.createOMElement("Password", namespaceWSSE);
omPassword.addAttribute("Type","http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText", null );
omPassword.setText("mdmadmin");
omusertoken.addChild(omuserName);
omusertoken.addChild(omPassword);
omSecurityElement.addChild(omusertoken);
InputCheckHeartBeatInfoBObjType inputCheckHeartBeatInfoBObj = InputCheckHeartBeatInfoBObjType.Factory.newInstance();
CheckHeartBeatInfoDocument checkHeartBeatInfo18 = CheckHeartBeatInfoDocument.Factory.newInstance();
CheckHeartBeatInfoInputType checkHeartBeatInfo = CheckHeartBeatInfoInputType.Factory.newInstance();
checkHeartBeatInfo.setRequestControl(requestControl);
checkHeartBeatInfo.setInputCheckHeartBeatInfoBObj(inputCheckHeartBeatInfoBObj);
checkHeartBeatInfo18.setCheckHeartBeatInfo(checkHeartBeatInfo);
stub._getServiceClient().addHeader(omSecurityElement);
CheckHeartBeatInfoResponseDocument response = stub.checkHeartBeatInfo(checkHeartBeatInfo18);
System.out.println(response.toString());
}
catch (AxisFault e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (RemoteException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (ProcessingFault e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

Related

input :Specified cast is not valid

I tried to execute my application Rest api. Using a breakpoint, I found a problm in this line:
expenses.AmountTTC = Convert.ToDecimal(ttc.Text);
The error is "Specified cast is not valid".
AmountTTC has the type decimal? in the model , same for my service(i have two projects, one for the services and anthor for my mobile application).
private void Button_Clicked(object sender, EventArgs e)
{
ajoutD.Clicked += async delegate
{
try
{
LoginViews expenses = new LoginViews();
expenses.Name = nameLib.Text;
expenses.StartDate = dataDe.Date;
expenses.EndDate = dateAu.Date;
datenow.Date = DateTime.Now;
expenses.Description = description.Text;
expenses.CurrencyId = Convert.ToInt32(devises.Id);
expenses.AmountTTC = Convert.ToDecimal(ttc.Text);
remb.Text = expenses.AmountReimbursed.ToString();
expenses.Remboursable = Convert.ToBoolean(isremboursable);
expenses.Provider = marchand.Text;
HttpClient httpClient = new HttpClient();
HttpResponseMessage response;
var json = JsonConvert.SerializeObject(expenses);
var content = new StringContent(json, Encoding.UTF8, "application/json");
response = await httpClient.PostAsync(url, content);
AuthResponse responseData = JsonConvert.DeserializeObject<AuthResponse>(response?.Content?.ReadAsStringAsync()?.Result);
if (responseData.data.Success)
{
await DisplayAlert("heey", "connexion done", "ok");
}
else
{
await DisplayAlert("wake up !", responseData.data.ErrorMessage, "attention");
}
}catch(Exception eee)
{
string msg = eee.ToString();
}
};
}

How to encrypt payload file streamingly via WSO2 ESB

I have to implement a scenario by using WSO2 ESB, as encrypting the binary payload streamingly while response to the client side (I assume the content-type in the case is Application/Octet-Stream), below is some details by my thought:
An Endpoint like "http://myhost/backend/" which provides business functionality;
A proxy which pass messages through the endpoint;
I attempt to write an OutSequence to check the Content-type: if the Content-Type matches Application/Octet-Stream, invoke my customized class mediator to encrypt the fileStream Streamingly and response.
I have no idea on how to write the class mediator to make it implemented? How could I get/read the file stream from the message as well as how to put the outputStream back to the response while I could only see mc.getEnvelope().getBody() in mediation method? Below is my current mediator which doesn't work.
public boolean mediate(MessageContext mc) {
org.apache.axis2.context.MessageContext amc = ((Axis2MessageContext) mc).getAxis2MessageContext();
try {
String contentID = amc.getAttachmentMap().getAllContentIDs()[0];
DataHandler dh = amc.getAttachment(contentID);
dh.getDataSource().getName();
InputStream is = null;
try {
is = dh.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = null;
while ((line = br.readLine()) != null) {
System.out.println("client read:" + line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
return true;
}
Many thanks if anybody with experience would kindly help.
Pasted my current solution for anyone else who confronts similar issue.
In the mediator, I read the file content from response stream via OMText.InputStream and use net.lingala.zip4j package to write a zip file(in memory) with the raw file encrypted; Finally I write the zip file content as ByteArray back to the OMElement of the soap message.
public boolean mediate(MessageContext mc) {
System.out.println("========================Mediator log start================================");
org.apache.axis2.context.MessageContext amc = ((Axis2MessageContext) mc).getAxis2MessageContext();
try {
#SuppressWarnings("unchecked")
Map<String, String> responseHeaders = (Map<String, String>) amc.getProperty("TRANSPORT_HEADERS");
String rawFileName = "";
String[] contentDisps = responseHeaders.get("Content-Disposition").split(";");
for (String item : contentDisps) {
System.out.println("item::" + item);
if (item.trim().startsWith(CONTENT_DISPOSITION_FILENAME)) {
rawFileName = item.substring(item.indexOf("\"") + 1, item.length() - 1);
break;
}
}
responseHeaders.put(
"Content-Disposition",
responseHeaders.get("Content-Disposition").replace(rawFileName,
rawFileName.substring(0, rawFileName.lastIndexOf(".")) + ".myzip"));
OMElement binaryPayload =
amc.getEnvelope().getBody()
.getFirstChildWithName(new QName("http://ws.apache.org/commons/ns/payload", "binary"));
OMText binaryNode = (OMText) binaryPayload.getFirstOMChild();
DataHandler dataHandler = (DataHandler) binaryNode.getDataHandler();
InputStream is = dataHandler.getInputStream();
ByteArrayOutputStream responseOutputStream = new ByteArrayOutputStream();
ZipOutputStream zipOutputStream = getZipOutputStreamInstance(responseOutputStream, rawFileName);
// write to zipOutputStream
byte data[] = new byte[BUFFER_SIZE];
int count;
while ((count = is.read(data, 0, BUFFER_SIZE)) != -1) {
zipOutputStream.write(data, 0, count);
zipOutputStream.flush();
}
zipOutputStream.closeEntry();
zipOutputStream.finish();
InputStream in = new ByteArrayInputStream(responseOutputStream.toByteArray());
DataHandler zipDataHandler = new DataHandler(new StreamingOnRequestDataSource(in));
OMFactory factory = OMAbstractFactory.getOMFactory();
OMText zipData = factory.createOMText(zipDataHandler, true);
zipData.setBinary(true);
binaryPayload.getFirstOMChild().detach();
binaryPayload.addChild(zipData);
amc.setProperty("TRANSPORT_HEADERS", responseHeaders);
System.out.println("========================Mediator end==================================");
} catch (Exception ex) {
System.out.println("exception found here:");
ex.printStackTrace();
}
return true;
}

get data (single value) from ksoap to andorid through webservice

final String SOAP_ACTION = "http://tempuri.org/get_data2";
final String OPERATION_NAME = "get_data2";
final String WSDL_TARGET_NAMESPACE = "http://tempuri.org/";
final String SOAP_ADDRESS = "****";
final String req_no, req_date, bolnumber, container_no, current_loc, truck_no;
SoapObject request = new SoapObject(WSDL_TARGET_NAMESPACE, OPERATION_NAME);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE httpTransport = new HttpTransportSE(SOAP_ADDRESS);
try
{
httpTransport.call(SOAP_ACTION, envelope);
SoapObject resultsString = (SoapObject)envelope.getResponse();
Log.d("-----------------------", resultsString.getProperty("emp_name").toString());
tv.setText(resultsString.getPropertyCount());
}
catch (Exception exception)
{
exception.printStackTrace();
tv.setText(exception.toString());
}

Error code 706 when signing PDF using Web Agent in Java

When testing the Web Agent sample in Java, I am getting an error reply
<?xml version="1.0" encoding="utf-8"?>
<response xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" type="error">
<Error>
<returnCode>706</returnCode>
<errorMessage>Value cannot be null.
Parameter name: s</errorMessage>
</Error>
</response>
I followed the Ruby example in the CoSign Web Agent samples and the documentation
I have used the demo.pdf file provided in the sample.
This is the XML (from test app) sent in the POST request (the <content></content> has the Base64 encoded PDF, but omitted because of length).
<?xml version="1.0" encoding="utf-8" ?>
<request>
<Logic>
<allowAdHoc>true</allowAdHoc>
<workingMode>pull</workingMode>
<enforceReason>false</enforceReason>
</Logic>
<Url>
<finishURL>http://localhost:64956/retrieveSignedFile.aspx</finishURL>
</Url>
<Document>
<fileID>1234567890</fileID>
<contentType>pdf</contentType>
<content>{BASE64 encoded pdf content}</content>
</Document>
</request>
The following is the java code I have used:
public class CoSignTest {
private static final String INPUT = "D:\\tmp\\demo.pdf";
private static final String PRECONTENT = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n" +
"<request>\n" +
" <Logic>\n" +
" <allowAdHoc>true</allowAdHoc>\n" +
" <workingMode>pull</workingMode>\n" +
" <enforceReason>false</enforceReason>\n" +
" </Logic>\n" +
" <Url>\n" +
" <finishURL>http://localhost:64956/retrieveSignedFile.aspx</finishURL>\n" +
" </Url>\n" +
" <Document>\n" +
" <fileID>1234567890</fileID>\n" +
" <contentType>pdf</contentType>\n" +
" <content>";
private static final String POSTCONTENT = "</content>\n" +
" </Document>\n" +
"</request>";
private static final String POST_URL = "https://webagentdev.arx.com/Sign/UploadFileToSign";
private static final String PULL_URL = "https://webagentdev.arx.com/Sign/DownloadSignedFileG";
public static final int TIMEOUT = 300000;
public static void main(String[] args) throws Exception {
InputStream is = new FileInputStream(INPUT);
String content = PRECONTENT + new String(Base64.encodeBase64(loadResource(is)), "UTF-8") + POSTCONTENT;
System.out.println(content);
String reply = new String(sendDocForProcessing(URLEncoder.encode(content, "UTF-8")));
System.out.println(reply);
System.out.println("DONE");
}
private static String sendDocForProcessing(String content) throws Exception {
HttpClient client = null;
HttpMethodBase method = null;
SimpleHttpConnectionManager mgr = new SimpleHttpConnectionManager();
String reply = "";
try {
mgr.getParams().setConnectionTimeout(TIMEOUT);
mgr.getParams().setSoTimeout(TIMEOUT);
client = new HttpClient(mgr);
method = new PostMethod(POST_URL);
method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(1, false));
method.getParams().setParameter("http.socket.timeout", TIMEOUT);
client.getHttpConnectionManager().getParams().setConnectionTimeout(TIMEOUT);
client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
method.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
method.getParams().setParameter("inputXML", content);
client.executeMethod(method);
reply = new String(method.getResponseBody());
} catch (Exception e) {
e.printStackTrace();
} finally {
if(method != null) {
method.releaseConnection();
}
client = null;
mgr.shutdown();
}
if (isSigningSuccessful(reply)) {
return reply;
} else {
throw new Exception("Failed in signing the document. Error: " + reply);
}
}
private static boolean isSigningSuccessful(String reply) throws ParserConfigurationException, IOException, SAXException {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new ByteArrayInputStream(reply.getBytes()));
Element elem = doc.getDocumentElement();
String type = elem.getAttribute("type");
return !"error".equals(type);
}
public static byte[] loadResource(InputStream in) {
if (in == null) {
return new byte[0];
}
try {
int indice, tempIndice;
byte[] tempArr;
byte[] mainArr = new byte[0];
byte[] byteArr = new byte[65535];
for (indice = 0; (indice = in.read(byteArr)) > 0;) {
tempIndice = mainArr.length + indice;
tempArr = new byte[tempIndice];
System.arraycopy(mainArr, 0, tempArr, 0, mainArr.length);
System.arraycopy(byteArr, 0, tempArr, mainArr.length, indice);
mainArr = tempArr;
}
in.close();
return mainArr;
} catch (Exception e) {
e.printStackTrace();
}
return new byte[0];
}
}
The XML elements are case sensitive and must be passed as shown in the documentation (e.g. Document instead of document, Auth instead of auth and so on). In addition, your XML request is missing the finishURL parameter which is mandatory.
Also note that some parameters in your XML request are obsolete. See the updated request parameter list in the link above. A sample XML is available here.
Thanks for adding your Java code. Note that the HttpClient instance is configured incorrectly and as a result the http-post request is sent empty. Take a look at the modifications I did in your sendDocForProcessing function in order to properly post the XML content:
private static String sendDocForProcessing(String content) throws Exception {
HttpClient client = null;
PostMethod method = null;
String reply = "";
try {
client = new HttpClient();
method = new PostMethod(POST_URL);
method.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
NameValuePair[] data = { new NameValuePair("inputXML", content) };
method.setRequestBody(data);
client.executeMethod(method);
reply = method.getResponseBodyAsString();
} catch (Exception e) {
e.printStackTrace();
} finally {
if(method != null) {
method.releaseConnection();
}
}
if (isSigningSuccessful(reply)) {
return reply;
} else {
throw new Exception("Failed in signing the document. Error: " + reply);
}
}
The content passed to the above function should not be URL-encoded as it is already done by the HttpClient library.
In addition, when analyzing the response, I suggest you to check the value of the returnCode element rather than the type property. The response is always of type 'error'.
Also note that the function name isSigningSuccessful is misleading as this stage is still prior to the act of signing.

Client giving error when invoking a secured web service

I have written a client that invokes webservice. My client is:
String publisherEPR = "https://abc:8280/services/ProviderPublication";
protected void publicationOpenSession(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("Inside publicationOpenSession");
date = new Date();
namespace = "http://www.openoandm.org/xml/ISBM/";
fac = OMAbstractFactory.getOMFactory();
OMNamespace ns = fac.createOMNamespace(namespace, "ns1");
OMElement result = null;
channelURI = request.getParameter("TxtPublisher1ChannelURI");
textfield = request.getParameter("TxtAreaServicePublisherLog");
String finalChannelURI = "";
int count = 0;
try {
if (channelURI != null && (channelURI.indexOf(".") > -1)) {
System.out.println("Inside If Checking Channel URI");
String[] tempChannelURI = channelURI.split("\\.");
for (count = 0; count < tempChannelURI.length - 1; count++) {
finalChannelURI = finalChannelURI + tempChannelURI[count];
if (count < tempChannelURI.length - 2) {
finalChannelURI = finalChannelURI + ".";
}
}
System.out.println("Inside If Checking Channel URI : " + finalChannelURI);
}
System.out.println("OpenPublicationSession" + finalChannelURI);
System.out.println(publisherEPR);
OMElement OpenPublicationSessionElement = fac.createOMElement("OpenPublicationSession", ns);
OMElement ChannelURIElement = fac.createOMElement("ChannelURI", ns);
ChannelURIElement.setText(finalChannelURI);
OpenPublicationSessionElement.addChild(ChannelURIElement);
String webinfFolder = request.getSession().getServletContext().getRealPath("/WEB-INF");
ConfigurationContext ctx = ConfigurationContextFactory.createConfigurationContextFromFileSystem(
webinfFolder, webinfFolder + "/conf/axis2.xml");
Options options = new Options();
ServiceClient client = new ServiceClient(ctx, null);
EndpointReference targetEPR = new EndpointReference(publisherEPR);
options.setTo(targetEPR);
options.setAction("urn:OpenPublicationSession");
options.setManageSession(true);
options.setUserName(user_name);
java.util.Map<String, Object> m = new java.util.HashMap<String, Object>();
/*m.put("javax.net.ssl.trustStorePassword", "wso2carbon");
m.put("javax.net.ssl.trustStore", "wso2carbon.jks");
*/
System.out.println(new Date() + " Checkpoint1");
// We are accessing STS over HTTPS - so need to set trustStore parameters.
System.setProperty("javax.net.ssl.trustStore", "client.jks");
System.setProperty("javax.net.ssl.trustStorePassword", "apache");
/*m.put("javax.net.ssl.trustStore", "client.jks");
m.put("javax.net.ssl.trustStorePassword", "apache");*/
/*m.put("org.apache.ws.security.crypto.provider","org.apache.ws.security.components.crypto.Merlin");
m.put("org.apache.ws.security.crypto.merlin.keystore.type", "jks");
m.put("org.apache.ws.security.crypto.merlin.keystore.password","apache");
m.put("org.apache.ws.security.crypto.merlin.file", "client.jks");*/
//options.setProperties(m);
System.out.println(new Date() + " Checkpoint2");
client.setOptions(options);
MessageContext messageContext = new MessageContext();
messageContext.setOptions(options);
messageContext.setMessageID("MyMessageID");
System.out.println("provider:user_name: " + user_name);
messageContext.setProperty("username", user_name);
messageContext.setProperty("password", user_password);
MessageContext.setCurrentMessageContext(messageContext);
messageContext.setProperty("myproperty", "mypropertyvalue");
String falconNS = "http://cts.falcon.isbm";
falcon = fac.createOMNamespace(falconNS, "falcon");
OMElement falconUserElement = fac.createOMElement("FalconUser", falcon);
falconUserElement.setText(user_name);
client.addHeader(falconUserElement);
// invoke web-service
try {
errorText = "Client Didnt Respond.";
result = client.sendReceive(OpenPublicationSessionElement);
System.out.println(result.toString());
OMElement SessionIDElement = null;
SessionIDElement = result.getFirstChildWithName(new QName(namespace, "SessionID"));
SessionID = SessionIDElement.getText();
request.setAttribute("PublisherSession", SessionID);
StringBuffer text = new StringBuffer();
text.append((request.getParameter("TxtAreaServicePublisherLog")).trim());
text.trimToSize();
SessionID = SessionIDElement.getText();
StringBuffer publisherLog = new StringBuffer();
publisherLog.append((request.getParameter("TxtAreaServicePublisherLog")).trim());
publisherLog.trimToSize();
System.out.println("Checkpoint1");
publisherLog.append("\n" + new Date().toString() + " " + PUBLISHER_SESSION_SUCCESS_MSG + SessionID);
request.setAttribute("textMessageService2", publisherLog);
request.setAttribute("PublisherSession", SessionID);
System.out.println("Checkpoint3");
RequestDispatcher rd = request.getRequestDispatcher("/Provider.jsp");// hard-coded
try {
rd.forward(request, response);
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (ServletException se) {
se.printStackTrace();
}
} catch (Exception e) {
errorText = "Client not responding";
buildErrorLog(request, response, e);
e.printStackTrace();
}
//buildCallLog(request, response, result);
} catch (Exception e) {
e.printStackTrace();
buildErrorLog(request, response, e);
}
}
And i have a proxy service upon which i have implemented security and its url is:
https://abc:8280/services/ProviderPublication.
My handle method inside callback handler is:
public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
System.out.println("\n \n " + new Date() + " ISBMClient.PWCBHandler.handle");
if(MessageContext.getCurrentMessageContext() == null){
System.out.println("CurrentMessageContext is null");
}else{
//get the credentials from the jsp
System.out.println("MessageID: " + MessageContext.getCurrentMessageContext().getMessageID());
dynamicUser = MessageContext.getCurrentMessageContext().getProperty("username").toString();
dynamicPassword = MessageContext.getCurrentMessageContext().getProperty("password").toString();
System.out.println("MessageContext user_name: " + dynamicUser);
System.out.println("MessageContext user_password: " + dynamicPassword);
}
for (int i = 0; i < callbacks.length; i++) {
WSPasswordCallback pwcb = (WSPasswordCallback)callbacks[i];
pwcb.setIdentifier(dynamicUser);
String id = pwcb.getIdentifier();
System.out.println("Invoking service with user: " + id);
if(dynamicUser.equals(id)){
pwcb.setPassword(dynamicPassword);
}
}
}
Now the problem is when i invoke this proxy service through my client code i am getting exception as
[INFO] Unable to sendViaPost to url[https://abc:8280/services/ProviderPublication]
org.apache.axis2.AxisFault: Trying to write END_DOCUMENT when document has no root (ie. trying to output empty document).
at org.apache.axis2.AxisFault.makeFault(AxisFault.java:430)
at org.apache.axis2.transport.http.SOAPMessageFormatter.writeTo(SOAPMessageFormatter.java:78)
at org.apache.axis2.transport.http.AxisRequestEntity.writeRequest(AxisRequestEntity.java:84)
at org.apache.commons.httpclient.methods.EntityEnclosingMethod.writeRequestBody(EntityEnclosingMethod.java:499)
at org.apache.commons.httpclient.HttpMethodBase.writeRequest(HttpMethodBase.java:2114)
at org.apache.commons.httpclient.HttpMethodBase.execute(HttpMethodBase.java:1096)
at org.apache.commons.httpclient.HttpMethodDirector.executeWithRetry(HttpMethodDirector.java:398)
at org.apache.commons.httpclient.HttpMethodDirector.executeMethod(HttpMethodDirector.java:171)
at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:397)
at org.apache.axis2.transport.http.AbstractHTTPSender.executeMethod(AbstractHTTPSender.java:621)
at org.apache.axis2.transport.http.HTTPSender.sendViaPost(HTTPSender.java:193)
at org.apache.axis2.transport.http.HTTPSender.send(HTTPSender.java:75)
at org.apache.axis2.transport.http.CommonsHTTPTransportSender.writeMessageWithCommons(CommonsHTTPTransportSender.java:404)
at org.apache.axis2.transport.http.CommonsHTTPTransportSender.invoke(CommonsHTTPTransportSender.java:231)
at org.apache.axis2.engine.AxisEngine.send(AxisEngine.java:443)
at org.apache.axis2.description.OutInAxisOperationClient.send(OutInAxisOperation.java:406)
at org.apache.axis2.description.OutInAxisOperationClient.executeImpl(OutInAxisOperation.java:229)
at org.apache.axis2.client.OperationClient.execute(OperationClient.java:165)
at org.apache.axis2.client.ServiceClient.sendReceive(ServiceClient.java:555)
at org.apache.axis2.client.ServiceClient.sendReceive(ServiceClient.java:531)
at cts.falcon.isbm.client.Provider.publicationOpenSession(Provider.java:557)
at cts.falcon.isbm.client.Provider.doPost(Provider.java:852)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:225)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:927)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1001)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:585)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
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)
Caused by: javax.xml.stream.XMLStreamException: Trying to write END_DOCUMENT when document has no root (ie. trying to output empty document).
at com.ctc.wstx.sw.BaseStreamWriter.throwOutputError(BaseStreamWriter.java:1473)
at com.ctc.wstx.sw.BaseStreamWriter.reportNwfStructure(BaseStreamWriter.java:1502)
at com.ctc.wstx.sw.BaseStreamWriter.finishDocument(BaseStreamWriter.java:1663)
at com.ctc.wstx.sw.BaseStreamWriter.close(BaseStreamWriter.java:288)
at org.apache.axiom.util.stax.wrapper.XMLStreamWriterWrapper.close(XMLStreamWriterWrapper.java:46)
at org.apache.axiom.om.impl.MTOMXMLStreamWriter.close(MTOMXMLStreamWriter.java:222)
at org.apache.axiom.om.impl.llom.OMSerializableImpl.serializeAndConsume(OMSerializableImpl.java:192)
at org.apache.axis2.transport.http.SOAPMessageFormatter.writeTo(SOAPMessageFormatter.java:74)
... 38 more
But the same code is working for another web service written in eclipse. What am i doing wrong? Looking forward to your answers. Thanks in advance
You need to set SOAP envelope along with SOAP body which carries your payload from Service Client. I think that cause this problem. Please refer this blog post and refactor your code to add that.
http://amilachinthaka.blogspot.com/2009/09/sending-arbitrary-soap-message-with.html
A little late on the response here, but I ran into the same error message and after further digging it was due to some SSL certificate failures.
There were 2 ways to fix this:
Adding trusted certificate to Java using the keytool command.
OR
Using your own custom code to accept all certs (ex. below with a acceptallCerts() method)
public class SslUtil {
private static class SmacsTrustManager implements X509TrustManager {
#Override
public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {}
#Override
public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {}
#Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
}
public static void acceptAllCerts(){
try{
SSLContext ctx = SSLContext.getInstance("TLS");
ctx.init(new KeyManager[0], new TrustManager[] {new SmacsTrustManager()}, new SecureRandom());
SSLContext.setDefault(ctx);
}catch (Exception e){
}
}
}