This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Web Services and the fly likes Saaj attachments through HttpServlet Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Web Services
Bookmark "Saaj attachments through HttpServlet" Watch "Saaj attachments through HttpServlet" New topic
Author

Saaj attachments through HttpServlet

DTR Prasad
Greenhorn

Joined: Aug 07, 2008
Posts: 3
I had written the following servlet that recives SOAPRequest and does some database manipulation ,then send attachments
package com.htc.wss;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletConfig;
import javax.xml.soap.MimeHeaders;
import javax.xml.soap.MimeHeader;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.SOAPMessage;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPPart;
import javax.xml.namespace.QName;
import javax.xml.soap.SOAPElement;
import javax.xml.soap.AttachmentPart;
import javax.xml.soap.SOAPBodyElement;
import javax.activation.DataHandler;
import java.util.Iterator;
import java.util.Enumeration;
import java.util.StringTokenizer;
import javax.servlet.ServletException;
import stockdb.StockDBBean;
import java.net.URL;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.logging.Logger;
import javax.xml.namespace.QName;


public class AttachmentsServlet extends HttpServlet
{
static final Logger logger =
Logger.getLogger("com.htc.wss");

static MessageFactory msgFactory = null;

private static StockDBBean dbBean;
static
{
try
{
msgFactory = MessageFactory.newInstance();
dbBean = new StockDBBean();
}
catch (Exception ex)
{
logger.severe("Exception: " + ex.toString());
}
}

public void init(ServletConfig servletConfig)
throws ServletException
{
super.init(servletConfig);
}

public void doPost(HttpServletRequest req,
HttpServletResponse resp)
throws ServletException, IOException
{
try
{

MimeHeaders headers = getHeaders(req);

headers.addHeader("Content-Type","multipart/related");
// Get the body of the HTTP request
InputStream is = req.getInputStream();

// Now internalize the contents of the HTTP request
// and create a SOAPMessage


SOAPMessage msg =
msgFactory.createMessage(headers, is);

SOAPMessage reply = null;

reply = onMessage(msg);
reply.writeTo(System.out);
if (reply != null)
{
/*
* Need to call saveChanges because we�re
* going to use the MimeHeaders to set HTTP
* response information. These MimeHeaders
* are generated as part of the save.
*/
if (reply.saveRequired())
{
reply.saveChanges();
}

resp.setStatus(HttpServletResponse.SC_OK);
putHeaders(reply.getMimeHeaders(), resp);
// Write out the message on the response stream
logger.info("Reply message:");
OutputStream os = resp.getOutputStream();
reply.writeTo(os);
os.flush();
}
else
{
resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
}
}
catch (Exception ex)
{
throw new ServletException( "SAAJ POST failed: " + ex.getMessage());
}
}
static MimeHeaders getHeaders(HttpServletRequest req)
{
Enumeration headerNames = req.getHeaderNames();
MimeHeaders headers = new MimeHeaders();
while (headerNames.hasMoreElements())
{
String headerName = (String)headerNames.nextElement();
String headerValue = req.getHeader(headerName);
StringTokenizer values = new StringTokenizer(headerValue, ",");
while (values.hasMoreTokens())
{
headers.addHeader(headerName, values.nextToken().trim());
}
}
return headers;
}

static void putHeaders(MimeHeaders headers,
HttpServletResponse res)
{
Iterator it = headers.getAllHeaders();
while (it.hasNext())
{
MimeHeader header = (MimeHeader)it.next();
String[] values = headers.getHeader(header.getName());
if (values.length == 1)
{
res.setHeader(header.getName(), header.getValue());
}
else
{
StringBuffer concat = new StringBuffer();
int i = 0;
while (i < values.length)
{
if (i != 0)
{
concat.append(',');
}
concat.append(values[i++]);
}
res.setHeader(header.getName(), concat.toString());
}
}

}

public String getRequestValue(SOAPBody body,String elementName)
{
String nameVal = "";
try
{
Iterator bodyIter =
body.getChildElements();
SOAPBodyElement elem = null;
while(bodyIter.hasNext())
{
elem = (SOAPBodyElement)bodyIter.next();
Iterator children = elem.getChildElements();
while(children.hasNext())
{
SOAPElement sElem = (SOAPElement)children.next();
String str =
sElem.getElementName().getQualifiedName();
System.out.println("\n"+str);
if(str.equalsIgnoreCase(elementName))
{
nameVal = sElem.getValue();
}
}
}
}
catch(Exception e){}
System.out.println("**"+nameVal);
return nameVal;
}

public SOAPMessage onMessage(SOAPMessage msg)
{
SOAPMessage reply = null;
try
{
msg.writeTo(System.out);
SOAPEnvelope envelope =
msg.getSOAPPart().getEnvelope();
SOAPBody body = envelope.getBody();


String person = getRequestValue(body,"person");
String company = getRequestValue(body,"company");
String qtyStr = getRequestValue(body,"qty");
dbBean = new StockDBBean();
String res = dbBean.doPurchase(person,company,qtyStr);
dbBean.close();
System.out.println("***"+res);
if(res.equals("DONE"))
{
reply = msgFactory.createMessage();
envelope =
reply.getSOAPPart().getEnvelope();
body = envelope.getBody();
QName bodyName =
new QName("http://wss.htc.com","reply-message","ns1");
SOAPElement bdyElement = body.addBodyElement(bodyName);

QName rName = new QName("reply");

SOAPElement rpy = bdyElement.addChildElement(rName);

rpy.addTextNode("transaction done for "+person);

QName statName = new QName("status");

SOAPElement statElement = bdyElement.addChildElement(statName);

statElement.addTextNode("success");

// attachementPart
String main1 = "http://localhost:10080/sec";
String att1 = main1+"/attachments/htmls/rules.xml";
String att2 = main1+"/attachments/pics/grapes.gif";
URL url = new URL(att1);
DataHandler dHandler = new DataHandler(url);
AttachmentPart attachment1 =
reply.createAttachmentPart(dHandler);

attachment1.addMimeHeader("Content-Type","application/xml");
attachment1.setContentId("rules");
reply.addAttachmentPart(attachment1);

url = new URL(att2);
DataHandler dHandler2 = new DataHandler(url);
AttachmentPart attachment2 =
reply.createAttachmentPart(dHandler2);
attachment2.addMimeHeader("Content-Type","application/xml");
attachment2.addMimeHeader("Content-Type","image/gif");
attachment2.setContentId("picture");


reply.addAttachmentPart(attachment2);
reply.saveChanges();
}
}
catch(Exception e)
{
System.out.println(e);
}
return reply;
}


}
Then i had written a client program like

import javax.xml.soap.MessageFactory;
import javax.xml.soap.SOAPConnectionFactory;
import javax.xml.soap.SOAPConnection;
import javax.xml.soap.SOAPMessage;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPHeader;
import javax.xml.soap.Name;
import javax.xml.soap.SOAPPart;
import javax.xml.soap.SOAPElement;
import javax.xml.soap.SOAPBodyElement;
import javax.xml.soap.AttachmentPart;
import java.util.Iterator;
import java.net.URL;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import javax.xml.soap.Node;
import javax.activation.DataHandler;


public class AttachmentsSenderClient
{
SOAPConnection soapCon;

private String target =
"http://localhost:10080/sec/stock-order";

MessageFactory mFactory;

public AttachmentsSenderClient()
{
try
{
SOAPConnectionFactory sFactory =
SOAPConnectionFactory.newInstance();
soapCon = sFactory.createConnection();
mFactory = MessageFactory.newInstance();
}
catch(Exception e)
{
e.printStackTrace();
}
}

public void sendMessage(String person,
String company,
String qty)
{
DataHandler handler = null;
BufferedOutputStream out = null;
try
{
SOAPMessage request =
mFactory.createMessage();
SOAPEnvelope envelope =
request.getSOAPPart().getEnvelope();
SOAPHeader header = envelope.getHeader();
SOAPBody body = envelope.getBody();
header.detachNode();

Name bodyName =
envelope.createName("placeOrders");
SOAPBodyElement bElem =
body.addBodyElement(bodyName);

SOAPElement sElem =
bElem.addChildElement(
envelope.createName("person"));
sElem.addTextNode(person);

sElem = bElem.addChildElement(
envelope.createName("company"));
sElem.addTextNode(company);

sElem = bElem.addChildElement(
envelope.createName("qty"));
sElem.addTextNode(qty);


URL targetUrl = new URL(target);
SOAPMessage reply = soapCon.call(request,targetUrl);


if(reply != null)
{
envelope =
reply.getSOAPPart().getEnvelope();
body = envelope.getBody();

System.out.println("\nRequest company is:"+ company);
System.out.println("Response is:"+ getResponseValue(body,"reply"));
System.out.println("Status is:"+ getResponseValue(body,"status"));
System.out.println("Attachements ");
Iterator iter = reply.getAttachments();

while(iter.hasNext())
{
AttachmentPart attach = (AttachmentPart)iter.next();
handler = attach.getDataHandler();
String str = attach.getContentId();
System.out.println(str);
if(str.equals("picture"))
{
out = new BufferedOutputStream(
new FileOutputStream("pic.gif"));
}
else if(str.equals("rules"))
{
out = new BufferedOutputStream(
new FileOutputStream("rules.xml"));
}
handler.writeTo(out);
out.close();
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
}


public static void main(String[] args)throws Exception
{
AttachmentsSenderClient client = new AttachmentsSenderClient();
if(args.length<2)
{
System.out.println("to run >java "+
" AttachmentsSenderClient <person> "+
" <company-name> <qty> to be given");
}
client.sendMessage(args[0],args[1],args[2]);
}

public String getResponseValue(SOAPBody body,
String given)
{
String nameVal = "";
SOAPBodyElement elem = null;
try
{
Iterator iter = body.getChildElements();
while(iter.hasNext())
{
SOAPElement sElem = (SOAPElement)iter.next();
String name = sElem.getElementName().getQualifiedName();

if(name.equalsIgnoreCase(given))
{
nameVal = sElem.getValue();
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
return nameVal;
}

}
When i run

c:\wspras>java AttachmentsSenderClient dtrprasad RELIANCE 54
it is showing an error
on command line

SEVERE: SAAJ0537:Invalid Content-Type.could be an error message instead of SOAP message.Java.security.PrivilegedActionException........................
text/html invalid content-type

in server logs
Servlet.service() for servlet stock-order threw exception
javax.servlet.ServletException: SAAJ POST failed: Error during saving a multipart message
at com.htc.wss.AttachmentsServlet.doPost(AttachmentsServlet.java:112)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:433)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:286)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:845)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:583)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447)
at java.lang.Thread.run(Thread.java:619)

If i am using JAXMServlet implemementing javax.xml.messaging.ReqRespListener

there are no problems and every thing is fine
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Saaj attachments through HttpServlet
 
Similar Threads
SAAJ (SOAP 1.1) incompatibility with Java 1.6
web service with attachment under java 1.6
how to set an attribute like SOAPAction in the Header?
simple SOAP Request/Response
WSDP and AXIS