Search in sources :

Example 21 with MimeHeaders

use of javax.xml.soap.MimeHeaders in project tdi-studio-se by Talend.

the class SOAPUtil method invokeSOAP.

public void invokeSOAP(String version, String destination, String soapAction, String soapMessage) throws SOAPException, TransformerException, ParserConfigurationException, FileNotFoundException, UnsupportedEncodingException {
    MessageFactory messageFactory = null;
    if (version.equals(SOAP12)) {
        messageFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL);
    } else {
        messageFactory = MessageFactory.newInstance();
    }
    SOAPMessage message = messageFactory.createMessage();
    MimeHeaders mimeHeaders = message.getMimeHeaders();
    mimeHeaders.setHeader("SOAPAction", soapAction);
    if (basicAuth) {
        addBasicAuthHeader(mimeHeaders, username, password);
    }
    // Create objects for the message parts
    SOAPPart soapPart = message.getSOAPPart();
    String encoding = getEncoding(soapMessage);
    ByteArrayInputStream stream = new ByteArrayInputStream(soapMessage.getBytes(encoding));
    StreamSource preppedMsgSrc = new StreamSource(stream);
    soapPart.setContent(preppedMsgSrc);
    // InputStream stream = new FileInputStream(new File("d://soap.txt"));
    // StreamSource preppedMsgSrc = new StreamSource(stream);
    // soapPart.setContent(preppedMsgSrc);
    message.saveChanges();
    // Send the message
    SOAPMessage reply = connection.call(message, destination);
    SOAPPart reSoapPart = reply.getSOAPPart();
    if (reSoapPart != null && reSoapPart instanceof SOAPPartImpl) {
        ((SOAPPartImpl) reSoapPart).setSourceCharsetEncoding(encoding);
    }
    SOAPEnvelope reEnvelope = reSoapPart.getEnvelope();
    SOAPHeader reHeader = reEnvelope.getHeader();
    if (reHeader != null) {
        setReHeaderMessage(Doc2StringWithoutDeclare(extractContentAsDocument(reHeader)));
    }
    SOAPBody reBody = reEnvelope.getBody();
    if (reBody.getFault() != null) {
        hasFault = true;
        setReFaultMessage(Doc2StringWithoutDeclare(extractContentAsDocument(reBody)));
        setReBodyMessage(null);
    } else {
        hasFault = false;
        if (reBody.getChildNodes().getLength() < 1) {
            setReBodyMessage(null);
        } else if (reBody.getChildNodes().getLength() == 1 && reBody.getChildNodes().item(0) instanceof javax.xml.soap.Text) {
            setReBodyMessage(null);
        } else {
            setReBodyMessage(Doc2StringWithoutDeclare(extractContentAsDocument(reBody)));
        }
        setReFaultMessage(null);
    }
}
Also used : SOAPPartImpl(com.sun.xml.messaging.saaj.soap.SOAPPartImpl) MessageFactory(javax.xml.soap.MessageFactory) StreamSource(javax.xml.transform.stream.StreamSource) SOAPEnvelope(javax.xml.soap.SOAPEnvelope) SOAPMessage(javax.xml.soap.SOAPMessage) MimeHeaders(javax.xml.soap.MimeHeaders) SOAPBody(javax.xml.soap.SOAPBody) ByteArrayInputStream(java.io.ByteArrayInputStream) SOAPPart(javax.xml.soap.SOAPPart) SOAPHeader(javax.xml.soap.SOAPHeader)

Example 22 with MimeHeaders

use of javax.xml.soap.MimeHeaders in project Lucee by lucee.

the class RPCServer method doPost.

/**
 * Process a POST to the servlet by handing it off to the Axis Engine.
 * Here is where SOAP messages are received
 * @param req posted request
 * @param res respose
 * @throws ServletException trouble
 * @throws IOException different trouble
 */
public void doPost(HttpServletRequest req, HttpServletResponse res, Component component) throws ServletException, IOException {
    long t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0;
    String soapAction = null;
    MessageContext msgContext = null;
    Message responseMsg = null;
    String contentType = null;
    InputStream is = null;
    try {
        AxisEngine engine = getEngine();
        if (engine == null) {
            // !!! should return a SOAP fault...
            ServletException se = new ServletException(Messages.getMessage("noEngine00"));
            log.debug("No Engine!", se);
            throw se;
        }
        // provide performance boost.
        res.setBufferSize(1024 * 8);
        /**
         * get message context w/ various properties set
         */
        msgContext = createMessageContext(engine, req, res, component);
        ComponentController.set(msgContext);
        // ? where it would also be picked up for 'doGet()' ?
        if (securityProvider != null) {
            if (isDebug) {
                log.debug("securityProvider:" + securityProvider);
            }
            msgContext.setProperty(MessageContext.SECURITY_PROVIDER, securityProvider);
        }
        is = req.getInputStream();
        Message requestMsg = new Message(is, false, req.getHeader(HTTPConstants.HEADER_CONTENT_TYPE), req.getHeader(HTTPConstants.HEADER_CONTENT_LOCATION));
        // Transfer HTTP headers to MIME headers for request message.
        MimeHeaders requestMimeHeaders = requestMsg.getMimeHeaders();
        for (Enumeration e = req.getHeaderNames(); e.hasMoreElements(); ) {
            String headerName = (String) e.nextElement();
            for (Enumeration f = req.getHeaders(headerName); f.hasMoreElements(); ) {
                String headerValue = (String) f.nextElement();
                requestMimeHeaders.addHeader(headerName, headerValue);
            }
        }
        if (isDebug) {
            log.debug("Request Message:" + requestMsg);
        /* Set the request(incoming) message field in the context */
        /**
         *******************************************************
         */
        }
        msgContext.setRequestMessage(requestMsg);
        String url = HttpUtils.getRequestURL(req).toString().toLowerCase();
        msgContext.setProperty(MessageContext.TRANS_URL, url);
        // put character encoding of request to message context
        // in order to reuse it during the whole process.
        String requestEncoding;
        try {
            requestEncoding = (String) requestMsg.getProperty(SOAPMessage.CHARACTER_SET_ENCODING);
            if (requestEncoding != null) {
                msgContext.setProperty(SOAPMessage.CHARACTER_SET_ENCODING, requestEncoding);
            }
        } catch (SOAPException e1) {
        }
        try {
            /**
             * Save the SOAPAction header in the MessageContext bag.
             * This will be used to tell the Axis Engine which service
             * is being invoked.  This will save us the trouble of
             * having to parse the Request message - although we will
             * need to double-check later on that the SOAPAction header
             * does in fact match the URI in the body.
             */
            // (is this last stmt true??? (I don't think so - Glen))
            /**
             *****************************************************
             */
            soapAction = getSoapAction(req);
            if (soapAction != null) {
                msgContext.setUseSOAPAction(true);
                msgContext.setSOAPActionURI(soapAction);
            }
            // Create a Session wrapper for the HTTP session.
            // These can/should be pooled at some point.
            // (Sam is Watching! :-)
            msgContext.setSession(new AxisHttpSession(req));
            if (log.isDebugEnabled()) {
                t1 = System.currentTimeMillis();
            }
            /**
             **************************
             */
            if (isDebug) {
                log.debug("Invoking Axis Engine.");
            // here we run the message by the engine
            }
            engine.invoke(msgContext);
            if (isDebug) {
                log.debug("Return from Axis Engine.");
            }
            if (log.isDebugEnabled())
                t2 = System.currentTimeMillis();
            responseMsg = msgContext.getResponseMessage();
        // We used to throw exceptions on null response messages.
        // They are actually OK in certain situations (asynchronous
        // services), so fall through here and return an ACCEPTED
        // status code below.  Might want to install a configurable
        // error check for this later.
        } catch (AxisFault fault) {
            // log and sanitize
            processAxisFault(fault);
            configureResponseFromAxisFault(res, fault);
            responseMsg = msgContext.getResponseMessage();
            if (responseMsg == null) {
                responseMsg = new Message(fault);
                ((org.apache.axis.SOAPPart) responseMsg.getSOAPPart()).getMessage().setMessageContext(msgContext);
            }
        } catch (Throwable t) {
            ExceptionUtil.rethrowIfNecessary(t);
            if (t instanceof InvocationTargetException)
                t = ((InvocationTargetException) t).getTargetException();
            // Exception
            if (t instanceof Exception) {
                Exception e = (Exception) t;
                // other exceptions are internal trouble
                responseMsg = msgContext.getResponseMessage();
                res.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                responseMsg = convertExceptionToAxisFault(e, responseMsg);
                ((org.apache.axis.SOAPPart) responseMsg.getSOAPPart()).getMessage().setMessageContext(msgContext);
            } else // throwable
            {
                logException(t);
                // other exceptions are internal trouble
                responseMsg = msgContext.getResponseMessage();
                res.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                responseMsg = new Message(new AxisFault(t.toString(), t));
                ((org.apache.axis.SOAPPart) responseMsg.getSOAPPart()).getMessage().setMessageContext(msgContext);
            }
        }
    } catch (AxisFault fault) {
        processAxisFault(fault);
        configureResponseFromAxisFault(res, fault);
        responseMsg = msgContext.getResponseMessage();
        if (responseMsg == null) {
            responseMsg = new Message(fault);
            ((org.apache.axis.SOAPPart) responseMsg.getSOAPPart()).getMessage().setMessageContext(msgContext);
        }
    } finally {
        IOUtil.closeEL(is);
    }
    if (log.isDebugEnabled()) {
        t3 = System.currentTimeMillis();
    }
    /**
     ********************************
     */
    if (responseMsg != null) {
        // Transfer MIME headers to HTTP headers for response message.
        MimeHeaders responseMimeHeaders = responseMsg.getMimeHeaders();
        for (Iterator i = responseMimeHeaders.getAllHeaders(); i.hasNext(); ) {
            MimeHeader responseMimeHeader = (MimeHeader) i.next();
            res.addHeader(responseMimeHeader.getName(), responseMimeHeader.getValue());
        }
        // synchronize the character encoding of request and response
        String responseEncoding = (String) msgContext.getProperty(SOAPMessage.CHARACTER_SET_ENCODING);
        if (responseEncoding != null) {
            try {
                responseMsg.setProperty(SOAPMessage.CHARACTER_SET_ENCODING, responseEncoding);
            } catch (SOAPException e) {
            }
        }
        // determine content type from message response
        contentType = responseMsg.getContentType(msgContext.getSOAPConstants());
        sendResponse(contentType, res, responseMsg);
    } else {
        // No content, so just indicate accepted
        res.setStatus(202);
    }
    if (isDebug) {
        log.debug("Response sent.");
        log.debug("Exit: doPost()");
    }
    if (log.isDebugEnabled()) {
        t4 = System.currentTimeMillis();
        log.debug("axisServlet.doPost: " + soapAction + " pre=" + (t1 - t0) + " invoke=" + (t2 - t1) + " post=" + (t3 - t2) + " send=" + (t4 - t3) + " " + msgContext.getTargetService() + "." + ((msgContext.getOperation() == null) ? "" : msgContext.getOperation().getName()));
    }
}
Also used : AxisFault(org.apache.axis.AxisFault) Enumeration(java.util.Enumeration) Message(org.apache.axis.Message) SOAPMessage(javax.xml.soap.SOAPMessage) InputStream(java.io.InputStream) AxisHttpSession(org.apache.axis.transport.http.AxisHttpSession) InvocationTargetException(java.lang.reflect.InvocationTargetException) ServletException(javax.servlet.ServletException) SOAPException(javax.xml.soap.SOAPException) PageServletException(lucee.runtime.exp.PageServletException) PageException(lucee.runtime.exp.PageException) InvocationTargetException(java.lang.reflect.InvocationTargetException) ClassException(lucee.commons.lang.ClassException) ConfigurationException(org.apache.axis.ConfigurationException) IOException(java.io.IOException) ServletException(javax.servlet.ServletException) PageServletException(lucee.runtime.exp.PageServletException) MimeHeaders(javax.xml.soap.MimeHeaders) MimeHeader(javax.xml.soap.MimeHeader) SOAPException(javax.xml.soap.SOAPException) Iterator(java.util.Iterator) MessageContext(org.apache.axis.MessageContext) AxisEngine(org.apache.axis.AxisEngine)

Example 23 with MimeHeaders

use of javax.xml.soap.MimeHeaders in project Payara by payara.

the class WebServicesDelegateImpl method getOpName.

private String getOpName(SOAPMessage message) {
    if (message == null) {
        return null;
    }
    String rvalue = null;
    // first look for a SOAPAction header.
    // this is what .net uses to identify the operation
    MimeHeaders headers = message.getMimeHeaders();
    if (headers != null) {
        String[] actions = headers.getHeader("SOAPAction");
        if (actions != null && actions.length > 0) {
            rvalue = actions[0];
            if (rvalue != null && rvalue.equals("\"\"")) {
                rvalue = null;
            }
        }
    }
    if (rvalue == null) {
        Name name = getName(message);
        if (name != null) {
            rvalue = name.getLocalName();
        }
    }
    return rvalue;
}
Also used : MimeHeaders(javax.xml.soap.MimeHeaders) Name(javax.xml.soap.Name) QName(javax.xml.namespace.QName)

Example 24 with MimeHeaders

use of javax.xml.soap.MimeHeaders in project Payara by payara.

the class EjbWebServiceDispatcher method handlePost.

private void handlePost(HttpServletRequest req, HttpServletResponse resp, EjbRuntimeEndpointInfo endpointInfo) throws IOException, SOAPException {
    JAXRPCEndpointImpl endpoint = null;
    String messageID = null;
    SOAPMessageContext msgContext = null;
    try {
        MimeHeaders headers = wsUtil.getHeaders(req);
        if (!wsUtil.hasTextXmlContentType(headers)) {
            wsUtil.writeInvalidContentType(resp);
            return;
        }
        msgContext = rpcFactory.createSOAPMessageContext();
        SOAPMessage message = createSOAPMessage(req, headers);
        boolean wssSucceded = true;
        if (message != null) {
            msgContext.setMessage(message);
            // get the endpoint info
            endpoint = (JAXRPCEndpointImpl) endpointInfo.getEndpoint().getExtraAttribute(EndpointImpl.NAME);
            if (endpoint != null) {
                // first global notification
                if (wsEngine.hasGlobalMessageListener()) {
                    messageID = wsEngine.preProcessRequest(endpoint);
                }
            } else {
                if (logger.isLoggable(Level.FINE)) {
                    logger.log(Level.FINE, LogUtils.MISSING_MONITORING_INFO, req.getRequestURI());
                }
            }
            AdapterInvocationInfo aInfo = null;
            if (!(endpointInfo instanceof Ejb2RuntimeEndpointInfo)) {
                throw new IllegalArgumentException(endpointInfo + "is not instance of Ejb2RuntimeEndpointInfo.");
            }
            try {
                Ejb2RuntimeEndpointInfo endpointInfo2 = (Ejb2RuntimeEndpointInfo) endpointInfo;
                // Do ejb container pre-invocation and pre-handler
                // logic
                aInfo = endpointInfo2.getHandlerImplementor();
                // Set message context in invocation
                EJBInvocation.class.cast(aInfo.getInv()).setMessageContext(msgContext);
                // Set http response object so one-way operations will
                // response before actual business method invocation.
                msgContext.setProperty(HTTP_SERVLET_RESPONSE, resp);
                if (secServ != null) {
                    wssSucceded = secServ.validateRequest(endpointInfo2.getServerAuthConfig(), (StreamingHandler) aInfo.getHandler(), msgContext);
                }
                // Trace if necessary
                if (messageID != null || (endpoint != null && endpoint.hasListeners())) {
                    // create the thread local
                    ThreadLocalInfo threadLocalInfo = new ThreadLocalInfo(messageID, req);
                    wsEngine.getThreadLocal().set(threadLocalInfo);
                    if (endpoint != null) {
                        endpoint.processRequest(msgContext);
                    } else {
                        if (logger.isLoggable(Level.FINE)) {
                            logger.log(Level.FINE, LogUtils.MISSING_MONITORING_INFO, req.getRequestURI());
                        }
                    }
                }
                // which will be flow back into the ejb container.
                if (wssSucceded) {
                    aInfo.getHandler().handle(msgContext);
                }
            } finally {
                // if implementor is null.
                if (aInfo != null) {
                    endpointInfo.releaseImplementor(aInfo.getInv());
                }
            }
        } else {
            String errorMsg = MessageFormat.format(logger.getResourceBundle().getString(LogUtils.NULL_MESSAGE), endpointInfo.getEndpoint().getEndpointName(), endpointInfo.getEndpointAddressUri());
            if (logger.isLoggable(Level.FINE)) {
                logger.fine(errorMsg);
            }
            msgContext.writeSimpleErrorResponse(FAULT_CODE_CLIENT, errorMsg);
        }
        if (messageID != null || endpoint != null) {
            endpoint.processResponse(msgContext);
        }
        SOAPMessage reply = msgContext.getMessage();
        if (secServ != null && wssSucceded) {
            if (!(endpointInfo instanceof Ejb2RuntimeEndpointInfo)) {
                throw new IllegalArgumentException(endpointInfo + "is not instance of Ejb2RuntimeEndpointInfo.");
            }
            Ejb2RuntimeEndpointInfo endpointInfo2 = (Ejb2RuntimeEndpointInfo) endpointInfo;
            secServ.secureResponse(endpointInfo2.getServerAuthConfig(), (StreamingHandler) endpointInfo2.getHandlerImplementor().getHandler(), msgContext);
        }
        if (reply.saveRequired()) {
            reply.saveChanges();
        }
        wsUtil.writeReply(resp, msgContext);
    } catch (Throwable e) {
        String errorMessage = MessageFormat.format(logger.getResourceBundle().getString(LogUtils.ERROR_ON_EJB), new Object[] { endpointInfo.getEndpoint().getEndpointName(), endpointInfo.getEndpointAddressUri(), e.getMessage() });
        logger.log(Level.WARNING, errorMessage, e);
        SOAPMessageContext errorMsgContext = rpcFactory.createSOAPMessageContext();
        errorMsgContext.writeSimpleErrorResponse(SOAPConstants.FAULT_CODE_SERVER, errorMessage);
        resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        if (messageID != null || endpoint != null) {
            endpoint.processResponse(errorMsgContext);
        }
        wsUtil.writeReply(resp, errorMsgContext);
    }
    // final tracing notification
    if (messageID != null) {
        HttpResponseInfoImpl response = new HttpResponseInfoImpl(resp);
        wsEngine.postProcessResponse(messageID, response);
    }
}
Also used : StreamingHandler(com.sun.xml.rpc.spi.runtime.StreamingHandler) SOAPMessage(javax.xml.soap.SOAPMessage) MimeHeaders(javax.xml.soap.MimeHeaders) SOAPMessageContext(com.sun.xml.rpc.spi.runtime.SOAPMessageContext) EJBInvocation(org.glassfish.ejb.api.EJBInvocation)

Aggregations

MimeHeaders (javax.xml.soap.MimeHeaders)24 SOAPMessage (javax.xml.soap.SOAPMessage)16 SOAPException (javax.xml.soap.SOAPException)9 ByteArrayInputStream (java.io.ByteArrayInputStream)8 IOException (java.io.IOException)7 InputStream (java.io.InputStream)6 ServletException (javax.servlet.ServletException)5 MessageFactory (javax.xml.soap.MessageFactory)4 FSException (com.sun.identity.federation.common.FSException)3 ByteArrayOutputStream (java.io.ByteArrayOutputStream)3 Enumeration (java.util.Enumeration)3 StringTokenizer (java.util.StringTokenizer)3 ServletInputStream (javax.servlet.ServletInputStream)3 FSAccountMgmtException (com.sun.identity.federation.accountmgmt.FSAccountMgmtException)2 SessionException (com.sun.identity.plugin.session.SessionException)2 SAMLException (com.sun.identity.saml.common.SAMLException)2 SAMLRequestVersionTooHighException (com.sun.identity.saml.common.SAMLRequestVersionTooHighException)2 SAMLRequestVersionTooLowException (com.sun.identity.saml.common.SAMLRequestVersionTooLowException)2 SAMLRequesterException (com.sun.identity.saml.common.SAMLRequesterException)2 SOAPPartImpl (com.sun.xml.messaging.saaj.soap.SOAPPartImpl)2