javax.xml.soap.SOAPMessage Java Examples

The following examples show how to use javax.xml.soap.SOAPMessage. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: XmlTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
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;
}
 
Example #2
Source File: StreamHeader.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
public void writeTo(SOAPMessage saaj) throws SOAPException {
    try {
        // TODO what about in-scope namespaces
        // Not very efficient consider implementing a stream buffer
        // processor that produces a DOM node from the buffer.
        TransformerFactory tf = XmlUtil.newTransformerFactory();
        Transformer t = tf.newTransformer();
        XMLStreamBufferSource source = new XMLStreamBufferSource(_mark);
        DOMResult result = new DOMResult();
        t.transform(source, result);
        Node d = result.getNode();
        if(d.getNodeType() == Node.DOCUMENT_NODE)
            d = d.getFirstChild();
        SOAPHeader header = saaj.getSOAPHeader();
        if(header == null)
            header = saaj.getSOAPPart().getEnvelope().addHeader();
        Node node = header.getOwnerDocument().importNode(d, true);
        header.appendChild(node);
    } catch (Exception e) {
        throw new SOAPException(e);
    }
}
 
Example #3
Source File: HarFileHandler.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
public boolean handleOutbound(SOAPMessageContext context) {
   this.setHandler();
   SOAPMessage msg = context.getMessage();

   try {
      JsonObject request = new JsonObject();
      request.addProperty("method", "POST");
      request.addProperty("url", context.get("javax.xml.ws.service.endpoint.address").toString());
      request.addProperty("httpVersion", "HTTP/1.1");
      request.add("headers", this.handleHeaders(msg.getMimeHeaders()));
      request.add("queryString", new JsonArray());
      request.add("cookies", new JsonArray());
      request.addProperty("headersSize", Integer.valueOf(-1));
      request.add("postData", this.getPostData(msg));
      request.addProperty("time", "1");
      request.addProperty("bodySize", Integer.valueOf(-1));
      this.split = System.currentTimeMillis();
      this.getEntry().get("timings").getAsJsonObject().addProperty("send", this.split.longValue() - this.start.longValue());
      this.getEntry().add("request", request);
   } catch (Exception var4) {
      LOG.error(var4.getMessage(), var4);
   }

   return true;
}
 
Example #4
Source File: SOAPHandlerFaultInInterceptor.java    From cxf with Apache License 2.0 6 votes vote down vote up
public void handleMessage(SoapMessage message) {
    if (binding.getHandlerChain().isEmpty()) {
        return;
    }
    if (getInvoker(message).getProtocolHandlers().isEmpty()) {
        return;
    }

    checkUnderstoodHeaders(message);
    MessageContext context = createProtocolMessageContext(message);
    HandlerChainInvoker invoker = getInvoker(message);
    invoker.setProtocolMessageContext(context);

    if (!invoker.invokeProtocolHandlersHandleFault(isRequestor(message), context)) {
        handleAbort(message, context);
    }

    SOAPMessage msg = message.getContent(SOAPMessage.class);
    if (msg != null) {
        XMLStreamReader xmlReader = createXMLStreamReaderFromSOAPMessage(msg);
        message.setContent(XMLStreamReader.class, xmlReader);
    }

}
 
Example #5
Source File: StreamHeader.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
public void writeTo(SOAPMessage saaj) throws SOAPException {
    try {
        // TODO what about in-scope namespaces
        // Not very efficient consider implementing a stream buffer
        // processor that produces a DOM node from the buffer.
        TransformerFactory tf = XmlUtil.newTransformerFactory();
        Transformer t = tf.newTransformer();
        XMLStreamBufferSource source = new XMLStreamBufferSource(_mark);
        DOMResult result = new DOMResult();
        t.transform(source, result);
        Node d = result.getNode();
        if(d.getNodeType() == Node.DOCUMENT_NODE)
            d = d.getFirstChild();
        SOAPHeader header = saaj.getSOAPHeader();
        if(header == null)
            header = saaj.getSOAPPart().getEnvelope().addHeader();
        Node node = header.getOwnerDocument().importNode(d, true);
        header.appendChild(node);
    } catch (Exception e) {
        throw new SOAPException(e);
    }
}
 
Example #6
Source File: Soap.java    From keycloak with Apache License 2.0 6 votes vote down vote up
/**
 * <p>Returns a string encoded accordingly with the SAML HTTP POST Binding specification based on the
 * given <code>inputStream</code> which must contain a valid SOAP message.
 *
 * <p>The resulting string is based on the Body of the SOAP message, which should map to a valid SAML message.
 *
 * @param inputStream the input stream containing a valid SOAP message with a Body that contains a SAML message
 *
 * @return a string encoded accordingly with the SAML HTTP POST Binding specification
 */
public static String toSamlHttpPostMessage(InputStream inputStream) {
    try {
        MessageFactory messageFactory = MessageFactory.newInstance();
        SOAPMessage soapMessage = messageFactory.createMessage(null, inputStream);
        SOAPBody soapBody = soapMessage.getSOAPBody();
        Node authnRequestNode = soapBody.getFirstChild();
        Document document = DocumentUtil.createDocument();

        document.appendChild(document.importNode(authnRequestNode, true));

        return PostBindingUtil.base64Encode(DocumentUtil.asString(document));
    } catch (Exception e) {
        throw new RuntimeException("Error creating fault message.", e);
    }
}
 
Example #7
Source File: GreeterDOMSourcePayloadProvider.java    From cxf with Apache License 2.0 6 votes vote down vote up
public DOMSource invoke(DOMSource request) {
    DOMSource response = new DOMSource();
    try {
        System.out.println("Incoming Client Request as a DOMSource data in PAYLOAD Mode");
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        transformerFactory.setFeature(javax.xml.XMLConstants.FEATURE_SECURE_PROCESSING, true);
        Transformer transformer = transformerFactory.newTransformer();
        StreamResult result = new StreamResult(System.out);
        transformer.transform(request, result);
        System.out.println("\n");

        SOAPMessage greetMeResponse = null;
        try (InputStream is = getClass().getResourceAsStream("/GreetMeDocLiteralResp3.xml")) {
            greetMeResponse = MessageFactory.newInstance().createMessage(null, is);
        }
        response.setNode(greetMeResponse.getSOAPBody().extractContentAsDocument());
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return response;
}
 
Example #8
Source File: LoggingHandler.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
private void getMessageID(SOAPMessage msg) throws SOAPException {
   SOAPHeader header = msg.getSOAPHeader();
   if (header != null && header.getChildElements().hasNext()) {
      Node elementsResponseHeader = (Node)header.getChildElements().next();
      NodeList elementsheader = elementsResponseHeader.getChildNodes();

      for(int i = 0; i < elementsheader.getLength(); ++i) {
         org.w3c.dom.Node element = elementsheader.item(i);
         if (element.getLocalName() != null && element.getLocalName().equals("MessageID")) {
            LOG.info("The message id of the response: " + element.getNodeValue());
            break;
         }
      }
   }

}
 
Example #9
Source File: SaajEmptyNamespaceTest.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testAddElementToGlobalNsQName() throws Exception {
    // Create empty SOAP message
    SOAPMessage msg = createSoapMessage();
    SOAPBody body = msg.getSOAPPart().getEnvelope().getBody();

    // Add elements
    SOAPElement parentExplicitNS = body.addChildElement("content", "", TEST_NS);
    parentExplicitNS.addNamespaceDeclaration("", TEST_NS);
    SOAPElement childGlobalNS = parentExplicitNS.addChildElement(new QName("", "global-child"));
    childGlobalNS.addNamespaceDeclaration("", "");
    SOAPElement grandChildGlobalNS = childGlobalNS.addChildElement("global-grand-child");
    SOAPElement childDefaultNS = parentExplicitNS.addChildElement("default-child");

    // Check namespace URIs
    Assert.assertNull(childGlobalNS.getNamespaceURI());
    Assert.assertNull(grandChildGlobalNS.getNamespaceURI());
    Assert.assertEquals(childDefaultNS.getNamespaceURI(),TEST_NS);
}
 
Example #10
Source File: Stubs.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Creates a new {@link Dispatch} stub that connects to the given pipe.
 *
 * @param portInfo
 *      see <a href="#param">common parameters</a>
 * @param owner
 *      see <a href="#param">common parameters</a>
 * @param binding
 *      see <a href="#param">common parameters</a>
 * @param clazz
 *      Type of the {@link Dispatch} to be created.
 *      See {@link Service#createDispatch(QName, Class, Service.Mode)}.
 * @param mode
 *      The mode of the dispatch.
 *      See {@link Service#createDispatch(QName, Class, Service.Mode)}.
 * @param epr
 *      see <a href="#param">common parameters</a>
 * TODO: are these parameters making sense?
 */
public static <T> Dispatch<T> createDispatch(WSPortInfo portInfo,
                                             WSService owner,
                                             WSBinding binding,
                                             Class<T> clazz, Service.Mode mode,
                                             @Nullable WSEndpointReference epr) {
    if (clazz == SOAPMessage.class) {
        return (Dispatch<T>) createSAAJDispatch(portInfo, binding, mode, epr);
    } else if (clazz == Source.class) {
        return (Dispatch<T>) createSourceDispatch(portInfo, binding, mode, epr);
    } else if (clazz == DataSource.class) {
        return (Dispatch<T>) createDataSourceDispatch(portInfo, binding, mode, epr);
    } else if (clazz == Message.class) {
        if(mode==Mode.MESSAGE)
            return (Dispatch<T>) createMessageDispatch(portInfo, binding, epr);
        else
            throw new WebServiceException(mode+" not supported with Dispatch<Message>");
    } else if (clazz == Packet.class) {
        if(mode==Mode.MESSAGE)
            return (Dispatch<T>) createPacketDispatch(portInfo, binding, epr);
        else
            throw new WebServiceException(mode+" not supported with Dispatch<Packet>");
    } else
        throw new WebServiceException("Unknown class type " + clazz.getName());
}
 
Example #11
Source File: PolicyBasedWSS4JOutInterceptor.java    From cxf with Apache License 2.0 5 votes vote down vote up
public void handleMessage(SoapMessage mc) throws Fault {
    boolean enableStax =
        MessageUtils.getContextualBoolean(mc, SecurityConstants.ENABLE_STREAMING_SECURITY);
    if (!enableStax) {
        if (mc.getContent(SOAPMessage.class) == null) {
            saajOut.handleMessage(mc);
        }
        mc.put(SECURITY_PROCESSED, Boolean.TRUE);
        mc.getInterceptorChain().add(ending);
    }
}
 
Example #12
Source File: SaajEmptyNamespaceTest.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testAddElementToGlobalNsNoDeclarations() throws Exception {
    // Create empty SOAP message
    SOAPMessage msg = createSoapMessage();
    SOAPBody body = msg.getSOAPPart().getEnvelope().getBody();

    // Add elements
    SOAPElement parentExplicitNS = body.addChildElement("content", "", TEST_NS);
    SOAPElement childGlobalNS = parentExplicitNS.addChildElement("global-child", "", "");
    SOAPElement childDefaultNS = parentExplicitNS.addChildElement("default-child");

    // Check namespace URIs
    Assert.assertNull(childGlobalNS.getNamespaceURI());
    Assert.assertEquals(childDefaultNS.getNamespaceURI(), TEST_NS);
}
 
Example #13
Source File: ITEntityEndpointPasswordPlainWss4j.java    From spring-ws-security-soap-example with MIT License 5 votes vote down vote up
/**
 * Tests that a message with a wrong user returns a fault.
 *
 * @throws Exception
 *             never, this is a required declaration
 */
@Test
public final void testEndpoint_InvalidUser_ReturnsFault() throws Exception {
    final SOAPMessage message; // Response message

    message = callWebService(SecureSoapMessages.getPlainPasswordMessage(
            pathValid, username + "abc123", password));

    Assert.assertNotNull(
            message.getSOAPPart().getEnvelope().getBody().getFault());
}
 
Example #14
Source File: SaajStaxWriter.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void writeStartDocument(final String encoding, final String version) throws XMLStreamException {
    if (version != null) soap.getSOAPPart().setXmlVersion(version);
    if (encoding != null) {
        try {
            soap.setProperty(SOAPMessage.CHARACTER_SET_ENCODING, encoding);
        } catch (SOAPException e) {
            throw new XMLStreamException(e);
        }
    }
}
 
Example #15
Source File: AsymmetricBindingHandler.java    From steady with Apache License 2.0 5 votes vote down vote up
public AsymmetricBindingHandler(WSSConfig config,
                                AsymmetricBinding binding,
                                SOAPMessage saaj,
                                WSSecHeader secHeader,
                                AssertionInfoMap aim,
                                SoapMessage message) {
    super(config, binding, saaj, secHeader, aim, message);
    this.abinding = binding;
    protectionOrder = binding.getProtectionOrder();
}
 
Example #16
Source File: SaajEmptyNamespaceTest.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
private static SOAPMessage createSoapMessage() throws SOAPException, UnsupportedEncodingException {
    String xml = "<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\">"
                +"<SOAP-ENV:Body/></SOAP-ENV:Envelope>";
    MessageFactory mFactory = MessageFactory.newInstance();
    SOAPMessage msg = mFactory.createMessage();
    msg.getSOAPPart().setContent(new StreamSource(new ByteArrayInputStream(xml.getBytes("utf-8"))));
    return msg;
}
 
Example #17
Source File: AbstractBindingBuilder.java    From steady with Apache License 2.0 5 votes vote down vote up
public AbstractBindingBuilder(
                       WSSConfig config,
                       Binding binding,
                       SOAPMessage saaj,
                       WSSecHeader secHeader,
                       AssertionInfoMap aim,
                       SoapMessage message) {
    this.wssConfig = config;
    this.binding = binding;
    this.aim = aim;
    this.secHeader = secHeader;
    this.saaj = saaj;
    this.message = message;
    message.getExchange().put(WSHandlerConstants.SEND_SIGV, signatures);
}
 
Example #18
Source File: WSS4JOutInterceptorTest.java    From steady with Apache License 2.0 5 votes vote down vote up
@Test
public void testUsernameTokenText() throws Exception {
    SOAPMessage saaj = readSAAJDocument("wsse-request-clean.xml");

    WSS4JOutInterceptor ohandler = new WSS4JOutInterceptor();
    PhaseInterceptor<SoapMessage> handler = ohandler.createEndingInterceptor();

    SoapMessage msg = new SoapMessage(new MessageImpl());
    Exchange ex = new ExchangeImpl();
    ex.setInMessage(msg);

    msg.setContent(SOAPMessage.class, saaj);

    msg.put(WSHandlerConstants.ACTION, WSHandlerConstants.USERNAME_TOKEN);
    msg.put(WSHandlerConstants.SIG_PROP_FILE, "outsecurity.properties");
    msg.put(WSHandlerConstants.USER, "username");
    msg.put("password", "myAliasPassword");
    msg.put(WSHandlerConstants.PASSWORD_TYPE, WSConstants.PW_TEXT);
    handler.handleMessage(msg);

    SOAPPart doc = saaj.getSOAPPart();
    assertValid("//wsse:Security", doc);
    assertValid("//wsse:Security/wsse:UsernameToken", doc);
    assertValid("//wsse:Security/wsse:UsernameToken/wsse:Username[text()='username']", doc);
    // Test to see that the plaintext password is used in the header
    assertValid("//wsse:Security/wsse:UsernameToken/wsse:Password[text()='myAliasPassword']", doc);
}
 
Example #19
Source File: WSAClientServerTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testDuplicateHeaders() throws Exception {
    URL wsdl = getClass().getResource("/wsdl_systest_wsspec/add_numbers.wsdl");
    assertNotNull("WSDL is null", wsdl);

    AddNumbersService service = new AddNumbersService(wsdl, serviceName);
    QName portName = new QName("http://apache.org/cxf/systest/ws/addr_feature/", "AddNumbersPort");
    Dispatch<SOAPMessage> disp = service.createDispatch(portName, SOAPMessage.class,
                                                        Service.Mode.MESSAGE,
                                                        new AddressingFeature(false, false));
    disp.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY,
                             "http://localhost:" + PORT + "/jaxws/add");

    InputStream msgIns = getClass().getResourceAsStream("./duplicate-wsa-header-msg.xml");
    String msg = new String(IOUtils.readBytesFromStream(msgIns));
    msg = msg.replaceAll("$PORT", PORT);

    ByteArrayInputStream bout = new ByteArrayInputStream(msg.getBytes());

    SOAPMessage soapReqMsg = MessageFactory.newInstance().createMessage(null, bout);
    assertNotNull(soapReqMsg);

    try {
        disp.invoke(soapReqMsg);
        fail("SOAPFaultFxception is expected");
    } catch (SOAPFaultException ex) {
        assertTrue("WSA header exception is expected",
                   ex.getMessage().indexOf("A header representing a Message Addressing") > -1);
    }
}
 
Example #20
Source File: SAAJFactory.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Reads Message as SOAPMessage.  After this call message is consumed.
 * @param soapVersion SOAP version
 * @param message Message
 * @return Created SOAPMessage
 * @throws SOAPException if SAAJ processing fails
 */
public SOAPMessage readAsSOAPMessage(final SOAPVersion soapVersion, final Message message) throws SOAPException {
SOAPMessage msg = soapVersion.getMessageFactory().createMessage();
SaajStaxWriter writer = new SaajStaxWriter(msg);
try {
    message.writeTo(writer);
} catch (XMLStreamException e) {
    throw (e.getCause() instanceof SOAPException) ? (SOAPException) e.getCause() : new SOAPException(e);
}
msg = writer.getSOAPMessage();
addAttachmentsToSOAPMessage(msg, message);
if (msg.saveRequired())
        msg.saveChanges();
return msg;
}
 
Example #21
Source File: SOAPMessageContextImpl.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
public void setMessage(SOAPMessage soapMsg) {
    try {
        this.soapMsg = soapMsg;
    } catch(Exception e) {
        throw new WebServiceException(e);
    }
}
 
Example #22
Source File: ProblemActionHeader.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
public void writeTo(SOAPMessage saaj) throws SOAPException {
    SOAPHeader header = saaj.getSOAPHeader();
    if(header == null)
        header = saaj.getSOAPPart().getEnvelope().addHeader();
    SOAPHeaderElement she = header.addHeaderElement(new QName(getNamespaceURI(), getLocalPart()));
    she.addChildElement(actionLocalName);
    she.addTextNode(action);
    if (soapAction != null) {
        she.addChildElement(soapActionLocalName);
        she.addTextNode(soapAction);
    }
}
 
Example #23
Source File: SecureSoapMessages.java    From spring-ws-security-soap-example with MIT License 5 votes vote down vote up
private static final SOAPMessage toMessage(final Document jdomDocument)
        throws IOException, SOAPException {
    final SOAPMessage message = MessageFactory.newInstance()
            .createMessage();
    final SOAPPart sp = message.getSOAPPart();
    sp.setContent(new DOMSource(jdomDocument.getFirstChild()));

    return message;
}
 
Example #24
Source File: SAAJFactory.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
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);
    }
}
 
Example #25
Source File: MessageWrapper.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public SOAPMessage readAsSOAPMessage(Packet p, boolean inbound) throws SOAPException {
    if (!(delegate instanceof SAAJMessage)) {
        delegate = toSAAJ(p, inbound);
    }
    return delegate.readAsSOAPMessage();
}
 
Example #26
Source File: SOAPConnectionImpl.java    From JVoiceXML with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Checks whether the request has an associated SOAPAction MIME header
 * and returns its value.
 * @param request the message to check
 * @return the value of any associated SOAPAction MIME header or null
 * if there is no such header.
 */
private String checkForSOAPActionHeader(SOAPMessage request) {
    MimeHeaders hdrs = request.getMimeHeaders();
    if (hdrs != null) {
        String[] saHdrs = hdrs.getHeader("SOAPAction");
        if (saHdrs != null && saHdrs.length > 0)
            return saHdrs[0];
    }
    return null;
}
 
Example #27
Source File: SOAPMessageContextImpl.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public SOAPMessage getMessage() {
    if(soapMsg == null) {
        try {
            Message m = packet.getMessage();
            soapMsg = m != null ? m.readAsSOAPMessage() : null;
        } catch (SOAPException e) {
            throw new WebServiceException(e);
        }
    }
    return soapMsg;
}
 
Example #28
Source File: FaultDetailHeader.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
public void writeTo(SOAPMessage saaj) throws SOAPException {
    SOAPHeader header = saaj.getSOAPHeader();
    if (header == null)
            header = saaj.getSOAPPart().getEnvelope().addHeader();
    SOAPHeaderElement she = header.addHeaderElement(av.faultDetailTag);
    she = header.addHeaderElement(new QName(av.nsUri, wrapper));
    she.addTextNode(problemValue);
}
 
Example #29
Source File: SAAJFactory.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
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);
    }
}
 
Example #30
Source File: IncomingSecurityHandler.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
public boolean handleInbound(SOAPMessageContext context) {
   SOAPMessage message = context.getMessage();
   WSSecurityEngine secEngine = new WSSecurityEngine();
   RequestData requestData = new RequestData();
   requestData.setWssConfig(this.config);

   try {
      SOAPHeader header = message.getSOAPHeader();
      if (header != null) {
         NodeList list = header.getElementsByTagNameNS(WSSE.getNamespaceURI(), WSSE.getLocalPart());
         if (list != null) {
            LOG.debug("Verify WS Security Header");

            for(int j = 0; j < list.getLength(); ++j) {
               List<WSSecurityEngineResult> results = secEngine.processSecurityHeader((Element)list.item(j), requestData);
               Iterator i$ = results.iterator();

               while(i$.hasNext()) {
                  WSSecurityEngineResult result = (WSSecurityEngineResult)i$.next();
                  if (!(Boolean) result.get("validated-token")) {
                     StringBuffer sb = new StringBuffer();
                     sb.append("Unable to validate incoming soap message. Action [");
                     sb.append(result.get("action"));
                     sb.append("].");
                     throw new ProtocolException(sb.toString());
                  }
               }
            }
         }
      }

      return true;
   } catch (WSSecurityException var12) {
      throw new ProtocolException(var12);
   } catch (SOAPException var13) {
      throw new ProtocolException(var13);
   }
}