Example usage for javax.xml.soap SOAPPart setContent

List of usage examples for javax.xml.soap SOAPPart setContent

Introduction

In this page you can find the example usage for javax.xml.soap SOAPPart setContent.

Prototype

public abstract void setContent(Source source) throws SOAPException;

Source Link

Document

Sets the content of the SOAPEnvelope object with the data from the given Source object.

Usage

From source file:com.wandrell.example.swss.test.util.factory.SecureSoapMessages.java

private static final SOAPMessage toMessage(Document jdomDocument) throws IOException, SOAPException {
    SOAPMessage message = MessageFactory.newInstance().createMessage();
    SOAPPart sp = message.getSOAPPart();
    sp.setContent(new DOMSource(jdomDocument.getFirstChild()));

    return message;
}

From source file:com.bernardomg.example.swss.test.util.factory.SecureSoapMessages.java

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;
}

From source file:com.nortal.jroad.util.SOAPUtil.java

/**
 * Substitutes all occurences of some given string inside the given {@link WebServiceMessage} with another value.
 *
 * @param message message to substitute in
 * @param from the value to substitute//  ww  w  .  jav  a2 s . co m
 * @param to the value to substitute with
 * @throws TransformerException
 */
public static void substitute(WebServiceMessage message, String from, String to) throws TransformerException {
    SaajSoapMessage saajSoapMessage = (SaajSoapMessage) message;
    SOAPPart soapPart = saajSoapMessage.getSaajMessage().getSOAPPart();

    Source source = new DOMSource(soapPart);
    StringResult stringResult = new StringResult();

    TransformerFactory.newInstance().newTransformer().transform(source, stringResult);

    String content = stringResult.toString().replaceAll(from, to);

    try {
        soapPart.setContent(new StringSource(content));
    } catch (SOAPException e) {
        throw new TransformerException(e);
    }
}

From source file:com.streamreduce.util.JiraClient.java

public SOAPMessage invokeSoap(JiraStudioApp app, String soapBody) throws SOAPException {
    String cacheKey = (app + "-SOAP-" + soapBody.hashCode());
    Object objectFromCache = requestCache.getIfPresent(cacheKey);

    if (objectFromCache != null) {
        debugLog(LOGGER, "  (From cache)");
        return (SOAPMessage) objectFromCache;
    }/*  ww  w .  j a  v  a 2s . com*/

    // Wrap the SOAP body content in an envelope/body container
    StringBuilder sb = new StringBuilder();
    String soapBaseURL = getBaseUrl();
    String soapNamespaceURL;

    sb.append("<soapenv:Envelope ").append("xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" ")
            .append("xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" ")
            .append("xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" ");

    switch (app) {
    case CONFLUENCE:
        soapNamespaceURL = "http://soap.rpc.confluence.atlassian.com";
        soapBaseURL += "/wiki/rpc/soap-axis/confluenceservice-v1";
        break;
    case JIRA:
        soapNamespaceURL = "http://soap.rpc.jira.atlassian.com";
        soapBaseURL += "/rpc/soap/jirasoapservice-v2";
        break;
    default:
        throw new SOAPException("Unknown Jira Studio application: " + app);
    }

    sb.append("xmlns:soap=\"" + soapNamespaceURL + "\">\n");
    sb.append("<soapenv:Body>\n");
    sb.append(soapBody);
    sb.append("</soapenv:Body></soapenv:Envelope>");

    String rawResponse;
    List<Header> requestHeaders = new ArrayList<>();

    requestHeaders.add(new BasicHeader("SOAPAction", ""));

    try {
        rawResponse = HTTPUtils.openUrl(soapBaseURL, "POST", sb.toString(), MediaType.TEXT_XML, null, null,
                requestHeaders, null);
    } catch (Exception e) {
        LOGGER.error(String.format("Unable to make SOAP call to %s: %s", soapBaseURL, e.getMessage()), e);
        throw new SOAPException(e);
    }

    Source response = new StreamSource(new StringReader(rawResponse));
    MessageFactory msgFactory = MessageFactory.newInstance();
    SOAPMessage message = msgFactory.createMessage();
    SOAPPart env = message.getSOAPPart();
    env.setContent(response);

    if (message.getSOAPBody().hasFault()) {
        SOAPFault fault = message.getSOAPBody().getFault();
        LOGGER.error("soap fault in jira soap response: " + fault.getFaultString());
    }

    requestCache.put(cacheKey, message);

    return message;
}

From source file:org.apache.ws.security.handler.WSS4JHandler.java

/**
 * Handles incoming web service requests and outgoing responses
 *///  w ww . ja  va  2 s. c o m
public boolean doSender(MessageContext mc, RequestData reqData, boolean isRequest) throws WSSecurityException {

    reqData.getSignatureParts().removeAllElements();
    reqData.getEncryptParts().removeAllElements();
    reqData.setNoSerialization(false);
    /*
    * Get the action first.
    */
    Vector actions = new Vector();
    String action = (String) getOption(WSHandlerConstants.SEND + '.' + WSHandlerConstants.ACTION);
    if (action == null) {
        action = (String) getOption(WSHandlerConstants.ACTION);
        if (action == null) {
            action = (String) mc.getProperty(WSHandlerConstants.ACTION);
        }
    }
    if (action == null) {
        throw new JAXRPCException("WSS4JHandler: No action defined");
    }
    int doAction = WSSecurityUtil.decodeAction(action, actions);
    if (doAction == WSConstants.NO_SECURITY) {
        return true;
    }

    /*
    * For every action we need a username, so get this now. The username
    * defined in the deployment descriptor takes precedence.
    */
    reqData.setUsername((String) getOption(WSHandlerConstants.USER));
    if (reqData.getUsername() == null || reqData.getUsername().equals("")) {
        reqData.setUsername((String) mc.getProperty(WSHandlerConstants.USER));
        mc.removeProperty(WSHandlerConstants.USER);
    }

    /*
    * Now we perform some set-up for UsernameToken and Signature
    * functions. No need to do it for encryption only. Check if username
    * is available and then get a password.
    */
    if (((doAction & (WSConstants.SIGN | WSConstants.UT | WSConstants.UT_SIGN)) != 0)
            && (reqData.getUsername() == null || reqData.getUsername().equals(""))) {
        /*
        * We need a username - if none throw an JAXRPCException. For encryption
        * there is a specific parameter to get a username.
        */
        throw new JAXRPCException("WSS4JHandler: Empty username for specified action");
    }
    if (doDebug) {
        log.debug("Action: " + doAction);
        log.debug("Actor: " + reqData.getActor());
    }
    /*
    * Now get the SOAP part from the request message and convert it into a
    * Document.
    *
    * This forces Axis to serialize the SOAP request into FORM_STRING.
    * This string is converted into a document.
    *
    * During the FORM_STRING serialization Axis performs multi-ref of
    * complex data types (if requested), generates and inserts references
    * for attachments and so on. The resulting Document MUST be the
    * complete and final SOAP request as Axis would send it over the wire.
    * Therefore this must shall be the last (or only) handler in a chain.
    *
    * Now we can perform our security operations on this request.
    */
    Document doc = null;
    SOAPMessage message = ((SOAPMessageContext) mc).getMessage();
    Boolean propFormOptimization = (Boolean) mc.getProperty("axis.form.optimization");
    log.debug("Form optimization: " + propFormOptimization);
    /*
    * If the message context property contains a document then this is a
    * chained handler.
    */
    SOAPPart sPart = message.getSOAPPart();
    if ((doc = (Document) mc.getProperty(WSHandlerConstants.SND_SECURITY)) == null) {
        try {
            doc = messageToDocument(message);
        } catch (Exception e) {
            if (doDebug) {
                log.debug(e.getMessage(), e);
            }
            throw new JAXRPCException("WSS4JHandler: cannot get SOAP envlope from message", e);
        }
    }
    if (doDebug) {
        log.debug("WSS4JHandler: orginal SOAP request: ");
        log.debug(org.apache.ws.security.util.XMLUtils.PrettyDocumentToString(doc));
    }
    doSenderAction(doAction, doc, reqData, actions, isRequest);

    /*
    * If required convert the resulting document into a message first. The
    * outputDOM() method performs the necessary c14n call. After that we
    * extract it as a string for further processing.
    *
    * Set the resulting byte array as the new SOAP message.
    *
    * If noSerialization is false, this handler shall be the last (or only)
    * one in a handler chain. If noSerialization is true, just set the
    * processed Document in the transfer property. The next Axis WSS4J
    * handler takes it and performs additional security processing steps.
    *
    */
    if (reqData.isNoSerialization()) {
        mc.setProperty(WSHandlerConstants.SND_SECURITY, doc);
    } else {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        XMLUtils.outputDOM(doc, os, true);
        if (doDebug) {
            String osStr = null;
            try {
                osStr = os.toString("UTF-8");
            } catch (UnsupportedEncodingException e) {
                if (doDebug) {
                    log.debug(e.getMessage(), e);
                }
                osStr = os.toString();
            }
            log.debug("Send request:");
            log.debug(osStr);
        }

        try {
            sPart.setContent(new StreamSource(new ByteArrayInputStream(os.toByteArray())));
        } catch (SOAPException se) {
            if (doDebug) {
                log.debug(se.getMessage(), se);
            }
            throw new JAXRPCException("Couldn't set content on SOAPPart" + se.getMessage(), se);
        }
        mc.removeProperty(WSHandlerConstants.SND_SECURITY);
    }
    if (doDebug) {
        log.debug("WSS4JHandler: exit invoke()");
    }
    return true;
}

From source file:org.apache.ws.security.handler.WSS4JHandler.java

/**
 * handle responses//from w  ww  .j a v a2  s.  com
 *
 * @param mc
 * @param reqData
 * @return true on successful processing
 * @throws WSSecurityException
 */
public boolean doReceiver(MessageContext mc, RequestData reqData, boolean isRequest)
        throws WSSecurityException {

    Vector actions = new Vector();
    String action = (String) getOption(WSHandlerConstants.RECEIVE + '.' + WSHandlerConstants.ACTION);
    if (action == null) {
        action = (String) getOption(WSHandlerConstants.ACTION);
        if (action == null) {
            action = (String) mc.getProperty(WSHandlerConstants.ACTION);
        }
    }
    if (action == null) {
        throw new JAXRPCException("WSS4JHandler: No action defined");
    }
    int doAction = WSSecurityUtil.decodeAction(action, actions);

    String actor = (String) getOption(WSHandlerConstants.ACTOR);

    SOAPMessage message = ((SOAPMessageContext) mc).getMessage();
    SOAPPart sPart = message.getSOAPPart();
    Document doc = null;
    try {
        doc = messageToDocument(message);
    } catch (Exception ex) {
        if (doDebug) {
            log.debug(ex.getMessage(), ex);
        }
        throw new JAXRPCException("WSS4JHandler: cannot convert into document", ex);
    }
    /*
    * Check if it's a fault. Don't process faults.
    *
    */
    SOAPConstants soapConstants = WSSecurityUtil.getSOAPConstants(doc.getDocumentElement());
    if (WSSecurityUtil.findElement(doc.getDocumentElement(), "Fault", soapConstants.getEnvelopeURI()) != null) {
        return false;
    }

    /*
    * To check a UsernameToken or to decrypt an encrypted message we need
    * a password.
    */
    CallbackHandler cbHandler = null;
    if ((doAction & (WSConstants.ENCR | WSConstants.UT)) != 0) {
        cbHandler = getPasswordCB(reqData);
    }

    /*
    * Get and check the Signature specific parameters first because they
    * may be used for encryption too.
    */
    doReceiverAction(doAction, reqData);

    Vector wsResult = null;
    try {
        wsResult = secEngine.processSecurityHeader(doc, actor, cbHandler, reqData.getSigCrypto(),
                reqData.getDecCrypto());
    } catch (WSSecurityException ex) {
        if (doDebug) {
            log.debug(ex.getMessage(), ex);
        }
        throw new JAXRPCException("WSS4JHandler: security processing failed", ex);
    }
    if (wsResult == null) { // no security header found
        if (doAction == WSConstants.NO_SECURITY) {
            return true;
        } else {
            throw new JAXRPCException("WSS4JHandler: Request does not contain required Security header");
        }
    }
    if (reqData.getWssConfig().isEnableSignatureConfirmation() && !isRequest) {
        checkSignatureConfirmation(reqData, wsResult);
    }

    /*
    * If we had some security processing, get the original
    * SOAP part of Axis' message and replace it with new SOAP
    * part. This new part may contain decrypted elements.
    */

    ByteArrayOutputStream os = new ByteArrayOutputStream();
    XMLUtils.outputDOM(doc, os, true);
    try {
        sPart.setContent(new StreamSource(new ByteArrayInputStream(os.toByteArray())));
    } catch (SOAPException se) {
        if (doDebug) {
            log.debug(se.getMessage(), se);
        }
        throw new JAXRPCException("Couldn't set content on SOAPPart" + se.getMessage(), se);
    }

    if (doDebug) {
        log.debug("Processed received SOAP request");
    }

    /*
    * After setting the new current message, probably modified because
    * of decryption, we need to locate the security header. That is,
    * we force Axis (with getSOAPEnvelope()) to parse the string, build
    * the new header. Then we examine, look up the security header
    * and set the header as processed.
    *
    * Please note: find all header elements that contain the same
    * actor that was given to processSecurityHeader(). Then
    * check if there is a security header with this actor.
    */

    SOAPHeader sHeader = null;
    try {
        sHeader = message.getSOAPPart().getEnvelope().getHeader();
    } catch (Exception ex) {
        if (doDebug) {
            log.debug(ex.getMessage(), ex);
        }
        throw new JAXRPCException("WSS4JHandler: cannot get SOAP header after security processing", ex);
    }

    Iterator headers = sHeader.examineHeaderElements(actor);

    SOAPHeaderElement headerElement = null;
    while (headers.hasNext()) {
        SOAPHeaderElement hE = (SOAPHeaderElement) headers.next();
        if (hE.getElementName().getLocalName().equals(WSConstants.WSSE_LN)
                && ((Node) hE).getNamespaceURI().equals(WSConstants.WSSE_NS)) {
            headerElement = hE;
            break;
        }
    }

    /* JAXRPC conversion changes */
    headerElement.setMustUnderstand(false); // is this sufficient?

    /*
    * Now we can check the certificate used to sign the message.
    * In the following implementation the certificate is only trusted
    * if either it itself or the certificate of the issuer is installed
    * in the keystore.
    *
    * Note: the method verifyTrust(X509Certificate) allows custom
    * implementations with other validation algorithms for subclasses.
    */

    // Extract the signature action result from the action vector

    WSSecurityEngineResult actionResult = WSSecurityUtil.fetchActionResult(wsResult, WSConstants.SIGN);

    if (actionResult != null) {
        X509Certificate returnCert = (X509Certificate) actionResult
                .get(WSSecurityEngineResult.TAG_X509_CERTIFICATE);

        if (returnCert != null && !verifyTrust(returnCert, reqData)) {
            throw new JAXRPCException("WSS4JHandler: The certificate used for the signature is not trusted");
        }
    }

    /*
    * Perform further checks on the timestamp that was transmitted in the header.
    * In the following implementation the timestamp is valid if it was
    * created after (now-ttl), where ttl is set on server side, not by the client.
    *
    * Note: the method verifyTimestamp(Timestamp) allows custom
    * implementations with other validation algorithms for subclasses.
    */

    // Extract the timestamp action result from the action vector
    actionResult = WSSecurityUtil.fetchActionResult(wsResult, WSConstants.TS);

    if (actionResult != null) {
        Timestamp timestamp = (Timestamp) actionResult.get(WSSecurityEngineResult.TAG_TIMESTAMP);

        if (timestamp != null && reqData.getWssConfig().isTimeStampStrict()
                && !verifyTimestamp(timestamp, decodeTimeToLive(reqData))) {
            throw new JAXRPCException("WSS4JHandler: The timestamp could not be validated");
        }
    }

    /*
    * now check the security actions: do they match, in right order?
    */
    if (!checkReceiverResults(wsResult, actions)) {
        throw new JAXRPCException("WSS4JHandler: security processing failed (actions mismatch)");
    }

    /*
    * All ok up to this point. Now construct and setup the
    * security result structure. The service may fetch this
    * and check it.
    */
    Vector results = null;
    if ((results = (Vector) mc.getProperty(WSHandlerConstants.RECV_RESULTS)) == null) {
        results = new Vector();
        mc.setProperty(WSHandlerConstants.RECV_RESULTS, results);
    }
    WSHandlerResult rResult = new WSHandlerResult(actor, wsResult);
    results.add(0, rResult);
    if (doDebug) {
        log.debug("WSS4JHandler: exit invoke()");
    }

    return true;
}

From source file:org.openhie.test.xds.util.SoapMessageSender.java

private SOAPMessage getSoapMessageFromString() throws SOAPException, IOException {
    MessageFactory factory = MessageFactory.newInstance();

    //MimeHeaders header=new MimeHeaders();
    //header.addHeader("Content-Type","application/xop+xml; application/soap+xml" + "action=urn:ihe:iti:2007:ProvideAndRegisterDocumentSet-b" + "boundary=MIMEBoundaryurn_uuid_E3F7CE4554928DA89B1231365678616;"+ "Content-Transfer-Encoding=binary" + "Content-ID=\"<0.urn:uuid:E3F7CE4554928DA89B1231365678617@apache.org>\"");
    //header.addHeader("action", "urn:ihe:iti:2007:ProvideAndRegisterDocumentSet-b");

    SOAPMessage message = MessageFactory.newInstance().createMessage();
    SOAPPart soapPart = message.getSOAPPart();

    MimeHeaders header = message.getMimeHeaders();
    //header.addHeader("Content-Type","application/xop+xml; application/soap+xml" + "action=urn:ihe:iti:2007:ProvideAndRegisterDocumentSet-b" + "boundary=MIMEBoundaryurn_uuid_E3F7CE4554928DA89B1231365678616;"+ "Content-Transfer-Encoding=binary" + "Content-ID=\"<0.urn:uuid:E3F7CE4554928DA89B1231365678617@apache.org>\"");
    //header.addHeader("Content-Type", "multipart/related;start=<rootpart*17f1ec84-85ec-4f1f-9b29-423a6a2e354f@example.jaxws.sun.com>;type=application/xop+xml;boundary=uuid:17f1ec84-85ec-4f1f-9b29-423a6a2e354f\";start-info=\"application/soap+xml\";action=\"urn:ihe:iti:2007:ProvideAndRegisterDocumentSet-b");
    header.setHeader("Content-Type", "application/soap+xml;charset=UTF-8");

    SOAPHeader soap = message.getSOAPHeader();
    soapPart.setContent(new StreamSource(new FileInputStream(
            "/Users/snkasthu/SourceCode/cds/openhie-integration-tests/src/test/resources/xds/OHIE-XDS-01-10.xml")));

    System.out.print("Request SOAP Message :");
    message.writeTo(System.out);//  w w  w. j a v a 2 s. c o  m
    System.out.println();

    return message;
}