Example usage for javax.xml.soap SOAPMessage createAttachmentPart

List of usage examples for javax.xml.soap SOAPMessage createAttachmentPart

Introduction

In this page you can find the example usage for javax.xml.soap SOAPMessage createAttachmentPart.

Prototype

public abstract AttachmentPart createAttachmentPart();

Source Link

Document

Creates a new empty AttachmentPart object.

Usage

From source file:com.googlecode.ddom.saaj.SOAPMessageTest.java

@Validated
@Test/*from  ww w.  j  a  v  a 2  s  .com*/
public void testCreateAttachmentPart() throws Exception {
    SOAPMessage message = getFactory().createMessage();
    message.createAttachmentPart();
    // The attachment part is not added to the message
    assertEquals(0, message.countAttachments());
}

From source file:com.googlecode.ddom.saaj.SOAPMessageTest.java

@Validated
@Test/*  w  w w .ja v  a  2  s  . c  o m*/
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.googlecode.ddom.saaj.SOAPMessageTest.java

@Validated
@Test//from   w w  w  .j  ava2  s .  c o  m
public void testGetAttachmentsFiltered() throws Exception {
    SOAPMessage message = getFactory().createMessage();

    AttachmentPart att1 = message.createAttachmentPart();
    att1.addMimeHeader("Content-Type", "text/plain");
    message.addAttachmentPart(att1);

    AttachmentPart att2 = message.createAttachmentPart();
    att2.addMimeHeader("Content-Type", "application/octet-stream");
    message.addAttachmentPart(att2);

    AttachmentPart att3 = message.createAttachmentPart();
    att3.addMimeHeader("Content-ID", "<123456@example.com>");
    att3.addMimeHeader("Content-Type", "text/plain");
    message.addAttachmentPart(att3);

    MimeHeaders headers = new MimeHeaders();
    headers.addHeader("Content-Type", "text/plain");
    Iterator it = message.getAttachments(headers);
    assertTrue(it.hasNext());
    assertSame(att1, it.next());
    assertTrue(it.hasNext());
    assertSame(att3, it.next());
    assertFalse(it.hasNext());
}

From source file:com.googlecode.ddom.saaj.SOAPMessageTest.java

@Validated
@Test//from  w  w  w.j  av a  2  s.c o  m
public void testWriteToWithAttachment() throws Exception {
    SOAPMessage message = getFactory().createMessage();
    message.getSOAPPart().getEnvelope().getBody().addBodyElement(new QName("urn:ns", "test", "p"));
    AttachmentPart attachment = message.createAttachmentPart();
    attachment.setDataHandler(new DataHandler("This is a test", "text/plain; charset=iso-8859-15"));
    message.addAttachmentPart(attachment);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    message.writeTo(baos);
    System.out.write(baos.toByteArray());
    MimeMultipart mp = new MimeMultipart(new ByteArrayDataSource(baos.toByteArray(), "multipart/related"));
    assertEquals(2, mp.getCount());
    BodyPart part1 = mp.getBodyPart(0);
    // TODO
    //        assertEquals(messageSet.getVersion().getContentType(), part1.getContentType());
    BodyPart part2 = mp.getBodyPart(1);
    // Note: text/plain is the default content type, so we need to include the parameters in the assertion
    assertEquals("text/plain; charset=iso-8859-15", part2.getContentType());
}

From source file:com.mirth.connect.connectors.ws.WebServiceMessageDispatcher.java

private void processMessage(MessageObject mo) throws Exception {
    /*//from  w  w w .  j a  v a 2s. c o  m
     * Initialize the dispatch object if it hasn't been initialized yet, or
     * create a new one if the connector properties have changed due to
     * variables.
     */
    createDispatch(mo);

    SOAPBinding soapBinding = (SOAPBinding) dispatch.getBinding();

    if (connector.isDispatcherUseAuthentication()) {
        dispatch.getRequestContext().put(BindingProvider.USERNAME_PROPERTY, currentUsername);
        dispatch.getRequestContext().put(BindingProvider.PASSWORD_PROPERTY, currentPassword);
        logger.debug("Using authentication: username=" + currentUsername + ", password length="
                + currentPassword.length());
    }

    // See: http://www.w3.org/TR/2000/NOTE-SOAP-20000508/#_Toc478383528
    String soapAction = replacer.replaceValues(connector.getDispatcherSoapAction(), mo);

    if (StringUtils.isNotEmpty(soapAction)) {
        dispatch.getRequestContext().put(BindingProvider.SOAPACTION_URI_PROPERTY, soapAction);
    }

    // build the message
    logger.debug("Creating SOAP envelope.");
    String content = replacer.replaceValues(connector.getDispatcherEnvelope(), mo);
    Source source = new StreamSource(new StringReader(content));
    SOAPMessage message = soapBinding.getMessageFactory().createMessage();
    message.getSOAPPart().setContent(source);

    if (connector.isDispatcherUseMtom()) {
        soapBinding.setMTOMEnabled(true);

        List<String> attachmentIds = connector.getDispatcherAttachmentNames();
        List<String> attachmentContents = connector.getDispatcherAttachmentContents();
        List<String> attachmentTypes = connector.getDispatcherAttachmentTypes();

        for (int i = 0; i < attachmentIds.size(); i++) {
            String attachmentContentId = replacer.replaceValues(attachmentIds.get(i), mo);
            String attachmentContentType = replacer.replaceValues(attachmentTypes.get(i), mo);
            String attachmentContent = replacer.replaceValues(attachmentContents.get(i), mo);

            AttachmentPart attachment = message.createAttachmentPart();
            attachment.setBase64Content(new ByteArrayInputStream(attachmentContent.getBytes("UTF-8")),
                    attachmentContentType);
            attachment.setContentId(attachmentContentId);
            message.addAttachmentPart(attachment);
        }
    }

    message.saveChanges();

    // make the call
    String response = null;
    if (connector.isDispatcherOneWay()) {
        logger.debug("Invoking one way service...");
        dispatch.invokeOneWay(message);
        response = "Invoked one way operation successfully.";
    } else {
        logger.debug("Invoking web service...");
        SOAPMessage result = dispatch.invoke(message);
        response = sourceToXmlString(result.getSOAPPart().getContent());
    }
    logger.debug("Finished invoking web service, got result.");

    // process the result
    messageObjectController.setSuccess(mo, response, null);

    // send to reply channel
    if (connector.getDispatcherReplyChannelId() != null
            && !connector.getDispatcherReplyChannelId().equals("sink")) {
        new VMRouter().routeMessageByChannelId(connector.getDispatcherReplyChannelId(), response, true);
    }
}

From source file:com.mirth.connect.connectors.ws.WebServiceDispatcher.java

@Override
public Response send(ConnectorProperties connectorProperties, ConnectorMessage connectorMessage) {
    WebServiceDispatcherProperties webServiceDispatcherProperties = (WebServiceDispatcherProperties) connectorProperties;

    eventController.dispatchEvent(new ConnectionStatusEvent(getChannelId(), getMetaDataId(),
            getDestinationName(), ConnectionStatusEventType.SENDING));

    String responseData = null;/*from  w  w  w  . j  a  va  2  s  .  c o m*/
    String responseError = null;
    String responseStatusMessage = null;
    Status responseStatus = Status.QUEUED;
    boolean validateResponse = false;

    try {
        long dispatcherId = getDispatcherId();
        DispatchContainer dispatchContainer = dispatchContainers.get(dispatcherId);
        if (dispatchContainer == null) {
            dispatchContainer = new DispatchContainer();
            dispatchContainers.put(dispatcherId, dispatchContainer);
        }

        /*
         * Initialize the dispatch object if it hasn't been initialized yet, or create a new one
         * if the connector properties have changed due to variables.
         */
        createDispatch(webServiceDispatcherProperties, dispatchContainer);

        Dispatch<SOAPMessage> dispatch = dispatchContainer.getDispatch();

        configuration.configureDispatcher(this, webServiceDispatcherProperties, dispatch.getRequestContext());

        SOAPBinding soapBinding = (SOAPBinding) dispatch.getBinding();

        if (webServiceDispatcherProperties.isUseAuthentication()) {
            String currentUsername = dispatchContainer.getCurrentUsername();
            String currentPassword = dispatchContainer.getCurrentPassword();

            dispatch.getRequestContext().put(BindingProvider.USERNAME_PROPERTY, currentUsername);
            dispatch.getRequestContext().put(BindingProvider.PASSWORD_PROPERTY, currentPassword);
            logger.debug("Using authentication: username=" + currentUsername + ", password length="
                    + currentPassword.length());
        }

        // See: http://www.w3.org/TR/2000/NOTE-SOAP-20000508/#_Toc478383528
        String soapAction = webServiceDispatcherProperties.getSoapAction();

        if (StringUtils.isNotEmpty(soapAction)) {
            dispatch.getRequestContext().put(BindingProvider.SOAPACTION_USE_PROPERTY, true); // MIRTH-2109
            dispatch.getRequestContext().put(BindingProvider.SOAPACTION_URI_PROPERTY, soapAction);
        }

        // Get default headers
        Map<String, List<String>> requestHeaders = new HashMap<String, List<String>>(
                dispatchContainer.getDefaultRequestHeaders());

        // Add custom headers
        if (MapUtils.isNotEmpty(webServiceDispatcherProperties.getHeaders())) {
            for (Entry<String, List<String>> entry : webServiceDispatcherProperties.getHeaders().entrySet()) {
                List<String> valueList = requestHeaders.get(entry.getKey());

                if (valueList == null) {
                    valueList = new ArrayList<String>();
                    requestHeaders.put(entry.getKey(), valueList);
                }

                valueList.addAll(entry.getValue());
            }
        }

        dispatch.getRequestContext().put(MessageContext.HTTP_REQUEST_HEADERS, requestHeaders);

        // build the message
        logger.debug("Creating SOAP envelope.");
        AttachmentHandlerProvider attachmentHandlerProvider = getAttachmentHandlerProvider();
        String content = attachmentHandlerProvider.reAttachMessage(webServiceDispatcherProperties.getEnvelope(),
                connectorMessage);
        Source source = new StreamSource(new StringReader(content));
        SOAPMessage message = soapBinding.getMessageFactory().createMessage();
        message.getSOAPPart().setContent(source);

        if (webServiceDispatcherProperties.isUseMtom()) {
            soapBinding.setMTOMEnabled(true);

            List<String> attachmentIds = webServiceDispatcherProperties.getAttachmentNames();
            List<String> attachmentContents = webServiceDispatcherProperties.getAttachmentContents();
            List<String> attachmentTypes = webServiceDispatcherProperties.getAttachmentTypes();

            for (int i = 0; i < attachmentIds.size(); i++) {
                String attachmentContentId = attachmentIds.get(i);
                String attachmentContentType = attachmentTypes.get(i);
                String attachmentContent = attachmentHandlerProvider.reAttachMessage(attachmentContents.get(i),
                        connectorMessage);

                AttachmentPart attachment = message.createAttachmentPart();
                attachment.setBase64Content(new ByteArrayInputStream(attachmentContent.getBytes("UTF-8")),
                        attachmentContentType);
                attachment.setContentId(attachmentContentId);
                message.addAttachmentPart(attachment);
            }
        }

        message.saveChanges();

        if (StringUtils.isNotBlank(webServiceDispatcherProperties.getLocationURI())) {
            dispatch.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY,
                    webServiceDispatcherProperties.getLocationURI());
        }

        boolean redirect = false;
        int tryCount = 0;

        /*
         * Attempt the invocation until we hit the maximum allowed redirects. The redirections
         * we handle are when the scheme changes (i.e. from HTTP to HTTPS).
         */
        do {
            redirect = false;
            tryCount++;

            try {
                DispatchTask<SOAPMessage> task = new DispatchTask<SOAPMessage>(dispatch, message,
                        webServiceDispatcherProperties.isOneWay());
                SOAPMessage result;

                /*
                 * If the timeout is set to zero, we need to do the invocation in a separate
                 * thread. This is because there's no way to get a reference to the underlying
                 * JAX-WS socket, so there's no way to forcefully halt the dispatch. If the
                 * socket is truly hung and the user halts the channel, the best we can do is
                 * just interrupt and ignore the thread. This means that a thread leak is
                 * potentially introduced, so we need to notify the user appropriately.
                 */
                if (timeout == 0) {
                    // Submit the task to an executor so that it's interruptible
                    Future<SOAPMessage> future = executor.submit(task);
                    // Keep track of the task by adding it to our set
                    dispatchTasks.add(task);
                    result = future.get();
                } else {
                    // Call the task directly
                    result = task.call();
                }

                if (webServiceDispatcherProperties.isOneWay()) {
                    responseStatusMessage = "Invoked one way operation successfully.";
                } else {
                    responseData = sourceToXmlString(result.getSOAPPart().getContent());
                    responseStatusMessage = "Invoked two way operation successfully.";
                }
                logger.debug("Finished invoking web service, got result.");

                // Automatically accept message; leave it up to the response transformer to find SOAP faults
                responseStatus = Status.SENT;
            } catch (Throwable e) {
                // Unwrap the exception if it came from the executor
                if (e instanceof ExecutionException && e.getCause() != null) {
                    e = e.getCause();
                }

                // If the dispatch was interrupted, make sure to reset the interrupted flag
                if (e instanceof InterruptedException) {
                    Thread.currentThread().interrupt();
                }

                Integer responseCode = null;
                String location = null;

                if (dispatch.getResponseContext() != null) {
                    responseCode = (Integer) dispatch.getResponseContext()
                            .get(MessageContext.HTTP_RESPONSE_CODE);

                    Map<String, List<String>> headers = (Map<String, List<String>>) dispatch
                            .getResponseContext().get(MessageContext.HTTP_RESPONSE_HEADERS);
                    if (MapUtils.isNotEmpty(headers)) {
                        List<String> locations = headers.get("Location");
                        if (CollectionUtils.isNotEmpty(locations)) {
                            location = locations.get(0);
                        }
                    }
                }

                if (tryCount < MAX_REDIRECTS && responseCode != null && responseCode >= 300
                        && responseCode < 400 && StringUtils.isNotBlank(location)) {
                    redirect = true;

                    // Replace the endpoint with the redirected URL
                    dispatch.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, location);
                } else {
                    // Leave the response status as QUEUED for NoRouteToHostException and ConnectException, otherwise ERROR
                    if (e instanceof NoRouteToHostException
                            || ((e.getCause() != null) && (e.getCause() instanceof NoRouteToHostException))) {
                        responseStatusMessage = ErrorMessageBuilder.buildErrorResponse("HTTP transport error",
                                e);
                        responseError = ErrorMessageBuilder.buildErrorMessage(connectorProperties.getName(),
                                "HTTP transport error", e);
                        eventController.dispatchEvent(
                                new ErrorEvent(getChannelId(), getMetaDataId(), connectorMessage.getMessageId(),
                                        ErrorEventType.DESTINATION_CONNECTOR, getDestinationName(),
                                        connectorProperties.getName(), "HTTP transport error.", e));
                    } else if ((e.getClass() == ConnectException.class) || ((e.getCause() != null)
                            && (e.getCause().getClass() == ConnectException.class))) {
                        responseStatusMessage = ErrorMessageBuilder.buildErrorResponse("Connection refused.",
                                e);
                        eventController.dispatchEvent(new ErrorEvent(getChannelId(), getMetaDataId(),
                                connectorMessage.getMessageId(), ErrorEventType.DESTINATION_CONNECTOR,
                                getDestinationName(), connectorProperties.getName(), "Connection refused.", e));
                    } else {
                        if (e instanceof SOAPFaultException) {
                            try {
                                responseData = new DonkeyElement(((SOAPFaultException) e).getFault()).toXml();
                            } catch (DonkeyElementException e2) {
                            }
                        }
                        responseStatus = Status.ERROR;
                        responseStatusMessage = ErrorMessageBuilder
                                .buildErrorResponse("Error invoking web service", e);
                        responseError = ErrorMessageBuilder.buildErrorMessage(connectorProperties.getName(),
                                "Error invoking web service", e);
                        eventController.dispatchEvent(
                                new ErrorEvent(getChannelId(), getMetaDataId(), connectorMessage.getMessageId(),
                                        ErrorEventType.DESTINATION_CONNECTOR, getDestinationName(),
                                        connectorProperties.getName(), "Error invoking web service.", e));
                    }
                }
            }
        } while (redirect && tryCount < MAX_REDIRECTS);
    } catch (Exception e) {
        responseStatusMessage = ErrorMessageBuilder.buildErrorResponse("Error creating web service dispatch",
                e);
        responseError = ErrorMessageBuilder.buildErrorMessage(connectorProperties.getName(),
                "Error creating web service dispatch", e);
        eventController.dispatchEvent(new ErrorEvent(getChannelId(), getMetaDataId(),
                connectorMessage.getMessageId(), ErrorEventType.DESTINATION_CONNECTOR, getDestinationName(),
                connectorProperties.getName(), "Error creating web service dispatch.", e));
    } finally {
        eventController.dispatchEvent(new ConnectionStatusEvent(getChannelId(), getMetaDataId(),
                getDestinationName(), ConnectionStatusEventType.IDLE));
    }

    return new Response(responseStatus, responseData, responseStatusMessage, responseError, validateResponse);
}

From source file:org.apache.axis2.saaj.AttachmentTest.java

@Validated
@Test/*www. j  a  va  2s. com*/
public void testStringAttachment() throws Exception {

    MessageFactory factory = MessageFactory.newInstance();
    SOAPMessage message = factory.createMessage();
    AttachmentPart attachment = message.createAttachmentPart();
    String stringContent = "Update address for Sunny Skies "
            + "Inc., to 10 Upbeat Street, Pleasant Grove, CA 95439";

    attachment.setContent(stringContent, "text/plain");
    attachment.setContentId("update_address");
    message.addAttachmentPart(attachment);

    assertTrue(message.countAttachments() == 1);

    Iterator it = message.getAttachments();
    while (it.hasNext()) {
        attachment = (AttachmentPart) it.next();
        Object content = attachment.getContent();
        String id = attachment.getContentId();
        assertEquals(content, stringContent);
    }
    message.removeAllAttachments();
    assertTrue(message.countAttachments() == 0);
}

From source file:org.apache.axis2.saaj.AttachmentTest.java

@Validated
@Test//w ww.j  av  a2 s. c o m
public void testClearContent() throws Exception {
    try {
        InputStream in1 = TestUtils.getTestFile("attach.xml");

        MessageFactory factory = MessageFactory.newInstance();
        SOAPMessage message = factory.createMessage();
        AttachmentPart ap = message.createAttachmentPart();
        MimeHeader mh = null;

        //Setting Mime Header
        ap.setMimeHeader("Content-Description", "some text");

        //Setting Content Id Header
        ap.setContentId("id@abc.com");

        //Setting Content
        ap.setContent(new StreamSource(in1), "text/xml");

        //Clearing Content
        ap.clearContent();

        try {

            //Getting Content
            InputStream is = (InputStream) ap.getContent();
            fail("Error: SOAPException should have been thrown");
        } catch (SOAPException e) {
            //Error thrown.(expected)
        }

        Iterator iterator = ap.getAllMimeHeaders();
        int cnt = 0;
        boolean foundHeader1 = false;
        boolean foundHeader2 = false;
        boolean foundDefaultHeader = false;
        while (iterator.hasNext()) {
            cnt++;
            mh = (MimeHeader) iterator.next();
            String name = mh.getName();
            String value = mh.getValue();
            if (name.equals("Content-Description") && value.equals("some text")) {
                if (!foundHeader1) {
                    foundHeader1 = true;
                    //MimeHeaders do match for header1
                } else {
                    fail("Error: Received the same header1 header twice");
                }
            } else if (name.equalsIgnoreCase("Content-Id") && value.equals("id@abc.com")) {
                if (!foundHeader2) {
                    foundHeader2 = true;
                    //MimeHeaders do match for header2
                } else {
                    fail("Error: Received the same header2 header twice");
                }
            } else if (name.equals("Content-Type") && value.equals("text/xml")) {
                if (!foundDefaultHeader) {
                    foundDefaultHeader = true;
                    //MimeHeaders do match for default header
                } else {
                    fail("Error: Received the same default header header twice");
                }
            } else {
                fail("Error: Received an invalid header");
            }
        }

        if (!(foundHeader1 && foundHeader2)) {
            fail("Error: did not receive both headers");
        }

    } catch (Exception e) {
        fail("Exception: " + e);
    }

}

From source file:org.apache.axis2.saaj.AttachmentTest.java

@Validated
@Test//from   w  w w .  j a  va  2s . c  o m
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);
    }
}