Search in sources :

Example 6 with MessageContext

use of org.apache.axis.MessageContext in project iaf by ibissource.

the class SoapWrapper method signMessage.

public String signMessage(String soapMessage, String user, String password) throws SenderException {
    try {
        WSSecurityEngine secEngine = WSSecurityEngine.getInstance();
        WSSConfig config = secEngine.getWssConfig();
        config.setPrecisionInMilliSeconds(false);
        // create context
        AxisClient tmpEngine = new AxisClient(new NullProvider());
        MessageContext msgContext = new MessageContext(tmpEngine);
        InputStream in = new ByteArrayInputStream(soapMessage.getBytes());
        Message msg = new Message(in);
        msg.setMessageContext(msgContext);
        // create unsigned envelope
        SOAPEnvelope unsignedEnvelope = msg.getSOAPEnvelope();
        Document doc = unsignedEnvelope.getAsDocument();
        // create security header and insert it into unsigned envelope
        WSSecHeader secHeader = new WSSecHeader();
        secHeader.insertSecurityHeader(doc);
        // add a UsernameToken
        WSSecUsernameToken tokenBuilder = new WSSecUsernameToken();
        tokenBuilder.setPasswordType(WSConstants.PASSWORD_DIGEST);
        tokenBuilder.setUserInfo(user, password);
        tokenBuilder.addNonce();
        tokenBuilder.addCreated();
        tokenBuilder.prepare(doc);
        WSSecSignature sign = new WSSecSignature();
        sign.setUsernameToken(tokenBuilder);
        sign.setKeyIdentifierType(WSConstants.UT_SIGNING);
        sign.setSignatureAlgorithm(XMLSignature.ALGO_ID_MAC_HMAC_SHA1);
        sign.build(doc, null, secHeader);
        tokenBuilder.prependToHeader(secHeader);
        // add a Timestamp
        WSSecTimestamp timestampBuilder = new WSSecTimestamp();
        timestampBuilder.setTimeToLive(300);
        timestampBuilder.prepare(doc);
        timestampBuilder.prependToHeader(secHeader);
        Document signedDoc = doc;
        return DOM2Writer.nodeToString(signedDoc);
    } catch (Exception e) {
        throw new SenderException(e);
    }
}
Also used : Message(org.apache.axis.Message) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) NullProvider(org.apache.axis.configuration.NullProvider) WSSecSignature(org.apache.ws.security.message.WSSecSignature) SOAPEnvelope(org.apache.axis.message.SOAPEnvelope) Document(org.w3c.dom.Document) WSSecTimestamp(org.apache.ws.security.message.WSSecTimestamp) TransformerException(javax.xml.transform.TransformerException) TransformerConfigurationException(javax.xml.transform.TransformerConfigurationException) DomBuilderException(nl.nn.adapterframework.util.DomBuilderException) IOException(java.io.IOException) ConfigurationException(nl.nn.adapterframework.configuration.ConfigurationException) SenderException(nl.nn.adapterframework.core.SenderException) WSSecHeader(org.apache.ws.security.message.WSSecHeader) WSSConfig(org.apache.ws.security.WSSConfig) AxisClient(org.apache.axis.client.AxisClient) ByteArrayInputStream(java.io.ByteArrayInputStream) WSSecurityEngine(org.apache.ws.security.WSSecurityEngine) MessageContext(org.apache.axis.MessageContext) SenderException(nl.nn.adapterframework.core.SenderException) WSSecUsernameToken(org.apache.ws.security.message.WSSecUsernameToken)

Example 7 with MessageContext

use of org.apache.axis.MessageContext in project Lucee by lucee.

the class AxisUtil method getSOAPResponseHeader.

public static Object getSOAPResponseHeader(PageContext pc, WSClient client, String namespace, String name, boolean asXML) throws Exception {
    MessageContext context = getMessageContext(client);
    SOAPEnvelope env = context.getResponseMessage().getSOAPEnvelope();
    SOAPHeaderElement header = env.getHeaderByName(namespace, name);
    return toValue(header, asXML);
}
Also used : SOAPHeaderElement(org.apache.axis.message.SOAPHeaderElement) MessageContext(org.apache.axis.MessageContext) SOAPEnvelope(org.apache.axis.message.SOAPEnvelope)

Example 8 with MessageContext

use of org.apache.axis.MessageContext 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 9 with MessageContext

use of org.apache.axis.MessageContext in project Lucee by lucee.

the class RPCServer method createMessageContext.

/**
 * Place the Request message in the MessagContext object - notice
 * that we just leave it as a 'ServletRequest' object and let the
 * Message processing routine convert it - we don't do it since we
 * don't know how it's going to be used - perhaps it might not
 * even need to be parsed.
 * @return a message context
 */
private MessageContext createMessageContext(AxisEngine engine, HttpServletRequest req, HttpServletResponse res, Component component) {
    MessageContext msgContext = new MessageContext(engine);
    String requestPath = getRequestPath(req);
    if (isDebug) {
        log.debug("MessageContext:" + msgContext);
        log.debug("HEADER_CONTENT_TYPE:" + req.getHeader(HTTPConstants.HEADER_CONTENT_TYPE));
        log.debug("HEADER_CONTENT_LOCATION:" + req.getHeader(HTTPConstants.HEADER_CONTENT_LOCATION));
        log.debug("Constants.MC_HOME_DIR:" + String.valueOf(homeDir));
        log.debug("Constants.MC_RELATIVE_PATH:" + requestPath);
        log.debug("HTTPConstants.MC_HTTP_SERVLETLOCATION:" + String.valueOf(webInfPath));
        log.debug("HTTPConstants.MC_HTTP_SERVLETPATHINFO:" + req.getPathInfo());
        log.debug("HTTPConstants.HEADER_AUTHORIZATION:" + req.getHeader(HTTPConstants.HEADER_AUTHORIZATION));
        log.debug("Constants.MC_REMOTE_ADDR:" + req.getRemoteAddr());
        log.debug("configPath:" + String.valueOf(webInfPath));
    }
    /* Set the Transport */
    /**
     ******************
     */
    msgContext.setTransportName("http");
    /* Save some HTTP specific info in the bag in case someone needs it */
    /**
     *****************************************************************
     */
    // msgContext.setProperty(Constants.MC_JWS_CLASSDIR, jwsClassDir);
    msgContext.setProperty(Constants.MC_HOME_DIR, homeDir);
    msgContext.setProperty(Constants.MC_RELATIVE_PATH, requestPath);
    msgContext.setProperty(HTTPConstants.MC_HTTP_SERVLET, this);
    msgContext.setProperty(HTTPConstants.MC_HTTP_SERVLETREQUEST, req);
    msgContext.setProperty(HTTPConstants.MC_HTTP_SERVLETRESPONSE, res);
    msgContext.setProperty(HTTPConstants.MC_HTTP_SERVLETLOCATION, webInfPath);
    msgContext.setProperty(HTTPConstants.MC_HTTP_SERVLETPATHINFO, req.getPathInfo());
    msgContext.setProperty(HTTPConstants.HEADER_AUTHORIZATION, req.getHeader(HTTPConstants.HEADER_AUTHORIZATION));
    msgContext.setProperty(lucee.runtime.net.rpc.server.Constants.COMPONENT, component);
    msgContext.setProperty(Constants.MC_REMOTE_ADDR, req.getRemoteAddr());
    // Set up a javax.xml.rpc.server.ServletEndpointContext
    ServletEndpointContextImpl sec = new ServletEndpointContextImpl();
    msgContext.setProperty(Constants.MC_SERVLET_ENDPOINT_CONTEXT, sec);
    /* Save the real path */
    /**
     *******************
     */
    String realpath = context.getRealPath(requestPath);
    if (realpath != null) {
        msgContext.setProperty(Constants.MC_REALPATH, realpath);
    }
    msgContext.setProperty(Constants.MC_CONFIGPATH, webInfPath);
    return msgContext;
}
Also used : ServletEndpointContextImpl(org.apache.axis.transport.http.ServletEndpointContextImpl) MessageContext(org.apache.axis.MessageContext)

Example 10 with MessageContext

use of org.apache.axis.MessageContext in project tomee by apache.

the class AxisWsContainer method doService.

protected void doService(final HttpRequest req, final HttpResponse res) throws Exception {
    final org.apache.axis.MessageContext messageContext = new org.apache.axis.MessageContext(null);
    req.setAttribute(WsConstants.MESSAGE_CONTEXT, messageContext);
    messageContext.setClassLoader(classLoader);
    Message responseMessage;
    String contentType = req.getHeader(HTTPConstants.HEADER_CONTENT_TYPE);
    final String contentLocation = req.getHeader(HTTPConstants.HEADER_CONTENT_LOCATION);
    final InputStream inputStream = req.getInputStream();
    final Message requestMessage = new Message(inputStream, false, contentType, contentLocation);
    messageContext.setRequestMessage(requestMessage);
    messageContext.setProperty(HTTPConstants.MC_HTTP_SERVLETPATHINFO, req.getURI().getPath());
    messageContext.setProperty(org.apache.axis.MessageContext.TRANS_URL, req.getURI().toString());
    messageContext.setService(service);
    messageContext.setProperty(REQUEST, req);
    messageContext.setProperty(RESPONSE, res);
    messageContext.setProperty(AxisEngine.PROP_DISABLE_PRETTY_XML, Boolean.TRUE);
    final ClassLoader oldClassLoader = Thread.currentThread().getContextClassLoader();
    try {
        try {
            final String characterEncoding = (String) requestMessage.getProperty(SOAPMessage.CHARACTER_SET_ENCODING);
            if (characterEncoding != null) {
                messageContext.setProperty(SOAPMessage.CHARACTER_SET_ENCODING, characterEncoding);
            } else {
                messageContext.setProperty(SOAPMessage.CHARACTER_SET_ENCODING, "UTF-8");
            }
            final String soapAction = req.getHeader(HTTPConstants.HEADER_SOAP_ACTION);
            if (soapAction != null) {
                messageContext.setUseSOAPAction(true);
                messageContext.setSOAPActionURI(soapAction);
            }
            final SOAPEnvelope env = requestMessage.getSOAPEnvelope();
            if (env != null && env.getSOAPConstants() != null) {
                messageContext.setSOAPConstants(env.getSOAPConstants());
            }
            final SOAPService service = messageContext.getService();
            Thread.currentThread().setContextClassLoader(classLoader);
            service.invoke(messageContext);
            responseMessage = messageContext.getResponseMessage();
        } catch (final AxisFault fault) {
            if (req.getMethod().equals(HttpRequest.Method.GET.name()) && req.getParameters().isEmpty()) {
                String serviceName = req.getURI().getRawPath();
                serviceName = serviceName.substring(serviceName.lastIndexOf("/") + 1);
                printServiceInfo(res, serviceName);
                return;
            } else {
                responseMessage = handleFault(fault, res, messageContext);
            }
        } catch (final Exception e) {
            responseMessage = handleException(messageContext, res, e);
        }
        // TODO investigate and fix operation == null!
        if (messageContext.getOperation() != null) {
            if (messageContext.getOperation().getMep() == OperationType.ONE_WAY) {
                // No content, so just indicate accepted
                res.setStatus(HttpServletResponse.SC_ACCEPTED);
                return;
            } else if (responseMessage == null) {
                responseMessage = handleException(messageContext, null, new ServerRuntimeException("No response for non-one-way operation"));
            }
        } else if (responseMessage == null) {
            res.setStatus(HttpServletResponse.SC_ACCEPTED);
            return;
        }
        try {
            final SOAPConstants soapConstants = messageContext.getSOAPConstants();
            final String contentType1 = responseMessage.getContentType(soapConstants);
            res.setContentType(contentType1);
            // Transfer MIME headers to HTTP headers for response message.
            final MimeHeaders responseMimeHeaders = responseMessage.getMimeHeaders();
            for (final Iterator i = responseMimeHeaders.getAllHeaders(); i.hasNext(); ) {
                final MimeHeader responseMimeHeader = (MimeHeader) i.next();
                res.setHeader(responseMimeHeader.getName(), responseMimeHeader.getValue());
            }
            // TODO discuss this with dims.
            // // synchronize the character encoding of request and response
            // String responseEncoding = (String) messageContext.getProperty(
            // SOAPMessage.CHARACTER_SET_ENCODING);
            // if (responseEncoding != null) {
            // try {
            // responseMessage.setProperty(SOAPMessage.CHARACTER_SET_ENCODING,
            // responseEncoding);
            // } catch (SOAPException e) {
            // log.info(Messages.getMessage("exception00"), e);
            // }
            // }
            // determine content type from message response
            contentType = responseMessage.getContentType(messageContext.getSOAPConstants());
            responseMessage.writeTo(res.getOutputStream());
        } catch (final Exception e) {
            LOGGER.warning(Messages.getMessage("exception00"), e);
        }
    } finally {
        Thread.currentThread().setContextClassLoader(oldClassLoader);
    }
}
Also used : SOAPService(org.apache.axis.handlers.soap.SOAPService) AxisFault(org.apache.axis.AxisFault) Message(org.apache.axis.Message) SOAPMessage(javax.xml.soap.SOAPMessage) InputStream(java.io.InputStream) SOAPEnvelope(org.apache.axis.message.SOAPEnvelope) ServerRuntimeException(org.apache.openejb.server.ServerRuntimeException) IOException(java.io.IOException) MimeHeaders(javax.xml.soap.MimeHeaders) MimeHeader(javax.xml.soap.MimeHeader) Iterator(java.util.Iterator) MessageContext(org.apache.axis.MessageContext) ServerRuntimeException(org.apache.openejb.server.ServerRuntimeException) SOAPConstants(org.apache.axis.soap.SOAPConstants) MessageContext(org.apache.axis.MessageContext)

Aggregations

MessageContext (org.apache.axis.MessageContext)10 SOAPEnvelope (org.apache.axis.message.SOAPEnvelope)6 AxisFault (org.apache.axis.AxisFault)4 IOException (java.io.IOException)3 InputStream (java.io.InputStream)3 Iterator (java.util.Iterator)3 Message (org.apache.axis.Message)3 SOAPHeaderElement (org.apache.axis.message.SOAPHeaderElement)3 MimeHeader (javax.xml.soap.MimeHeader)2 MimeHeaders (javax.xml.soap.MimeHeaders)2 SOAPMessage (javax.xml.soap.SOAPMessage)2 AxisEngine (org.apache.axis.AxisEngine)2 ByteArrayInputStream (java.io.ByteArrayInputStream)1 InvocationTargetException (java.lang.reflect.InvocationTargetException)1 Method (java.lang.reflect.Method)1 Enumeration (java.util.Enumeration)1 ServletException (javax.servlet.ServletException)1 TypeMapping (javax.xml.rpc.encoding.TypeMapping)1 SOAPException (javax.xml.soap.SOAPException)1 TransformerConfigurationException (javax.xml.transform.TransformerConfigurationException)1