List of usage examples for javax.xml.soap SOAPMessage getAttachments
public abstract Iterator<AttachmentPart> getAttachments();
From source file:com.googlecode.ddom.saaj.SOAPMessageTest.java
@Validated @Test/*from www . j a va 2 s .c om*/ public void testAddAttachmentPart() throws Exception { SOAPMessage message = getFactory().createMessage(); AttachmentPart attachment = message.createAttachmentPart(); message.addAttachmentPart(attachment); Iterator it = message.getAttachments(); assertTrue(it.hasNext()); assertSame(attachment, it.next()); assertFalse(it.hasNext()); // Check that the content type automatically changes to SwA if (message.saveRequired()) { message.saveChanges(); } String[] contentTypeArray = message.getMimeHeaders().getHeader("Content-Type"); assertNotNull(contentTypeArray); assertEquals(1, contentTypeArray.length); MimeType contentType = new MimeType(contentTypeArray[0]); assertEquals("multipart/related", contentType.getBaseType()); assertEquals(messageSet.getVersion().getContentType(), contentType.getParameter("type")); assertNotNull(contentType.getParameter("boundary")); }
From source file:com.nortal.jroad.endpoint.AbstractXTeeBaseEndpoint.java
@SuppressWarnings("unchecked") protected void getResponse(Document query, SOAPMessage responseMessage, SOAPMessage requestMessage) throws Exception { XTeeHeader header = metaService ? null : parseXteeHeader(requestMessage); // Build request message List<XTeeAttachment> attachments = new ArrayList<XTeeAttachment>(); for (Iterator<AttachmentPart> i = requestMessage.getAttachments(); i.hasNext();) { AttachmentPart a = i.next(); attachments.add(new XTeeAttachment(a.getContentId(), a.getContentType(), a.getRawContentBytes())); }//from w w w .ja v a 2s .c o m XTeeMessage<Document> request = new BeanXTeeMessage<Document>(header, query, attachments); SOAPElement teenusElement = createXteeMessageStructure(requestMessage, responseMessage); if (XRoadProtocolVersion.V2_0 == version) { if (!metaService) { copyParing(query, teenusElement); } teenusElement = teenusElement.addChildElement("keha"); } // Build response message XTeeMessage<Element> response = new BeanXTeeMessage<Element>(header, teenusElement, new ArrayList<XTeeAttachment>()); // Run logic invokeInternalEx(request, response, requestMessage, responseMessage); // Add any attachments for (XTeeAttachment a : response.getAttachments()) { AttachmentPart attachment = responseMessage.createAttachmentPart(a.getDataHandler()); attachment.setContentId("<" + a.getCid() + ">"); responseMessage.addAttachmentPart(attachment); } }
From source file:it.cnr.icar.eric.common.SOAPMessenger.java
/** * @return HashMap containing {contentId, DataHandler} entries or null * if no attachments/*w w w. j a v a 2s .co m*/ */ private HashMap<String, Object> processResponseAttachments(SOAPMessage response) throws JAXRException, SOAPException, MessagingException { if (response.countAttachments() == 0) { return null; } HashMap<String, Object> attachMap = new HashMap<String, Object>(); for (Iterator<?> it = response.getAttachments(); it.hasNext();) { AttachmentPart ap = (AttachmentPart) it.next(); String uuid = WSS4JSecurityUtilSAML.convertContentIdToUUID(ap.getContentId()); if (log.isTraceEnabled()) { log.trace("Processing attachment w/ contentId=" + uuid); } DataHandler dh = ap.getDataHandler(); attachMap.put(uuid, dh); } return attachMap; }
From source file:it.cnr.icar.eric.server.interfaces.soap.RegistryBSTServlet.java
public SOAPMessage onMessage(SOAPMessage msg, HttpServletRequest req, HttpServletResponse resp) { //System.err.println("onMessage called for RegistrySOAPServlet"); SOAPMessage soapResponse = null; SOAPHeader sh = null;//w w w. j a v a 2 s.c o m try { // set 'sh' variable ASAP (before "firstly") SOAPPart sp = msg.getSOAPPart(); SOAPEnvelope se = sp.getEnvelope(); SOAPBody sb = se.getBody(); sh = se.getHeader(); // Firstly we put save the attached repository items in a map HashMap<String, Object> idToRepositoryItemMap = new HashMap<String, Object>(); Iterator<?> apIter = msg.getAttachments(); while (apIter.hasNext()) { AttachmentPart ap = (AttachmentPart) apIter.next(); //Get the content for the attachment RepositoryItem ri = processIncomingAttachment(ap); idToRepositoryItemMap.put(ri.getId(), ri); } // Log received message //if (log.isTraceEnabled()) { // Warning! BAOS.toString() uses platform's default encoding /* ByteArrayOutputStream msgOs = new ByteArrayOutputStream(); msg.writeTo(msgOs); msgOs.close(); System.err.println(msgOs.toString()); */ //System.err.println(sb.getTextContent()); // log.trace("incoming message:\n" + msgOs.toString()); //} // verify signature // returns false if no security header, throws exception if invalid CredentialInfo credentialInfo = new CredentialInfo(); boolean noRegRequired = Boolean.valueOf( CommonProperties.getInstance().getProperty("eric.common.noUserRegistrationRequired", "false")) .booleanValue(); if (!noRegRequired) { WSS4JSecurityUtilBST.verifySOAPEnvelopeOnServerBST(se, credentialInfo); } //The ebXML registry request is the only element in the SOAPBody StringWriter requestXML = new StringWriter(); //The request as an XML String String requestRootElement = null; Iterator<?> iter = sb.getChildElements(); int i = 0; while (iter.hasNext()) { Object obj = iter.next(); if (!(obj instanceof SOAPElement)) { continue; } if (i++ == 0) { SOAPElement elem = (SOAPElement) obj; Name name = elem.getElementName(); requestRootElement = name.getLocalName(); StreamResult result = new StreamResult(requestXML); TransformerFactory tf = TransformerFactory.newInstance(); Transformer trans = tf.newTransformer(); trans.transform(new DOMSource(elem), result); } else { throw new RegistryException( ServerResourceBundle.getInstance().getString("message.invalidRequest")); } } if (requestRootElement == null) { throw new RegistryException( ServerResourceBundle.getInstance().getString("message.noebXMLRegistryRequest")); } // unmarshalling request to message Object message = bu.getRequestObject(requestRootElement, requestXML.toString()); if (message instanceof JAXBElement<?>) { // If Element; take ComplexType from Element message = ((JAXBElement<?>) message).getValue(); } // request sets ServerContext with ComplexType: RegistryObjectType BSTRequest request = new BSTRequest(req, credentialInfo, message, idToRepositoryItemMap); Response response = request.process(); // response.getMessage() is ComplexType again soapResponse = createResponseSOAPMessage(response); if (response.getIdToRepositoryItemMap().size() > 0 && (response.getMessage().getStatus() .equals(BindingUtility.CANONICAL_RESPONSE_STATUS_TYPE_ID_Success))) { idToRepositoryItemMap = response.getIdToRepositoryItemMap(); Iterator<?> mapKeysIter = idToRepositoryItemMap.keySet().iterator(); while (mapKeysIter.hasNext()) { String id = (String) mapKeysIter.next(); RepositoryItem repositoryItem = (RepositoryItem) idToRepositoryItemMap.get(id); String cid = WSS4JSecurityUtilBST.convertUUIDToContentId(id); DataHandler dh = repositoryItem.getDataHandler(); AttachmentPart ap = soapResponse.createAttachmentPart(dh); ap.setMimeHeader("Content-Type", "text/xml"); ap.setContentId(cid); soapResponse.addAttachmentPart(ap); if (log.isTraceEnabled()) { log.trace("adding attachment: contentId=" + id); } } } } catch (Throwable t) { //Do not log ObjectNotFoundException as it clutters the log if (!(t instanceof ObjectNotFoundException)) { log.error(ServerResourceBundle.getInstance().getString("message.CaughtException", new Object[] { t.getMessage() }), t); Throwable cause = t.getCause(); while (cause != null) { log.error(ServerResourceBundle.getInstance().getString("message.CausedBy", new Object[] { cause.getMessage() }), cause); cause = cause.getCause(); } } soapResponse = createFaultSOAPMessage(t, sh); } if (log.isTraceEnabled()) { try { ByteArrayOutputStream rspOs = new ByteArrayOutputStream(); soapResponse.writeTo(rspOs); rspOs.close(); // Warning! BAOS.toString() uses platform's default encoding log.trace("response message:\n" + rspOs.toString()); } catch (Exception e) { log.error(ServerResourceBundle.getInstance().getString("message.FailedToLogResponseMessage", new Object[] { e.getMessage() }), e); } } return soapResponse; }
From source file:eu.domibus.ebms3.receiver.MSHWebservice.java
@Override @Transactional//from ww w .j a v a2s . co m public SOAPMessage invoke(final SOAPMessage request) { SOAPMessage responseMessage = null; String pmodeKey = null; try { //FIXME: use a consistent way of property exchange between JAXWS and CXF message model. This: PropertyExchangeInterceptor pmodeKey = (String) request.getProperty(MSHDispatcher.PMODE_KEY_CONTEXT_PROPERTY); } catch (SOAPException e) { //this error should never occur because pmode handling is done inside the in-interceptorchain LOG.error("Cannot find PModeKey property for incoming Message"); assert false; } LegConfiguration legConfiguration = pModeProvider.getLegConfiguration(pmodeKey); String messageId = ""; try (StringWriter sw = new StringWriter()) { if (MSHWebservice.LOG.isDebugEnabled()) { this.transformerFactory.newTransformer().transform(new DOMSource(request.getSOAPPart()), new StreamResult(sw)); MSHWebservice.LOG.debug(sw.toString()); MSHWebservice.LOG.debug("received attachments:"); Iterator i = request.getAttachments(); while (i.hasNext()) { MSHWebservice.LOG.debug(i.next()); } } Messaging messaging = this.getMessaging(request); checkCharset(messaging); boolean messageExists = legConfiguration.getReceptionAwareness().getDuplicateDetection() && this.checkDuplicate(messaging); if (!messageExists && !(eu.domibus.common.configuration.model.Service.PING_SERVICE .equals(legConfiguration.getService().getValue()) && Action.PING_ACTION.equals(legConfiguration.getAction().getValue()))) { // ping messages are not stored/delivered messageId = this.persistReceivedMessage(request, legConfiguration, pmodeKey, messaging); } responseMessage = this.generateReceipt(request, legConfiguration, messageExists); if (!messageExists) { this.notifyBackends(messageId, legConfiguration); } } catch (TransformerException | SOAPException | JAXBException | IOException e) { throw new RuntimeException(e); } catch (EbMS3Exception e) { throw new WebServiceException(e); } return responseMessage; }
From source file:it.cnr.icar.eric.server.interfaces.soap.RegistrySAMLServlet.java
@SuppressWarnings("unchecked") public SOAPMessage onMessage(SOAPMessage msg, HttpServletRequest req, HttpServletResponse resp) { SOAPMessage soapResponse = null; SOAPHeader soapHeader = null; try {//from www . ja v a 2 s . com // extract SOAP related parts from incoming SOAP message // set 'soapHeader' variable ASAP (before "firstly") SOAPPart soapPart = msg.getSOAPPart(); SOAPEnvelope soapEnvelope = soapPart.getEnvelope(); SOAPBody soapBody = soapEnvelope.getBody(); soapHeader = soapEnvelope.getHeader(); /**************************************************************** * * REPOSITORY ITEM HANDLING (IN) REPOSITORY ITEM HANDLING (IN) * ***************************************************************/ // Firstly we put save the attached repository items in a map HashMap<String, Object> idToRepositoryItemMap = new HashMap<String, Object>(); Iterator<AttachmentPart> apIter = msg.getAttachments(); while (apIter.hasNext()) { AttachmentPart ap = apIter.next(); // Get the content for the attachment RepositoryItem ri = processIncomingAttachment(ap); idToRepositoryItemMap.put(ri.getId(), ri); } /**************************************************************** * * LOGGING (IN) LOGGING (IN) LOGGING (IN) LOGGING (IN) * ***************************************************************/ // Log received message if (log.isTraceEnabled()) { // Warning! BAOS.toString() uses platform's default encoding ByteArrayOutputStream msgOs = new ByteArrayOutputStream(); msg.writeTo(msgOs); msgOs.close(); log.trace("incoming message:\n" + msgOs.toString()); } /**************************************************************** * * MESSAGE VERIFICATION (IN) MESSAGE VERIFICATION (IN) * ***************************************************************/ CredentialInfo credentialInfo = new CredentialInfo(); WSS4JSecurityUtilSAML.verifySOAPEnvelopeOnServerSAML(soapEnvelope, credentialInfo); /**************************************************************** * * RS:REQUEST HANDLING RS:REQUEST HANDLING RS:REQUEST * ***************************************************************/ // The ebXML registry request is the only element in the SOAPBody StringWriter requestXML = new StringWriter(); // The request as an // XML String String requestRootElement = null; Iterator<?> iter = soapBody.getChildElements(); int i = 0; while (iter.hasNext()) { Object obj = iter.next(); if (!(obj instanceof SOAPElement)) { continue; } if (i++ == 0) { SOAPElement elem = (SOAPElement) obj; Name name = elem.getElementName(); requestRootElement = name.getLocalName(); StreamResult result = new StreamResult(requestXML); TransformerFactory tf = TransformerFactory.newInstance(); Transformer trans = tf.newTransformer(); trans.transform(new DOMSource(elem), result); } else { throw new RegistryException( ServerResourceBundle.getInstance().getString("message.invalidRequest")); } } if (requestRootElement == null) { throw new RegistryException( ServerResourceBundle.getInstance().getString("message.noebXMLRegistryRequest")); } // unmarshalling request to message Object message = bu.getRequestObject(requestRootElement, requestXML.toString()); if (message instanceof JAXBElement<?>) { // If Element; take ComplexType from Element message = ((JAXBElement<?>) message).getValue(); } SAMLRequest request = new SAMLRequest(req, credentialInfo.assertion, message, idToRepositoryItemMap); Response response = request.process(); /**************************************************************** * * RESPONSE HANDLING RESPONSE HANDLING RESPONSE HANDLING * ***************************************************************/ soapResponse = createResponseSOAPMessage(response); if (response.getIdToRepositoryItemMap().size() > 0 && (response.getMessage().getStatus() .equals(BindingUtility.CANONICAL_RESPONSE_STATUS_TYPE_ID_Success))) { idToRepositoryItemMap = response.getIdToRepositoryItemMap(); Iterator<String> mapKeysIter = idToRepositoryItemMap.keySet().iterator(); while (mapKeysIter.hasNext()) { String id = mapKeysIter.next(); RepositoryItem repositoryItem = (RepositoryItem) idToRepositoryItemMap.get(id); String cid = WSS4JSecurityUtilSAML.convertUUIDToContentId(id); DataHandler dh = repositoryItem.getDataHandler(); AttachmentPart ap = soapResponse.createAttachmentPart(dh); ap.setContentId(cid); soapResponse.addAttachmentPart(ap); if (log.isTraceEnabled()) { log.trace("adding attachment: contentId=" + id); } } } } catch (Throwable t) { // Do not log ObjectNotFoundException as it clutters the log if (!(t instanceof ObjectNotFoundException)) { log.error(ServerResourceBundle.getInstance().getString("message.CaughtException", new Object[] { t.getMessage() }), t); Throwable cause = t.getCause(); while (cause != null) { log.error(ServerResourceBundle.getInstance().getString("message.CausedBy", new Object[] { cause.getMessage() }), cause); cause = cause.getCause(); } } soapResponse = createFaultSOAPMessage(t, soapHeader); } if (log.isTraceEnabled()) { try { ByteArrayOutputStream rspOs = new ByteArrayOutputStream(); soapResponse.writeTo(rspOs); rspOs.close(); // Warning! BAOS.toString() uses platform's default encoding log.trace("response message:\n" + rspOs.toString()); } catch (Exception e) { log.error(ServerResourceBundle.getInstance().getString("message.FailedToLogResponseMessage", new Object[] { e.getMessage() }), e); } } return soapResponse; }
From source file:edu.xtec.colex.client.beans.ColexRecordBean.java
/** * Calls the web service operation/* w w w.jav a 2s . co m*/ * <I>exportCollection(User,Owner,Collection,Query) : FILE</I> * * @param response the HttpServletResponse where to return the File * @throws java.lang.Exception when an Exception error occurs */ protected void exportCollection(HttpServletResponse response) throws Exception { User u = new User(""); if (sUserVisitor != null) { u.setUserId(sUserVisitor); } else { u = new User(getUserId()); } try { smRequest = mf.createMessage(); SOAPBodyElement sbeRequest = setRequestName(smRequest, "exportCollection"); addParam(sbeRequest, u); if (owner != null) { Owner oRequest = new Owner(owner); addParam(sbeRequest, oRequest); } addParam(sbeRequest, new Collection(collection)); if (operation.equals("exportAll")) { Query qAux = new Query(); qAux.setBeginIndex(0); qAux.setDirection("asc"); qAux.setOrderField("null"); addParam(sbeRequest, qAux); } else if (operation.equals("exportStructure")) { Query qAux = new Query(); qAux.setBeginIndex(0); qAux.setDirection("asc"); qAux.setOrderField("null"); Condition cAux = new Condition("null", ((FieldDef) vFieldDefs.get(0)).getName(), "=", "31051983"); /*We make a query that hopefully :) returns no records, just the structure*/ qAux.addCondition(cAux); addParam(sbeRequest, qAux); } else { addParam(sbeRequest, q); } smRequest.saveChanges(); SOAPMessage smResponse = sendMessage(smRequest, this.getJspProperties().getProperty("url.servlet.collection")); SOAPBody sbResponse = smResponse.getSOAPBody(); if (sbResponse.hasFault()) { checkFault(sbResponse, "export"); } else { Iterator iAttachments = smResponse.getAttachments(); //response.setContentType("application/x-zip-compressed"); response.setContentType("application/zip"); String nameOk = Utils.toValidFileName(collection); response.setHeader("Content-disposition", "filename=" + nameOk + ".zip"); if (iAttachments.hasNext()) { AttachmentPart ap = (AttachmentPart) iAttachments.next(); InputStream is = ap.getDataHandler().getInputStream(); OutputStream os = response.getOutputStream(); byte[] buff = new byte[1024]; int read = 0; while ((read = is.read(buff, 0, buff.length)) != -1) { os.write(buff, 0, read); } os.flush(); //os.close(); } } } catch (Exception e) { throw e; } }
From source file:eu.domibus.ebms3.receiver.MSHWebservice.java
/** * This method persists incoming messages into the database (and handles decompression before) * * @param request the message to persist * @param legConfiguration processing information for the message * @throws SOAPException/*ww w. j av a 2 s .c o m*/ * @throws JAXBException * @throws TransformerException * @throws IOException * @throws EbMS3Exception */ //TODO: improve error handling private String persistReceivedMessage(SOAPMessage request, LegConfiguration legConfiguration, String pmodeKey, Messaging messaging) throws SOAPException, JAXBException, TransformerException, EbMS3Exception { boolean bodyloadFound = false; for (PartInfo partInfo : messaging.getUserMessage().getPayloadInfo().getPartInfo()) { String cid = partInfo.getHref(); MSHWebservice.LOG.debug("looking for attachment with cid: " + cid); boolean payloadFound = false; if (cid == null || cid.isEmpty()) { if (bodyloadFound) { throw new EbMS3Exception(EbMS3Exception.EbMS3ErrorCode.EBMS_0003, "More than one Partinfo without CID found", messaging.getUserMessage().getMessageInfo().getMessageId(), null, MSHRole.RECEIVING); } bodyloadFound = true; payloadFound = true; partInfo.setInBody(true); Node bodyContent = (((Node) request.getSOAPBody().getChildElements().next())); Source source = new DOMSource(bodyContent); ByteArrayOutputStream out = new ByteArrayOutputStream(); Result result = new StreamResult(out); Transformer transformer = this.transformerFactory.newTransformer(); transformer.transform(source, result); partInfo.setBinaryData(out.toByteArray()); } @SuppressWarnings("unchecked") Iterator<AttachmentPart> attachmentIterator = request.getAttachments(); AttachmentPart attachmentPart; while (attachmentIterator.hasNext() && !payloadFound) { attachmentPart = attachmentIterator.next(); //remove square brackets from cid for further processing attachmentPart.setContentId(AttachmentUtil.cleanContentId(attachmentPart.getContentId())); MSHWebservice.LOG.debug("comparing with: " + attachmentPart.getContentId()); if (attachmentPart.getContentId().equals(AttachmentUtil.cleanContentId(cid))) { partInfo.setBinaryData(attachmentPart.getRawContentBytes()); partInfo.setInBody(false); payloadFound = true; } } if (!payloadFound) { throw new EbMS3Exception(EbMS3Exception.EbMS3ErrorCode.EBMS_0011, "No Attachment found for cid: " + cid + " of message: " + messaging.getUserMessage().getMessageInfo().getMessageId(), messaging.getUserMessage().getMessageInfo().getMessageId(), null, MSHRole.RECEIVING); } } boolean compressed = this.compressionService.handleDecompression(messaging.getUserMessage(), legConfiguration); this.payloadProfileValidator.validate(messaging, pmodeKey); this.propertyProfileValidator.validate(messaging, pmodeKey); MSHWebservice.LOG.debug("Compression for message with id: " + messaging.getUserMessage().getMessageInfo().getMessageId() + " applied: " + compressed); MessageLogEntry messageLogEntry = new MessageLogEntry(); messageLogEntry.setMessageId(messaging.getUserMessage().getMessageInfo().getMessageId()); messageLogEntry.setMessageType(MessageType.USER_MESSAGE); messageLogEntry.setMshRole(MSHRole.RECEIVING); messageLogEntry.setReceived(new Date()); String mpc = messaging.getUserMessage().getMpc(); messageLogEntry.setMpc((mpc == null || mpc.isEmpty()) ? Mpc.DEFAULT_MPC : mpc); messageLogEntry.setMessageStatus(MessageStatus.RECEIVED); this.messageLogDao.create(messageLogEntry); this.messagingDao.create(messaging); return messageLogEntry.getMessageId(); }
From source file:nl.nn.adapterframework.extensions.cxf.SOAPProviderBase.java
@Override public SOAPMessage invoke(SOAPMessage request) { String result;// w w w. j av a2s . c o m PipeLineSessionBase pipelineSession = new PipeLineSessionBase(); String correlationId = Misc.createSimpleUUID(); log.debug(getLogPrefix(correlationId) + "received message"); if (request == null) { String faultcode = "soap:Server"; String faultstring = "SOAPMessage is null"; String httpRequestMethod = (String) webServiceContext.getMessageContext() .get(MessageContext.HTTP_REQUEST_METHOD); if (!"POST".equals(httpRequestMethod)) { faultcode = "soap:Client"; faultstring = "Request was send using '" + httpRequestMethod + "' instead of 'POST'"; } result = "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">" + "<soap:Body><soap:Fault>" + "<faultcode>" + faultcode + "</faultcode>" + "<faultstring>" + faultstring + "</faultstring>" + "</soap:Fault></soap:Body></soap:Envelope>"; } else { // Make mime headers in request available as session key @SuppressWarnings("unchecked") Iterator<MimeHeader> mimeHeaders = request.getMimeHeaders().getAllHeaders(); String mimeHeadersXml = getMimeHeadersXml(mimeHeaders).toXML(); pipelineSession.put("mimeHeaders", mimeHeadersXml); // Make attachments in request (when present) available as session keys int i = 1; XmlBuilder attachments = new XmlBuilder("attachments"); @SuppressWarnings("unchecked") Iterator<AttachmentPart> attachmentParts = request.getAttachments(); while (attachmentParts.hasNext()) { try { InputStreamAttachmentPart attachmentPart = new InputStreamAttachmentPart( attachmentParts.next()); XmlBuilder attachment = new XmlBuilder("attachment"); attachments.addSubElement(attachment); XmlBuilder sessionKey = new XmlBuilder("sessionKey"); sessionKey.setValue("attachment" + i); attachment.addSubElement(sessionKey); pipelineSession.put("attachment" + i, attachmentPart.getInputStream()); log.debug(getLogPrefix(correlationId) + "adding attachment [attachment" + i + "] to session"); @SuppressWarnings("unchecked") Iterator<MimeHeader> attachmentMimeHeaders = attachmentPart.getAllMimeHeaders(); attachment.addSubElement(getMimeHeadersXml(attachmentMimeHeaders)); } catch (SOAPException e) { e.printStackTrace(); log.warn("Could not store attachment in session key", e); } i++; } pipelineSession.put("attachments", attachments.toXML()); // Transform SOAP message to string String message; try { message = XmlUtils.nodeToString(request.getSOAPPart()); log.debug(getLogPrefix(correlationId) + "transforming from SOAP message"); } catch (TransformerException e) { String m = "Could not transform SOAP message to string"; log.error(m, e); throw new WebServiceException(m, e); } // Process message via WebServiceListener ISecurityHandler securityHandler = new WebServiceContextSecurityHandler(webServiceContext); pipelineSession.setSecurityHandler(securityHandler); pipelineSession.put(IPipeLineSession.HTTP_REQUEST_KEY, webServiceContext.getMessageContext().get(MessageContext.SERVLET_REQUEST)); pipelineSession.put(IPipeLineSession.HTTP_RESPONSE_KEY, webServiceContext.getMessageContext().get(MessageContext.SERVLET_RESPONSE)); try { log.debug(getLogPrefix(correlationId) + "processing message"); result = processRequest(correlationId, message, pipelineSession); } catch (ListenerException e) { String m = "Could not process SOAP message: " + e.getMessage(); log.error(m); throw new WebServiceException(m, e); } } // Transform result string to SOAP message SOAPMessage soapMessage = null; try { log.debug(getLogPrefix(correlationId) + "transforming to SOAP message"); soapMessage = getMessageFactory().createMessage(); StreamSource streamSource = new StreamSource(new StringReader(result)); soapMessage.getSOAPPart().setContent(streamSource); } catch (SOAPException e) { String m = "Could not transform string to SOAP message"; log.error(m); throw new WebServiceException(m, e); } String multipartXml = (String) pipelineSession.get(attachmentXmlSessionKey); log.debug(getLogPrefix(correlationId) + "building multipart message with MultipartXmlSessionKey [" + multipartXml + "]"); if (StringUtils.isNotEmpty(multipartXml)) { Element partsElement; try { partsElement = XmlUtils.buildElement(multipartXml); } catch (DomBuilderException e) { String m = "error building multipart xml"; log.error(m, e); throw new WebServiceException(m, e); } Collection<Node> parts = XmlUtils.getChildTags(partsElement, "part"); if (parts == null || parts.size() == 0) { log.warn(getLogPrefix(correlationId) + "no part(s) in multipart xml [" + multipartXml + "]"); } else { Iterator<Node> iter = parts.iterator(); while (iter.hasNext()) { Element partElement = (Element) iter.next(); //String partType = partElement.getAttribute("type"); String partName = partElement.getAttribute("name"); String partSessionKey = partElement.getAttribute("sessionKey"); String partMimeType = partElement.getAttribute("mimeType"); Object partObject = pipelineSession.get(partSessionKey); if (partObject instanceof InputStream) { InputStream fis = (InputStream) partObject; DataHandler dataHander = null; try { dataHander = new DataHandler(new ByteArrayDataSource(fis, partMimeType)); } catch (IOException e) { String m = "Unable to add session key '" + partSessionKey + "' as attachment"; log.error(m, e); throw new WebServiceException(m, e); } AttachmentPart attachmentPart = soapMessage.createAttachmentPart(dataHander); attachmentPart.setContentId(partName); soapMessage.addAttachmentPart(attachmentPart); log.debug(getLogPrefix(correlationId) + "appended filepart [" + partSessionKey + "] with value [" + partObject + "] and name [" + partName + "]"); } else { //String String partValue = (String) partObject; DataHandler dataHander = new DataHandler(new ByteArrayDataSource(partValue, partMimeType)); AttachmentPart attachmentPart = soapMessage.createAttachmentPart(dataHander); attachmentPart.setContentId(partName); soapMessage.addAttachmentPart(attachmentPart); log.debug(getLogPrefix(correlationId) + "appended stringpart [" + partSessionKey + "] with value [" + partValue + "]"); } } } } return soapMessage; }
From source file:org.apache.axis2.jaxws.handler.SoapMessageContext.java
/** * Updates information about the SOAPMessage so that * we can determine later if it has changed * @param sm SOAPMessage//from w w w . j a va2 s.c om */ private void cacheSOAPMessageInfo(SOAPMessage sm) { cachedSoapPart = null; cachedSoapEnvelope = null; cachedAttachmentParts.clear(); try { cachedSoapPart = sm.getSOAPPart(); if (cachedSoapPart != null) { cachedSoapEnvelope = cachedSoapPart.getEnvelope(); } if (sm.countAttachments() > 0) { Iterator it = sm.getAttachments(); while (it != null && it.hasNext()) { AttachmentPart ap = (AttachmentPart) it.next(); cachedAttachmentParts.add(ap); } } } catch (Throwable t) { if (log.isDebugEnabled()) { log.debug("Ignoring ", t); } } }