public void test() throws Exception { File file = new File("message.xml"); file.deleteOnExit(); MessageFactory mf = MessageFactory.newInstance(); SOAPMessage msg = createMessage(mf); // Save the soap message to file try (FileOutputStream sentFile = new FileOutputStream(file)) { msg.writeTo(sentFile); } // See if we get the image object back try (FileInputStream fin = new FileInputStream(file)) { SOAPMessage newMsg = mf.createMessage(msg.getMimeHeaders(), fin); newMsg.writeTo(new ByteArrayOutputStream()); Iterator<?> i = newMsg.getAttachments(); while (i.hasNext()) { AttachmentPart att = (AttachmentPart) i.next(); Object obj = att.getContent(); if (!(obj instanceof StreamSource)) { fail("Got incorrect attachment type [" + obj.getClass() + "], " + "expected [javax.xml.transform.stream.StreamSource]"); } } } }
/** * Returns a string containing info about all the SOAP attachments. * * @param soapMessage SOAP message * @return String containing attachments info */ public static String getAttachmentsInfo(SOAPMessage soapMessage) { try { int numOfAttachments = soapMessage.countAttachments(); Iterator attachments = soapMessage.getAttachments(); StringBuilder buf = new StringBuilder("Number of attachments: "); buf.append(numOfAttachments); int count = 1; while (attachments.hasNext()) { AttachmentPart attachment = (AttachmentPart) attachments.next(); buf.append(" | #").append(count); buf.append(" | Content Location: ").append(attachment.getContentLocation()); buf.append(" | Content Id: ").append(attachment.getContentId()); buf.append(" | Content Size: ").append(attachment.getSize()); buf.append(" | Content Type: ").append(attachment.getContentType()); count++; } return buf.toString(); } catch (SOAPException e) { LOGGER.error(e.getMessage(), e); return ""; } }
private SOAPMessage createMessage(MessageFactory mf) throws SOAPException, IOException { SOAPMessage msg = mf.createMessage(); SOAPEnvelope envelope = msg.getSOAPPart().getEnvelope(); Name name = envelope.createName("hello", "ex", "http://example.com"); envelope.getBody().addChildElement(name).addTextNode("THERE!"); String s = "<root><hello>THERE!</hello></root>"; AttachmentPart ap = msg.createAttachmentPart( new StreamSource(new ByteArrayInputStream(s.getBytes())), "text/xml" ); msg.addAttachmentPart(ap); msg.saveChanges(); return msg; }
public void parseAll() throws MessagingException { if (parsed) { return; } if (soapPart == null) { readSOAPPart(); } List<MIMEPart> prts = mm.getAttachments(); for(MIMEPart part : prts) { if (part != soapPart) { AttachmentPart attach = new AttachmentPartImpl(part); this.addBodyPart(new MimeBodyPart(part)); } } parsed = true; }
/** * Searches the attachment with the given content id and returns its string * contents. If there's no attachment with the given content id or its value * is not a string, null is returned. * * @param contentId content id of the attachment * @param attachments list of attachments to be searched * @return string value of the attachment or null */ public static String getStringAttachment(String contentId, Iterator attachments) { if (attachments == null) { return null; } try { while (attachments.hasNext()) { AttachmentPart att = (AttachmentPart) attachments.next(); if (att.getContentId().equals(contentId)) { return new Scanner(att.getRawContent(), CHARSET).useDelimiter("\\A").next(); } } } catch (Exception e) { LOGGER.error(e.getMessage(), e); } return null; }
/** * Get the payload from the SOAP response. This should be called * during {@link #onResponse()}. * * @return A set of payload in SOAP message. * * @throws SOAPException * When unable to extract the payload in the SOAP Response. * @throws IOException * When unable to open the input stream for the payload. */ public Payload[] getResponsePayloads() throws SOAPException, IOException{ if (this.response == null) return null; int index = 0; Iterator itr = this.response.getAttachments(); Payload[] payloads = new Payload[this.response.countAttachments()]; while(itr.hasNext()){ AttachmentPart ap = (AttachmentPart) itr.next(); payloads[index] = new Payload( ap.getDataHandler().getInputStream(), ap.getContentType()); index++; } return payloads; }
@Override public Payload[] getResponsePayloads() throws SOAPException ,IOException { if (this.response == null) return null; int index = 0; Iterator itr = this.response.getAttachments(); Payload[] payloads = new Payload[this.response.countAttachments()]; while(itr.hasNext()){ AttachmentPart ap = (AttachmentPart) itr.next(); payloads[index] = new Payload( ap.getDataHandler().getInputStream(), ap.getContentType()); //Retrieve filename of the payload String filename = retrieveAttachmentFilename(ap); if(filename != null){ payloads[index].setFilePath(filename); this.log.log("Payload filename: " + filename); } index++; } return payloads; }
@Override protected boolean handleInbound(SOAPMessageContext msgContext) { SOAPMessage soapMessage = msgContext.getMessage(); Iterator<?> it = soapMessage.getAttachments(); while(it.hasNext()) { try { AttachmentPart attachment = (AttachmentPart)it.next(); System.out.println("Recv " + attachment.getContentType() + " attachment:"); System.out.println("'"+attachment.getContent()+"'"); return true; } catch (SOAPException e) { throw new RuntimeException("Failed to access attachment data"); } } throw new IllegalStateException("Missing attachment on the client side"); }
@Test @RunAsClient public void testSendMultipartSoapMessage() throws Exception { final MessageFactory msgFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL); final SOAPMessage msg = msgFactory.createMessage(); final SOAPBodyElement bodyElement = msg.getSOAPBody().addBodyElement( new QName("urn:ledegen:soap-attachment:1.0", "echoImage")); bodyElement.addTextNode("cid:" + IN_IMG_NAME); final AttachmentPart ap = msg.createAttachmentPart(); ap.setDataHandler(getResource("saaj/jbws3857/" + IN_IMG_NAME)); ap.setContentId(IN_IMG_NAME); msg.addAttachmentPart(ap); final SOAPConnectionFactory conFactory = SOAPConnectionFactory.newInstance(); final SOAPConnection connection = conFactory.createConnection(); final SOAPMessage response = connection.call(msg, new URL("http://" + baseURL.getHost()+ ":" + baseURL.getPort() + "/" + PROJECT_NAME + "/testServlet")); final String contentTypeWeHaveSent = getBodyElementTextValue(response); assertContentTypeStarts("multipart/related", contentTypeWeHaveSent); }
@Override protected void serializeRequest(ServiceRequest request, SOAPElement soapRequest, SOAPEnvelope envelope) throws SOAPException { // Get TestServiceRequest object TestServiceRequest testServiceRequest = (TestServiceRequest) request.getRequestData(); // Add responseBodySize element SOAPElement responseBodySize = soapRequest.addChildElement(envelope.createName("responseBodySize")); responseBodySize.addTextNode(testServiceRequest.getResponseBodySize()); // Add responseAttachmentSize element SOAPElement responseAttachmentSize = soapRequest.addChildElement(envelope.createName("responseAttachmentSize")); responseAttachmentSize.addTextNode(testServiceRequest.getResponseAttachmentSize()); // Add request payload SOAPElement payload = soapRequest.addChildElement(envelope.createName("payload")); payload.addTextNode(testServiceRequest.getRequestPayload()); // Add request attachment if (testServiceRequest.getRequestAttachment() != null && !testServiceRequest.getRequestAttachment().isEmpty()) { String attachment = "<attachmentData>" + testServiceRequest.getRequestAttachment() + "</attachmentData>"; AttachmentPart attachPart = request.getSoapMessage().createAttachmentPart(attachment, "text/xml"); attachPart.setContentId("attachment_id"); request.getSoapMessage().addAttachmentPart(attachPart); } }
private String getOperationFromSOAPAttachment(Iterator<AttachmentPart> it) throws SOAPException { AttachmentPart opAttachment = null; while (it.hasNext()) { opAttachment = it.next(); if ("<operation>".equals(opAttachment.getContentId())) { System.out.println("Found operation in SOAP attachment"); return opAttachment.getContent().toString(); } } return null; }
/** * Updates information about the SOAPMessage so that * we can determine later if it has changed * @param sm SOAPMessage */ 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); } } }
/** * Very simple operation. * If there are no attachments, an exception is thrown. * Otherwise the message is echoed. */ public SOAPMessage invoke(SOAPMessage soapMessage) { System.out.println(">> SoapMessageCheckMTOMProvider: Request received."); int numAttachments = soapMessage.countAttachments(); if (numAttachments == 0) { System.out.println(">> SoapMessageCheckMTOMProvider: No Attachments."); throw new WebServiceException("No Attachments are detected"); } SOAPMessage response = null; try { MessageFactory factory = MessageFactory.newInstance(); response = factory.createMessage(); SOAPPart soapPart = response.getSOAPPart(); SOAPBody soapBody = soapPart.getEnvelope().getBody(); soapBody.addChildElement((SOAPBodyElement) soapMessage. getSOAPBody().getChildElements().next()); response.addAttachmentPart((AttachmentPart) soapMessage.getAttachments().next()); } catch (SOAPException e) { throw new WebServiceException(e); } System.out.println(">> SoapMessageCheckMTOMProvider: Returning."); return response; // echo back the same message }
/** * Get the response for an XML and an Attachment request * @param request * @param dataElement * @return SOAPMessage */ private SOAPMessage getXMLAttachmentResponse(SOAPMessage request, SOAPElement dataElement) throws Exception { SOAPMessage response; // Additional assertion checks assertTrue(countAttachments(request) == 1); AttachmentPart requestAP = (AttachmentPart) request.getAttachments().next(); StreamSource contentSS = (StreamSource) requestAP.getContent(); String content = getAsString(contentSS); assertTrue(content.contains(SoapMessageProvider.TEXT_XML_ATTACHMENT)); // Build the Response MessageFactory factory = MessageFactory.newInstance(); String responseXML = responseMsgStart + ATTACHMENT_RETURN + responseMsgEnd; response = factory.createMessage(null, new ByteArrayInputStream(responseXML.getBytes())); // Create and attach the attachment AttachmentPart ap = response.createAttachmentPart(SoapMessageProvider.TEXT_XML_ATTACHMENT, "text/xml"); ap.setContentId(ID); response.addAttachmentPart(ap); return response; }
/** * Get the response for an XML and an MTOM Attachment request * @param request * @param dataElement * @return SOAPMessage */ private SOAPMessage getXMLSWARefResponse(SOAPMessage request, SOAPElement dataElement) throws Exception { SOAPMessage response; // Additional assertion checks assertTrue(countAttachments(request) == 1); AttachmentPart requestAP = (AttachmentPart) request.getAttachments().next(); assertTrue(requestAP.getContentId().equals(ID)); StreamSource contentSS = (StreamSource) requestAP.getContent(); String content = getAsString(contentSS); assertTrue(content.contains(SoapMessageProvider.TEXT_XML_ATTACHMENT)); // Build the Response MessageFactory factory = MessageFactory.newInstance(); String responseXML = responseMsgStart + SWAREF_RETURN + responseMsgEnd; response = factory.createMessage(null, new ByteArrayInputStream(responseXML.getBytes())); // Create and attach the attachment AttachmentPart ap = response.createAttachmentPart(SoapMessageProvider.TEXT_XML_ATTACHMENT, "text/xml"); ap.setContentId(ID); response.addAttachmentPart(ap); return response; }
/** * Removes all the AttachmentPart objects that have header entries that match the specified * headers. Note that the removed attachment could have headers in addition to those specified. * * @param headers - a MimeHeaders object containing the MIME headers for which to search * @since SAAJ 1.3 */ public void removeAttachments(MimeHeaders headers) { Collection<AttachmentPart> newAttachmentParts = new ArrayList<AttachmentPart>(); for (AttachmentPart attachmentPart : attachmentParts) { //Get all the headers for (Iterator iterator = headers.getAllHeaders(); iterator.hasNext();) { MimeHeader mimeHeader = (MimeHeader)iterator.next(); String[] headerValues = attachmentPart.getMimeHeader(mimeHeader.getName()); //if values for this header name, do not remove it if (headerValues.length != 0) { if (!(headerValues[0].equals(mimeHeader.getValue()))) { newAttachmentParts.add(attachmentPart); } } } } attachmentParts.clear(); this.attachmentParts = newAttachmentParts; }
/** * Convert a SAAJ message to an Axiom SOAP envelope object and process xop:Include * elements. * * @param message the SAAJ message * @return the OM SOAP envelope * @throws SOAPException */ public static org.apache.axiom.soap.SOAPEnvelope toOMSOAPEnvelope( javax.xml.soap.SOAPMessage message) throws SOAPException { Attachments attachments = new Attachments(); for (Iterator it = message.getAttachments(); it.hasNext(); ) { AttachmentPart attachment = (AttachmentPart)it.next(); String contentId = attachment.getContentId(); if (contentId != null) { DataHandler dh = attachment.getDataHandler(); if (dh == null) { throw new SOAPException("Attachment with NULL DataHandler"); } if (contentId.startsWith("<") && contentId.endsWith(">")) { contentId = contentId.substring(1, contentId.length()-1); } attachments.addDataHandler(contentId, dh); } } OMElement docElem = (OMElement)message.getSOAPPart().getDocumentElement(); MTOMStAXSOAPModelBuilder builder = new MTOMStAXSOAPModelBuilder(docElem.getXMLStreamReader(), attachments); return builder.getSOAPEnvelope(); }
@Validated @Test public void testCallMTOM() throws Exception { MessageFactory mf = MessageFactory.newInstance(); MimeHeaders headers = new MimeHeaders(); headers.addHeader("Content-Type", TestUtils.MTOM_TEST_MESSAGE_CONTENT_TYPE); InputStream in = TestUtils.getTestFile(TestUtils.MTOM_TEST_MESSAGE_FILE); SOAPMessage request = mf.createMessage(headers, in); SOAPEnvelope envelope = request.getSOAPPart().getEnvelope(); // Remove the headers since they have mustunderstand=1 envelope.getHeader().removeContents(); // Change the name of the body content so that the request is routed to the echo service ((SOAPElement)envelope.getBody().getChildElements().next()).setElementQName(new QName("echo")); SOAPConnection sCon = SOAPConnectionFactory.newInstance().createConnection(); SOAPMessage response = sCon.call(request, getAddress()); sCon.close(); SOAPPart soapPart = response.getSOAPPart(); SOAPElement textElement = (SOAPElement)soapPart.getEnvelope().getElementsByTagName("text").item(0); AttachmentPart ap = response.getAttachment((SOAPElement)textElement.getChildNodes().item(0)); assertNotNull(ap); }
@Validated @Test public void testGetContent() throws Exception { try { MessageFactory factory = MessageFactory.newInstance(); SOAPMessage msg = factory.createMessage(); AttachmentPart ap = msg.createAttachmentPart(); Image image = ImageIO.read(TestUtils.getTestFileURL("attach.gif")); ap = msg.createAttachmentPart(image, "image/gif"); //Getting Content should return an Image object Object o = ap.getContent(); if (o != null) { if (o instanceof Image) { //Image object was returned (ok) } else { fail("Unexpected object was returned"); } } } catch (Exception e) { fail("Exception: " + e); } }
private static void assertAttachmentsAreEqual(SOAPMessage expected, SOAPMessage actual) throws Exception { int expectedNumAttachments = expected.countAttachments(); int actualNumAttachments = actual.countAttachments(); if (expectedNumAttachments != actualNumAttachments) { throw new Exception( "expectedNumAttachments=" + expectedNumAttachments + "actualNumAttachments=" + actualNumAttachments); } Iterator<?> expectedAttachmentIterator = expected.getAttachments(); Iterator<?> actualAttachmentIterator = actual.getAttachments(); for (int attachmentIndex = 0; attachmentIndex < actualNumAttachments; attachmentIndex++) { AttachmentPart expectedAttachment = (AttachmentPart) expectedAttachmentIterator.next(); AttachmentPart actualAttachment = (AttachmentPart) actualAttachmentIterator.next(); assertEquals(expectedAttachment, actualAttachment, attachmentIndex); } }
/** * Default implementation that uses {@link #writeTo(ContentHandler, ErrorHandler)} */ public SOAPMessage readAsSOAPMessage() throws SOAPException { SOAPMessage msg = soapVersion.saajMessageFactory.createMessage(); SAX2DOMEx s2d = new SAX2DOMEx(msg.getSOAPPart()); try { writeTo(s2d, XmlUtil.DRACONIAN_ERROR_HANDLER); } catch (SAXException e) { throw new SOAPException(e); } for(Attachment att : getAttachments()) { AttachmentPart part = msg.createAttachmentPart(); part.setDataHandler(att.asDataHandler()); part.setContentId('<'+att.getContentId()+'>'); msg.addAttachmentPart(part); } return msg; }
private SOAPMessage createRequest(Element bodyElement, String contentLocation) throws SOAPException { SOAPMessage msg = MessageFactory.newInstance().createMessage(); SOAPPart soapPart = msg.getSOAPPart(); SOAPEnvelope soapEnvelope = soapPart.getEnvelope(); SOAPBody soapBody = soapEnvelope.getBody(); SOAPElement attachment = soapBody.addChildElement(soapEnvelope.createName("Attachment")); attachment.addAttribute(soapEnvelope.createName("href"), contentLocation); AttachmentPart ap = msg.createAttachmentPart(); DOMSource apSource = new DOMSource(bodyElement); ap.setContent(apSource, "text/xml"); ap.setContentLocation(contentLocation); msg.addAttachmentPart(ap); return msg; }
@Override public void writeTo(SOAPMessage saaj) throws SOAPException { AttachmentPart part = saaj.createAttachmentPart(); part.setDataHandler(asDataHandler()); part.setContentId(contentId); saaj.addAttachmentPart(part); }
static protected void addAttachmentsToSOAPMessage(SOAPMessage msg, Message message) { for(Attachment att : message.getAttachments()) { AttachmentPart part = msg.createAttachmentPart(); part.setDataHandler(att.asDataHandler()); // Be safe and avoid double angle-brackets. String cid = att.getContentId(); if (cid != null) { if (cid.startsWith("<") && cid.endsWith(">")) part.setContentId(cid); else part.setContentId('<' + cid + '>'); } // Add any MIME headers beside Content-ID, which is already // accounted for above, and Content-Type, which is provided // by the DataHandler above. if (att instanceof AttachmentEx) { AttachmentEx ax = (AttachmentEx) att; Iterator<AttachmentEx.MimeHeader> imh = ax.getMimeHeaders(); while (imh.hasNext()) { AttachmentEx.MimeHeader ame = imh.next(); if ((!"Content-ID".equals(ame.getName())) && (!"Content-Type".equals(ame.getName()))) part.addMimeHeader(ame.getName(), ame.getValue()); } } msg.addAttachmentPart(part); } }
/** * Converts the given attachment part to string. * * @param att attachment part to be converted * @return string presentation of the attachment or null */ public static String toString(AttachmentPart att) { try { return new Scanner(att.getRawContent(), CHARSET).useDelimiter("\\A").next(); } catch (Exception e) { LOGGER.error(e.getMessage(), e); } return null; }
/** * Returns the content type of the first SOAP attachment or null if there's * no attachments. * * @param message SOAP message * @return content type of the first attachment or null */ public static String getAttachmentContentType(SOAPMessage message) { if (message.countAttachments() == 0) { return null; } AttachmentPart att = (AttachmentPart) message.getAttachments().next(); return att.getContentType(); }
/** * This method sends a file as an attachment then * receives it as a return. The returned file is * compared to the source. Uses SAAJ API. * @param The filename that is the source to send. * @return True if sent and compared. */ public boolean echoUsingSAAJ(String filename) throws Exception { String endPointURLString = "http://localhost:" +opts.getPort() + "/axis/services/urn:EchoAttachmentsService"; SOAPConnectionFactory soapConnectionFactory = javax.xml.soap.SOAPConnectionFactory.newInstance(); SOAPConnection soapConnection = soapConnectionFactory.createConnection(); MessageFactory messageFactory = MessageFactory.newInstance(); SOAPMessage soapMessage = messageFactory.createMessage(); SOAPPart soapPart = soapMessage.getSOAPPart(); SOAPEnvelope requestEnvelope = soapPart.getEnvelope(); SOAPBody body = requestEnvelope.getBody(); SOAPBodyElement operation = body.addBodyElement (requestEnvelope.createName("echo")); Vector dataHandlersToAdd = new Vector(); dataHandlersToAdd.add(new DataHandler(new FileDataSource(new File(filename)))); if (dataHandlersToAdd != null) { ListIterator dataHandlerIterator = dataHandlersToAdd.listIterator(); while (dataHandlerIterator.hasNext()) { DataHandler dataHandler = (DataHandler) dataHandlerIterator.next(); javax.xml.soap.SOAPElement element = operation.addChildElement(requestEnvelope.createName("source")); javax.xml.soap.AttachmentPart attachment = soapMessage.createAttachmentPart(dataHandler); soapMessage.addAttachmentPart(attachment); element.addAttribute(requestEnvelope.createName ("href"), "cid:" + attachment.getContentId()); } } javax.xml.soap.SOAPMessage returnedSOAPMessage = soapConnection.call(soapMessage, endPointURLString); Iterator iterator = returnedSOAPMessage.getAttachments(); if (!iterator.hasNext()) { //The wrong type of object that what was expected. System.out.println("Received problem response from server"); throw new AxisFault("", "Received problem response from server", null, null); } //Still here, so far so good. //Now lets brute force compare the source attachment // to the one we received. DataHandler rdh = (DataHandler) ((AttachmentPart)iterator.next()).getDataHandler(); //From here we'll just treat the data resource as file. String receivedfileName = rdh.getName();//Get the filename. if (receivedfileName == null) { System.err.println("Could not get the file name."); throw new AxisFault("", "Could not get the file name.", null, null); } System.out.println("Going to compare the files.."); boolean retv = compareFiles(filename, receivedfileName); java.io.File receivedFile = new java.io.File(receivedfileName); receivedFile.delete(); return retv; }
void addSoapAttachement() { try { MessageFactory messageFactory = MessageFactory.newInstance(); SOAPMessage message = messageFactory.createMessage(); AttachmentPart a = message.createAttachmentPart(); a.setContentType("binary/octet-stream"); message.addAttachmentPart(a); } catch (SOAPException e) { e.printStackTrace(); } }