Example usage for javax.xml.soap SOAPMessage getSOAPPart

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

Introduction

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

Prototype

public abstract SOAPPart getSOAPPart();

Source Link

Document

Gets the SOAP part of this SOAPMessage object.

Usage

From source file:it.cnr.icar.eric.server.interfaces.soap.RegistrySAMLServlet.java

@SuppressWarnings("unchecked")
public SOAPMessage onMessage(SOAPMessage msg, HttpServletRequest req, HttpServletResponse resp) {

    SOAPMessage soapResponse = null;
    SOAPHeader soapHeader = null;

    try {/*from   w  w  w.  j  a v  a  2 s. c o  m*/

        // extract SOAP related parts from incoming SOAP message

        // set 'soapHeader' variable ASAP (before "firstly")
        SOAPPart soapPart = msg.getSOAPPart();
        SOAPEnvelope soapEnvelope = soapPart.getEnvelope();
        SOAPBody soapBody = soapEnvelope.getBody();
        soapHeader = soapEnvelope.getHeader();

        /****************************************************************
         * 
         * REPOSITORY ITEM HANDLING (IN) REPOSITORY ITEM HANDLING (IN)
         * 
         ***************************************************************/

        // Firstly we put save the attached repository items in a map

        HashMap<String, Object> idToRepositoryItemMap = new HashMap<String, Object>();
        Iterator<AttachmentPart> apIter = msg.getAttachments();

        while (apIter.hasNext()) {
            AttachmentPart ap = apIter.next();

            // Get the content for the attachment
            RepositoryItem ri = processIncomingAttachment(ap);
            idToRepositoryItemMap.put(ri.getId(), ri);
        }

        /****************************************************************
         * 
         * LOGGING (IN) LOGGING (IN) LOGGING (IN) LOGGING (IN)
         * 
         ***************************************************************/

        // Log received message

        if (log.isTraceEnabled()) {
            // Warning! BAOS.toString() uses platform's default encoding
            ByteArrayOutputStream msgOs = new ByteArrayOutputStream();
            msg.writeTo(msgOs);
            msgOs.close();
            log.trace("incoming message:\n" + msgOs.toString());
        }

        /****************************************************************
         * 
         * MESSAGE VERIFICATION (IN) MESSAGE VERIFICATION (IN)
         * 
         ***************************************************************/
        CredentialInfo credentialInfo = new CredentialInfo();

        WSS4JSecurityUtilSAML.verifySOAPEnvelopeOnServerSAML(soapEnvelope, credentialInfo);

        /****************************************************************
         * 
         * RS:REQUEST HANDLING RS:REQUEST HANDLING RS:REQUEST
         * 
         ***************************************************************/

        // The ebXML registry request is the only element in the SOAPBody

        StringWriter requestXML = new StringWriter(); // The request as an
        // XML String
        String requestRootElement = null;

        Iterator<?> iter = soapBody.getChildElements();
        int i = 0;

        while (iter.hasNext()) {
            Object obj = iter.next();

            if (!(obj instanceof SOAPElement)) {
                continue;
            }

            if (i++ == 0) {
                SOAPElement elem = (SOAPElement) obj;
                Name name = elem.getElementName();
                requestRootElement = name.getLocalName();

                StreamResult result = new StreamResult(requestXML);
                TransformerFactory tf = TransformerFactory.newInstance();
                Transformer trans = tf.newTransformer();
                trans.transform(new DOMSource(elem), result);
            } else {
                throw new RegistryException(
                        ServerResourceBundle.getInstance().getString("message.invalidRequest"));
            }
        }

        if (requestRootElement == null) {
            throw new RegistryException(
                    ServerResourceBundle.getInstance().getString("message.noebXMLRegistryRequest"));
        }

        // unmarshalling request to message
        Object message = bu.getRequestObject(requestRootElement, requestXML.toString());

        if (message instanceof JAXBElement<?>) {
            // If Element; take ComplexType from Element
            message = ((JAXBElement<?>) message).getValue();
        }

        SAMLRequest request = new SAMLRequest(req, credentialInfo.assertion, message, idToRepositoryItemMap);

        Response response = request.process();

        /****************************************************************
         * 
         * RESPONSE HANDLING RESPONSE HANDLING RESPONSE HANDLING
         * 
         ***************************************************************/

        soapResponse = createResponseSOAPMessage(response);

        if (response.getIdToRepositoryItemMap().size() > 0 && (response.getMessage().getStatus()
                .equals(BindingUtility.CANONICAL_RESPONSE_STATUS_TYPE_ID_Success))) {

            idToRepositoryItemMap = response.getIdToRepositoryItemMap();
            Iterator<String> mapKeysIter = idToRepositoryItemMap.keySet().iterator();

            while (mapKeysIter.hasNext()) {
                String id = mapKeysIter.next();
                RepositoryItem repositoryItem = (RepositoryItem) idToRepositoryItemMap.get(id);

                String cid = WSS4JSecurityUtilSAML.convertUUIDToContentId(id);
                DataHandler dh = repositoryItem.getDataHandler();
                AttachmentPart ap = soapResponse.createAttachmentPart(dh);
                ap.setContentId(cid);
                soapResponse.addAttachmentPart(ap);

                if (log.isTraceEnabled()) {
                    log.trace("adding attachment: contentId=" + id);
                }
            }
        }

    } catch (Throwable t) {
        // Do not log ObjectNotFoundException as it clutters the log
        if (!(t instanceof ObjectNotFoundException)) {
            log.error(ServerResourceBundle.getInstance().getString("message.CaughtException",
                    new Object[] { t.getMessage() }), t);
            Throwable cause = t.getCause();
            while (cause != null) {
                log.error(ServerResourceBundle.getInstance().getString("message.CausedBy",
                        new Object[] { cause.getMessage() }), cause);
                cause = cause.getCause();
            }
        }

        soapResponse = createFaultSOAPMessage(t, soapHeader);
    }

    if (log.isTraceEnabled()) {
        try {
            ByteArrayOutputStream rspOs = new ByteArrayOutputStream();
            soapResponse.writeTo(rspOs);
            rspOs.close();
            // Warning! BAOS.toString() uses platform's default encoding
            log.trace("response message:\n" + rspOs.toString());
        } catch (Exception e) {
            log.error(ServerResourceBundle.getInstance().getString("message.FailedToLogResponseMessage",
                    new Object[] { e.getMessage() }), e);
        }
    }
    return soapResponse;
}

From source file:it.cnr.icar.eric.server.common.Utility.java

public org.w3c.dom.Element getSignatureElement(SOAPMessage msg)
        throws javax.xml.soap.SOAPException, javax.xml.transform.TransformerException {
    org.w3c.dom.Element sigElement = null;

    javax.xml.transform.Transformer xFormer = javax.xml.transform.TransformerFactory.newInstance()
            .newTransformer();/*ww w  . j ava2  s. c o m*/

    // grab info out of msg
    javax.xml.soap.SOAPPart msgPart = msg.getSOAPPart();
    javax.xml.transform.Source msgSource = msgPart.getContent();

    // transform
    javax.xml.transform.dom.DOMResult domResult = new javax.xml.transform.dom.DOMResult();
    xFormer.transform(msgSource, domResult);

    //root node is the soap:Envelope
    Node envelopeNode = domResult.getNode();

    //now you have the node. the following code strips off the envelope of
    //the soap message to get to the actual content
    // Advance to envelope node in case of text nodes preceding it
    while ((envelopeNode.getLocalName() == null)
            || (!envelopeNode.getLocalName().equalsIgnoreCase("envelope"))) {
        envelopeNode = envelopeNode.getFirstChild();
    }

    // Advance to header within envelope node
    Node headerNode = envelopeNode.getFirstChild();

    while ((headerNode.getLocalName() == null) || (!headerNode.getLocalName().equalsIgnoreCase("header"))) {
        headerNode = headerNode.getNextSibling();
    }

    //System.err.println("headerNode name is: " + headerNode.getLocalName());
    // Advance to signature node within header
    Node sigNode = headerNode.getFirstChild();

    if (sigNode == null) {
        return null;
    }

    //System.err.println("sigNode: " + sigNode);
    while ((sigNode.getLocalName() == null) || (!sigNode.getLocalName().equalsIgnoreCase("signature"))) {
        sigNode = sigNode.getNextSibling();

        if (sigNode == null) {
            return null;
        }
    }

    //Desired Signature element may be inside a SOAP-SEC signature element
    if (!sigNode.getNamespaceURI().equals("http://www.w3.org/2000/09/xmldsig#")) {
        sigNode = sigNode.getFirstChild();

        while ((sigNode.getLocalName() == null) || (!sigNode.getLocalName().equalsIgnoreCase("signature"))) {
            sigNode = sigNode.getNextSibling();
        }
    }

    if (sigNode.getNamespaceURI().equals("http://www.w3.org/2000/09/xmldsig#")) {
        if (sigNode instanceof org.w3c.dom.Element) {
            sigElement = (org.w3c.dom.Element) sigNode;
        }
    }

    return sigElement;
}

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;//  w w w.j  a  v a 2s.  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:com.cisco.dvbu.ps.common.adapters.connect.SoapHttpConnector.java

private Document send(SoapHttpConnectorCallback cb, String requestXml) throws AdapterException {
    log.debug("Entered send: " + cb.getName());

    // set up the factories and create a SOAP factory
    SOAPConnection soapConnection;
    Document doc = null;// w  w w  .  j a  v  a 2 s.c o  m
    URL endpoint = null;
    try {
        soapConnection = SOAPConnectionFactory.newInstance().createConnection();
        MessageFactory messageFactory = MessageFactory.newInstance();

        // Create a message from the message factory.
        SOAPMessage soapMessage = messageFactory.createMessage();

        // Set the SOAP Action here
        MimeHeaders headers = soapMessage.getMimeHeaders();
        headers.addHeader("SOAPAction", cb.getAction());

        // set credentials
        //         String authorization = new sun.misc.BASE64Encoder().encode((shConfig.getUser() + "@" + shConfig.getDomain() + ":" + shConfig.getPassword()).getBytes());
        String authorization = new String(org.apache.commons.codec.binary.Base64.encodeBase64(
                (shConfig.getUser() + "@" + shConfig.getDomain() + ":" + shConfig.getPassword()).getBytes()));
        headers.addHeader("Authorization", "Basic " + authorization);
        log.debug("Authentication: " + authorization);

        // create a SOAP part have populate the envelope
        SOAPPart soapPart = soapMessage.getSOAPPart();
        SOAPEnvelope envelope = soapPart.getEnvelope();
        envelope.setEncodingStyle(SOAPConstants.URI_NS_SOAP_ENCODING);

        SOAPHeader head = envelope.getHeader();
        if (head == null)
            head = envelope.addHeader();

        // create a SOAP body
        SOAPBody body = envelope.getBody();

        log.debug("Request XSL Style Sheet:\n"
                + XMLUtils.getPrettyXml(XMLUtils.getDocumentFromString(cb.getRequestBodyXsl())));

        // convert request string to document and then transform
        body.addDocument(XmlUtils.xslTransform(XmlUtils.stringToDocument(requestXml), cb.getRequestBodyXsl()));

        // build the request structure
        soapMessage.saveChanges();
        log.debug("Soap request successfully built: ");
        log.debug("  Body:\n"
                + XMLUtils.getPrettyXml(XMLUtils.getDocumentFromString(XmlUtils.nodeToString(body))));

        if (shConfig.useProxy()) {
            System.setProperty("http.proxySet", "true");
            System.setProperty("http.proxyHost", shConfig.getProxyHost());
            System.setProperty("http.proxyPort", "" + shConfig.getProxyPort());
            if (shConfig.useProxyCredentials()) {
                System.setProperty("http.proxyUser", shConfig.getProxyUser());
                System.setProperty("http.proxyPassword", shConfig.getProxyPassword());
            }
        }

        endpoint = new URL(shConfig.getEndpoint(cb.getEndpoint()));

        // now make that call over the SOAP connection
        SOAPMessage reply = null;
        AdapterException ae = null;

        for (int i = 1; (i <= shConfig.getRetryAttempts() && reply == null); i++) {
            log.debug("Attempt " + i + ": sending request to endpoint: " + endpoint);
            try {
                reply = soapConnection.call(soapMessage, endpoint);
                log.debug("Attempt " + i + ": received response: " + reply);
            } catch (Exception e) {
                ae = new AdapterException(502, String.format(AdapterConstants.ADAPTER_EM_CONNECTION, endpoint),
                        e);
                Thread.sleep(100);
            }
        }

        // close down the connection
        soapConnection.close();

        if (reply == null)
            throw ae;

        SOAPFault fault = reply.getSOAPBody().getFault();
        if (fault == null) {
            doc = reply.getSOAPBody().extractContentAsDocument();
        } else {
            // Extracts the entire Soap Fault message coming back from CIS
            String faultString = XmlUtils.nodeToString(fault);
            throw new AdapterException(503, faultString, null);
        }
    } catch (AdapterException e) {
        throw e;
    } catch (Exception e) {
        throw new AdapterException(504,
                String.format(AdapterConstants.ADAPTER_EM_CONNECTION, shConfig.getEndpoint(cb.getEndpoint())),
                e);
    } finally {
        if (shConfig.useProxy()) {
            System.setProperty("http.proxySet", "false");
        }
    }
    log.debug("Exiting send: " + cb.getName());

    return doc;
}

From source file:com.jaspersoft.ireport.designer.data.fieldsproviders.olap.OLAPQueryExecuter.java

protected SOAPMessage createQueryMessage(JRXMLADataSourceConnection xmlaConnection) {
    String queryStr = getQueryString();

    if (log.isDebugEnabled()) {
        log.debug("MDX query: " + queryStr);
    }/*from w ww. ja va 2 s.com*/

    try {
        // Force the use of Axis as message factory...

        MessageFactory mf = MessageFactory.newInstance();

        SOAPMessage message = mf.createMessage();

        MimeHeaders mh = message.getMimeHeaders();
        mh.setHeader("SOAPAction", "\"urn:schemas-microsoft-com:xml-analysis:Execute\"");
        //mh.setHeader("Content-Type", "text/xml; charset=utf-8");

        SOAPPart soapPart = message.getSOAPPart();
        SOAPEnvelope envelope = soapPart.getEnvelope();
        SOAPBody body = envelope.getBody();
        Name nEx = envelope.createName("Execute", "", XMLA_URI);

        SOAPElement eEx = body.addChildElement(nEx);

        // add the parameters

        // COMMAND parameter
        // <Command>
        // <Statement>queryStr</Statement>
        // </Command>
        Name nCom = envelope.createName("Command", "", XMLA_URI);
        SOAPElement eCommand = eEx.addChildElement(nCom);
        Name nSta = envelope.createName("Statement", "", XMLA_URI);
        SOAPElement eStatement = eCommand.addChildElement(nSta);
        eStatement.addTextNode(queryStr);

        // <Properties>
        // <PropertyList>
        // <DataSourceInfo>dataSource</DataSourceInfo>
        // <Catalog>catalog</Catalog>
        // <Format>Multidimensional</Format>
        // <AxisFormat>TupleFormat</AxisFormat>
        // </PropertyList>
        // </Properties>
        Map paraList = new HashMap();
        String datasource = xmlaConnection.getDatasource();
        paraList.put("DataSourceInfo", datasource);
        String catalog = xmlaConnection.getCatalog();
        paraList.put("Catalog", catalog);
        paraList.put("Format", "Multidimensional");
        paraList.put("AxisFormat", "TupleFormat");
        addParameterList(envelope, eEx, "Properties", "PropertyList", paraList);
        message.saveChanges();

        if (log.isDebugEnabled()) {
            log.debug("XML/A query message: " + message.toString());
        }

        return message;
    } catch (SOAPException e) {
        log.error(e);
        throw new JRRuntimeException(e);
    }
}

From source file:com.nortal.jroad.endpoint.AbstractXTeeBaseEndpoint.java

@SuppressWarnings("unchecked")
private XRoadProtocolVersion parseProtocolVersion(SOAPMessage requestMessage) throws SOAPException {
    XRoadProtocolVersion version = null;
    // Extract protocol version by headers
    if (requestMessage.getSOAPHeader() != null) {
        NodeList reqHeaders = requestMessage.getSOAPHeader().getChildNodes();
        for (int i = 0; i < reqHeaders.getLength(); i++) {
            Node reqHeader = reqHeaders.item(i);
            if (reqHeader.getNodeType() != Node.ELEMENT_NODE
                    || !reqHeader.getLocalName().equals(XTeeHeader.PROTOCOL_VERSION.getLocalPart())) {
                continue;
            }/*  w  w w.  j a  v  a 2  s  .co m*/

            if ((version = XRoadProtocolVersion
                    .getValueByVersionCode(SOAPUtil.getTextContent(reqHeader))) != null) {
                return version;
            }
        }
    }

    // Extract protocol version by namespaces
    SOAPEnvelope soapEnv = requestMessage.getSOAPPart().getEnvelope();
    Iterator<String> prefixes = soapEnv.getNamespacePrefixes();
    while (prefixes.hasNext()) {
        String nsPrefix = (String) prefixes.next();
        String nsURI = soapEnv.getNamespaceURI(nsPrefix).toLowerCase();
        if ((version = XRoadProtocolVersion.getValueByNamespaceURI(nsURI)) != null) {
            return version;
        }
    }
    throw new IllegalStateException("Unsupported protocol version");
}

From source file:com.twinsoft.convertigo.engine.translators.WebServiceTranslator.java

public void buildInputDocument(Context context, Object inputData) throws Exception {
    Engine.logBeans.debug("[WebServiceTranslator] Making input document");

    HttpServletRequest request = (HttpServletRequest) inputData;

    SOAPMessage requestMessage = (SOAPMessage) request
            .getAttribute(WebServiceServlet.REQUEST_MESSAGE_ATTRIBUTE);

    SOAPPart sp = requestMessage.getSOAPPart();
    SOAPEnvelope se = sp.getEnvelope();
    SOAPBody sb = se.getBody();//from  w  w w  .j av  a 2s.c  o  m

    Iterator<?> iterator = sb.getChildElements();
    SOAPElement method, parameter;
    String methodName;

    InputDocumentBuilder inputDocumentBuilder = new InputDocumentBuilder(context);

    while (iterator.hasNext()) {
        List<RequestableVariable> variableList = null; // jmc 12/06/26

        Object element = iterator.next();
        if (element instanceof SOAPElement) {
            method = (SOAPElement) element;

            methodName = method.getElementName().getLocalName();
            Engine.logBeans.debug("[WebServiceTranslator] Requested web service name: " + methodName);

            int i = methodName.indexOf("__");

            // for statefull transaction, don't replace the project
            if (context.project == null || !context.project.getName().equals(context.projectName)) {
                context.project = Engine.theApp.databaseObjectsManager.getProjectByName(context.projectName);
            }

            String connectorName = null;
            if (i == -1) {
                context.connectorName = null;
                context.sequenceName = methodName;
            } else {
                connectorName = methodName.substring(0, i);
                context.transactionName = methodName.substring(i + 2);
            }

            if ((connectorName != null) && (!connectorName.equals(context.connectorName))) {
                Engine.logBeans.debug("Connector name differs from previous one; requiring new session");
                context.isNewSession = true;
                context.connectorName = connectorName;
                Engine.logBeans.debug("[WebServiceTranslator] The connector is overridden to \""
                        + context.connectorName + "\".");
            }

            Engine.logBeans.debug("[WebServiceTranslator] Connector: "
                    + (context.connectorName == null ? "(default)" : context.connectorName));
            Engine.logBeans.debug("[WebServiceTranslator] Transaction: " + context.transactionName);

            //Connector connector = (context.connectorName == null ? context.project.getDefaultConnector() : context.project.getConnectorByName(context.connectorName));
            //Transaction transaction = (context.transactionName == null ? connector.getDefaultTransaction() : connector.getTransactionByName(context.transactionName));
            RequestableObject requestable = null;
            if (context.sequenceName != null) {
                requestable = context.project.getSequenceByName(context.sequenceName);
                variableList = ((Sequence) requestable).getVariablesList();
            } else if (context.connectorName != null) {
                if (context.transactionName != null) {
                    requestable = context.project.getConnectorByName(context.connectorName)
                            .getTransactionByName(context.transactionName);
                    if (requestable instanceof TransactionWithVariables) {
                        variableList = ((TransactionWithVariables) requestable).getVariablesList();
                    }
                }
            }

            Iterator<?> iterator2 = method.getChildElements();
            String parameterName, parameterValue;

            while (iterator2.hasNext()) {
                element = iterator2.next();
                if (element instanceof SOAPElement) {
                    parameter = (SOAPElement) element;
                    parameterName = parameter.getElementName().getLocalName();
                    parameterValue = parameter.getValue();
                    if (parameterValue == null) {
                        parameterValue = "";
                    }

                    if (variableList != null) { // jmc 12/06/26 hide hidden variables in sequences
                        String str = (String) Visibility.Logs.replaceVariables(variableList,
                                "" + parameterName + "=\"" + parameterValue + "\"");
                        Engine.logBeans.debug("   Parameter: " + str);
                    } else
                        Engine.logBeans.debug("   Parameter: " + parameterName + "=\"" + parameterValue + "\"");

                    // Handle convertigo parameters
                    if (parameterName.startsWith("__")) {
                        webServiceServletRequester.handleParameter(parameterName, parameterValue);
                    }

                    // Common parameter handling
                    if (inputDocumentBuilder.handleSpecialParameter(parameterName, parameterValue)) {
                        // handled
                    }
                    // Compatibility for Convertigo 2.x
                    else if (parameterName.equals("context")) {
                        // Just ignore it
                    } else {
                        SOAPElement soapArrayElement = null;
                        Iterator<?> iterator3;

                        String href = parameter.getAttributeValue(se.createName("href"));

                        String arrayType = parameter.getAttributeValue(se.createName("soapenc:arrayType"));
                        if (arrayType == null) {
                            iterator3 = parameter.getAllAttributes();
                            while (iterator3.hasNext()) {
                                element = iterator3.next();
                                if (element instanceof Name) {
                                    String s = ((Name) element).getQualifiedName();
                                    if (s.equals("soapenc:arrayType")) {
                                        arrayType = s;
                                        break;
                                    }
                                }
                            }
                        }

                        // Array (Microsoft .net)
                        if (href != null) {
                            Engine.logBeans.debug("Deserializing Microsoft .net array");
                            iterator3 = sb.getChildElements();
                            while (iterator3.hasNext()) {
                                element = iterator3.next();
                                if (element instanceof SOAPElement) {
                                    soapArrayElement = (SOAPElement) element;
                                    String elementId = soapArrayElement.getAttributeValue(se.createName("id"));
                                    if (elementId != null) {
                                        if (href.equals("#" + elementId)) {
                                            iterator3 = soapArrayElement.getChildElements();
                                            while (iterator3.hasNext()) {
                                                element = iterator3.next();
                                                if (element instanceof SOAPElement) {
                                                    break;
                                                }
                                            }
                                            break;
                                        }
                                    }
                                }
                            }

                            // Find the element with href id
                            iterator3 = sb.getChildElements();
                            while (iterator3.hasNext()) {
                                element = iterator3.next();
                                if (element instanceof SOAPElement) {
                                    soapArrayElement = (SOAPElement) element;
                                    String elementId = soapArrayElement.getAttributeValue(se.createName("id"));
                                    if (elementId != null) {
                                        if (href.equals("#" + elementId)) {
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                        // Array (Java/Axis)
                        else if (arrayType != null) {
                            Engine.logBeans.debug("Deserializing Java/Axis array");
                            soapArrayElement = parameter;
                        }
                        // If the node has children nodes, we assume it is an array.
                        else if (parameter.getChildElements().hasNext()) {
                            if (isSoapArray((IVariableContainer) requestable, parameterName)) {
                                Engine.logBeans.debug("Deserializing array");
                                soapArrayElement = parameter;
                            }
                        }

                        // Deserializing array
                        if (soapArrayElement != null) {
                            iterator3 = soapArrayElement.getChildElements();
                            while (iterator3.hasNext()) {
                                element = iterator3.next();
                                if (element instanceof SOAPElement) {
                                    soapArrayElement = (SOAPElement) element;
                                    parameterValue = soapArrayElement.getValue();
                                    if (parameterValue == null)
                                        parameterValue = "";
                                    handleSimpleVariable(context.inputDocument, soapArrayElement, parameterName,
                                            parameterValue, inputDocumentBuilder.transactionVariablesElement);
                                }
                            }
                        }
                        // Deserializing simple variable
                        else {
                            handleSimpleVariable(context.inputDocument, parameter, parameterName,
                                    parameterValue, inputDocumentBuilder.transactionVariablesElement);
                        }
                    }
                }
            }

            if (Engine.logBeans.isDebugEnabled()) {
                String soapMessage = SOAPUtils.toString(requestMessage, request.getCharacterEncoding());

                if (requestable instanceof TransactionWithVariables)
                    Engine.logBeans.debug("[WebServiceTranslator] SOAP message received:\n"
                            + Visibility.Logs.replaceVariables(
                                    ((TransactionWithVariables) (requestable)).getVariablesList(), request));
                else if (requestable instanceof Sequence)
                    Engine.logBeans.debug("[WebServiceTranslator] SOAP message received:\n" + Visibility.Logs
                            .replaceVariables(((Sequence) (requestable)).getVariablesList(), request));
                else
                    Engine.logBeans.debug("[WebServiceTranslator] SOAP message received:\n" + soapMessage);
            }

            break;
        }
    }

    Engine.logBeans.debug("[WebServiceTranslator] SOAP message analyzed");

    Engine.logBeans.debug("[WebServiceTranslator] Input document created");
}

From source file:it.cnr.icar.eric.common.SOAPMessenger.java

/** Send a SOAP request to the registry server. Main entry point for
 * this class. If credentials have been set on the registry connection,
 * they will be used to sign the request.
 *
 * @param requestString//  w ww  . j a  v  a2s .com
 *     String that will be placed in the body of the
 *     SOAP message to be sent to the server
 *
 * @param attachments
 *     HashMap consisting of entries each of which
 *     corresponds to an attachment where the entry key is the ContentId
 *     and the entry value is a javax.activation.DataHandler of the
 *     attachment. A parameter value of null means no attachments.
 *
 * @return
 *     RegistryResponseHolder that represents the response from the
 *     server
 */
@SuppressWarnings("unchecked")
public RegistryResponseHolder sendSoapRequest(String requestString, Map<?, ?> attachments)
        throws JAXRException {
    boolean logRequests = Boolean.valueOf(
            CommonProperties.getInstance().getProperty("eric.common.soapMessenger.logRequests", "false"))
            .booleanValue();

    if (logRequests) {
        PrintStream requestLogPS = null;
        try {
            requestLogPS = new PrintStream(
                    new FileOutputStream(java.io.File.createTempFile("SOAPMessenger_requestLog", ".xml")));
            requestLogPS.println(requestString);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (requestLogPS != null) {
                requestLogPS.close();
            }
        }
    }

    // =================================================================

    //        // Remove the XML Declaration, if any
    //        if (requestString.startsWith("<?xml")) {
    //            requestString = requestString.substring(requestString.indexOf("?>")+2).trim();
    //        }
    //
    //        StringBuffer soapText = new StringBuffer(
    //                "<soap-env:Envelope xmlns:soap-env=\"http://schemas.xmlsoap.org/soap/envelope/\">");
    //
    //      soapText.append("<soap-env:Header>\n");
    //      // tell server about our superior SOAP Fault capabilities
    //      soapText.append("<");
    //      soapText.append(BindingUtility.SOAP_CAPABILITY_HEADER_LocalName);
    //      soapText.append(" xmlns='");
    //      soapText.append(BindingUtility.SOAP_CAPABILITY_HEADER_Namespace);
    //      soapText.append("'>");
    //      soapText.append(BindingUtility.SOAP_CAPABILITY_ModernFaultCodes);
    //      soapText.append("</");
    //      soapText.append(BindingUtility.SOAP_CAPABILITY_HEADER_LocalName);
    //      soapText.append(">\n");
    //      soapText.append("</soap-env:Header>\n");

    //      soapText.append("<soap-env:Body>\n");
    //        soapText.append(requestString);
    //        soapText.append("</soap-env:Body>");
    //        soapText.append("</soap-env:Envelope>");

    MessageFactory messageFactory;
    SOAPMessage message = null;
    SOAPPart sp = null;
    SOAPEnvelope se = null;
    SOAPBody sb = null;
    SOAPHeader sh = null;

    if (log.isTraceEnabled()) {
        log.trace("requestString=\"" + requestString + "\"");
    }
    try {

        messageFactory = MessageFactory.newInstance();
        message = messageFactory.createMessage();

        sp = message.getSOAPPart();
        se = sp.getEnvelope();
        sb = se.getBody();
        sh = se.getHeader();

        /*
         * <soap-env:Envelope xmlns:soap-env="http://schemas.xmlsoap.org/soap/envelope/">
         *       <soap-env:Header>
         *          <capabilities xmlns="urn:freebxml:registry:soap">urn:freebxml:registry:soap:modernFaultCodes</capabilities>
         *
         * change with explicit namespace
         *          <ns1:capabilities xmlns:ns1="urn:freebxml:registry:soap">urn:freebxml:registry:soap:modernFaultCodes</ns1:capabilities>
                
         */
        SOAPHeaderElement capabilityElement = sh
                .addHeaderElement(se.createName(BindingUtility.SOAP_CAPABILITY_HEADER_LocalName, "ns1",
                        BindingUtility.SOAP_CAPABILITY_HEADER_Namespace));
        //           capabilityElement.addAttribute(
        //                 se.createName("xmlns"), 
        //                 BindingUtility.SOAP_CAPABILITY_HEADER_Namespace);
        capabilityElement.setTextContent(BindingUtility.SOAP_CAPABILITY_ModernFaultCodes);

        /*
         * body
         */

        // Remove the XML Declaration, if any
        if (requestString.startsWith("<?xml")) {
            requestString = requestString.substring(requestString.indexOf("?>") + 2).trim();
        }

        // Generate DOM Document from request xml string
        DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
        builderFactory.setNamespaceAware(true);
        InputStream stream = new ByteArrayInputStream(requestString.getBytes("UTF-8"));

        // Inject request into body
        sb.addDocument(builderFactory.newDocumentBuilder().parse(stream));

        // Is it never the case that there attachments but no credentials
        if ((attachments != null) && !attachments.isEmpty()) {
            addAttachments(message, attachments);
        }

        if (credentialInfo == null) {
            throw new JAXRException(resourceBundle.getString("message.credentialInfo"));
        }

        WSS4JSecurityUtilSAML.signSOAPEnvelopeOnClientSAML(se, credentialInfo);

        SOAPMessage response = send(message);

        // Check to see if the session has expired
        // by checking for an error response code
        // TODO: what error code to we look for?
        if (isSessionExpired(response)) {
            credentialInfo.sessionId = null;
            // sign the SOAPMessage this time
            // TODO: session - add method to do the signing
            // signSOAPMessage(msg);
            // send signed message
            // SOAPMessage response = send(msg);
        }

        // Process the main SOAPPart of the response
        //check for soapfault and throw RegistryException
        SOAPFault fault = response.getSOAPBody().getFault();
        if (fault != null) {
            throw createRegistryException(fault);
        }

        Reader reader = processResponseBody(response, "Response");

        RegistryResponseType ebResponse = null;

        try {
            Object obj = BindingUtility.getInstance().getJAXBContext().createUnmarshaller()
                    .unmarshal(new InputSource(reader));

            if (obj instanceof JAXBElement<?>)
                // if Element: take ComplexType from Element
                obj = ((JAXBElement<RegistryResponseType>) obj).getValue();

            ebResponse = (RegistryResponseType) obj;
        } catch (Exception x) {
            log.error(CommonResourceBundle.getInstance().getString("message.FailedToUnmarshalServerResponse"),
                    x);
            throw new JAXRException(resourceBundle.getString("message.invalidServerResponse"));
        }

        // Process the attachments of the response if any
        HashMap<String, Object> responseAttachments = processResponseAttachments(response);

        return new RegistryResponseHolder(ebResponse, responseAttachments);

    } catch (SAXException e) {
        throw new JAXRException(e);

    } catch (ParserConfigurationException e) {
        throw new JAXRException(e);

    } catch (UnsupportedEncodingException x) {
        throw new JAXRException(x);

    } catch (MessagingException x) {
        throw new JAXRException(x);

    } catch (FileNotFoundException x) {
        throw new JAXRException(x);

    } catch (IOException e) {
        throw new JAXRException(e);

    } catch (SOAPException x) {
        x.printStackTrace();
        throw new JAXRException(resourceBundle.getString("message.cannotConnect"), x);

    } catch (TransformerConfigurationException x) {
        throw new JAXRException(x);

    } catch (TransformerException x) {
        throw new JAXRException(x);
    }
}

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;
    }//from  w w  w . jav a  2  s.c o m

    // 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:eu.domibus.ebms3.receiver.MSHWebservice.java

/**
 * Handles Receipt generation for a incoming message
 *
 * @param request          the incoming message
 * @param legConfiguration processing information of the message
 * @param duplicate        indicates whether or not the message is a duplicate
 * @return the response message to the incoming request message
 * @throws EbMS3Exception if generation of receipt was not successful
 *//*from w w w. ja va  2s .c om*/
private SOAPMessage generateReceipt(SOAPMessage request, LegConfiguration legConfiguration, Boolean duplicate)
        throws EbMS3Exception {
    SOAPMessage responseMessage = null;

    assert legConfiguration != null;

    if (legConfiguration.getReliability() == null) {
        return responseMessage;
    }

    if (ReplyPattern.RESPONSE.equals(legConfiguration.getReliability().getReplyPattern())) {
        MSHWebservice.LOG.debug("Checking reliability for incoming message");
        try {
            responseMessage = this.messageFactory.createMessage();
            Source messageToReceiptTransform = new StreamSource(
                    this.getClass().getClassLoader().getResourceAsStream("./xslt/GenerateAS4Receipt.xsl"));
            Transformer transformer = this.transformerFactory.newTransformer(messageToReceiptTransform);
            Source requestMessage = request.getSOAPPart().getContent();
            transformer.setParameter("messageid", this.messageIdGenerator.generateMessageId());
            transformer.setParameter("timestamp", this.timestampDateFormatter.generateTimestamp());
            transformer.setParameter("nonRepudiation",
                    Boolean.toString(legConfiguration.getReliability().isNonRepudiation()));

            DOMResult domResult = new DOMResult();

            transformer.transform(requestMessage, domResult);
            responseMessage.getSOAPPart().setContent(new DOMSource(domResult.getNode()));

            //                transformer.transform(requestMessage, new DOMResult(responseMessage.getSOAPPart().getEnvelope()));
        } catch (TransformerConfigurationException | SOAPException e) {
            // this cannot happen
            assert false;
            throw new RuntimeException(e);
        } catch (TransformerException e) {
            throw new EbMS3Exception(EbMS3Exception.EbMS3ErrorCode.EBMS_0201,
                    "Could not generate Receipt. Check security header and non-repudiation settings", null, e,
                    MSHRole.RECEIVING);
        }
    }

    return responseMessage;
}