axisinvocationcontroller.java

来自「开源的axis2框架的源码。用于开发WEBSERVER」· Java 代码 · 共 643 行 · 第 1/2 页

JAVA
643
字号
                        af.getMessage());
            }
            /*
             * Save the exception on the callback.  The client will learn about the error when they try to
             * retrieve the async results via the Response.get().  "Errors that occur during the invocation
             * are reported via an exception when the client attempts to retrieve the results of the operation."
             * -- JAXWS 4.3.3
             */
            pf.onError(af);
        }

        return resp;
    }

    /*
    * (non-Javadoc)
    * @see org.apache.axis2.jaxws.core.controller.InvocationController#prepareRequest(org.apache.axis2.jaxws.core.MessageContext)
    */
    protected void prepareRequest(MessageContext requestMsgCtx) {
        try {
            if (requestMsgCtx == null) {
                //throw an exception
            }

            org.apache.axis2.context.MessageContext axisRequestMsgCtx =
                    requestMsgCtx.getAxisMessageContext();

            // The MessageContext will contain a Message object with the
            // contents that need to be sent.  We need to get those contents
            // in a form that Axis2 can consume them, an AXIOM SOAPEnvelope.
            MessageUtils.putMessageOnMessageContext(
                    requestMsgCtx.getMessage(),  // JAX-WS Message
                    axisRequestMsgCtx // Axis 2 MessageContext
            );

            if (log.isDebugEnabled()) {
                log.debug("Properties: " + axisRequestMsgCtx.getProperties().toString());
            }
        } catch (WebServiceException e) {
            throw ExceptionFactory
                    .makeWebServiceException(Messages.getMessage("prepareRequestFail"));
        } catch (AxisFault e) {
            throw ExceptionFactory
                    .makeWebServiceException(Messages.getMessage("prepareRequestFail"), e);
        }
    }

    /*
    * (non-Javadoc)
    * @see org.apache.axis2.jaxws.core.controller.InvocationController#prepareResponse(org.apache.axis2.jaxws.core.MessageContext)
    */
    protected void prepareResponse(MessageContext responseMsgCtx) {

    }

    private void initOperationClient(OperationClient opClient, MessageContext requestMsgCtx) {
        org.apache.axis2.context.MessageContext axisRequest = requestMsgCtx.getAxisMessageContext();
        setupProperties(requestMsgCtx);//, axisRequest.getOptions());

        Options options = opClient.getOptions();
        if (opClient != null) {
            // Get the target endpoint address and setup the TO endpoint 
            // reference.  This tells us where the request is going.
            String targetUrl = (String)requestMsgCtx.getProperty(
                    BindingProvider.ENDPOINT_ADDRESS_PROPERTY);
            EndpointReference toEPR = new EndpointReference(targetUrl);
            options.setTo(toEPR);

            // Get the SOAP Action (if needed)
            String soapAction = ClientUtils.findSOAPAction(requestMsgCtx);
            options.setAction(soapAction);
            // get the timeout from the request message context options as it may have been
            // set by the user; if it was not set by the user we will just be setting the
            // timeout on the operation client to the default so it will not have a negative
            // effect; this logic is reliant on the fact the JAX-WS MessageContext is delegating
            // to the Axis2 Options object and not storing its own property bag
            long timeout = axisRequest.getOptions().getTimeOutInMilliSeconds();
            options.setTimeOutInMilliSeconds(timeout);

            // Use the OperationClient to send the request and put the contents
            // of the response in the response MessageContext.
            try {
                // Setting the ServiceContext will create the association between 
                // the OperationClient it's MessageContexts and the 
                // AxisService/AxisOperation that they are tied to.
                OperationContext opContext = opClient.getOperationContext();
                ServiceContext svcContext = opContext.getServiceContext();
                axisRequest.setServiceContext(svcContext);

                // Set the Axis2 request MessageContext
                opClient.addMessageContext(axisRequest);
            }
            catch (Exception e) {
                //TODO: Do something
            }
        }
    }

    /**
     * Use the provided ServiceClient instance to create an OperationClient identified by the
     * operation QName provided.
     *
     * @param sc
     * @param operation
     * @return
     */
    private OperationClient createOperationClient(ServiceClient sc, QName operation) {
        if (sc == null) {
            throw ExceptionFactory
                    .makeWebServiceException(Messages.getMessage("ICCreateOpClientErr1"));
        }
        if (operation == null) {
            throw ExceptionFactory
                    .makeWebServiceException(Messages.getMessage("ICCreateOpClientErr2"));
        }

        if (log.isDebugEnabled()) {
            log.debug("Creating OperationClient for operation: " + operation);
        }

        try {
            OperationClient client = sc.createClient(operation);
            return client;
        } catch (AxisFault e) {
            //TODO: NLS and ExceptionFactory
            throw ExceptionFactory.makeWebServiceException(e);
        }
    }

    private void configureAsyncListener(OperationClient client,
                                        org.apache.axis2.context.MessageContext mc) {
        if (log.isDebugEnabled()) {
            log.debug(
                    "Enabling asynchronous message exchange.  An asynchronous listener will be establish.");
        }

        client.getOptions().setUseSeparateListener(true);

        //FIXME: This has to be here so the ThreadContextMigrator can pick it up.
        //This should go away once AXIS2-978 is fixed.
        mc.getOptions().setUseSeparateListener(true);

        // Setup the response callback receiver to receive the async response
        // This logic is based on org.apache.axis2.client.ServiceClient.sendReceiveNonBlocking(...)
        AxisOperation op = client.getOperationContext().getAxisOperation();
        MessageReceiver messageReceiver = op.getMessageReceiver();
        if (messageReceiver == null || !(messageReceiver instanceof CallbackReceiver))
            op.setMessageReceiver(new CallbackReceiver());
    }

    /*
    * TODO: This is a first pass at filtering the properties that are set on the
    * RequestContext.  Right now it's called during the invoke, but needs to be
    * moved over to when the property is set.  This should not be in the path
    * of performance.
    */
    private void setupProperties(MessageContext mc) {//, Options ops) {
        Map<String, Object> properties = mc.getProperties();

        // Enable MTOM
        Message msg = mc.getMessage();
        if (msg.isMTOMEnabled()) {
            mc.setProperty(Configuration.ENABLE_MTOM, "true");
        }

        // Enable session management
        if (mc.isMaintainSession()) {
            mc.getAxisMessageContext().getOptions().setManageSession(true);
        }

        // Check to see if BASIC_AUTH is enabled.  If so, make sure
        // the properties are setup correctly.
        if (properties.containsKey(BindingProvider.USERNAME_PROPERTY) &&
                properties.containsKey(BindingProvider.PASSWORD_PROPERTY)) {

            String userId = (String)properties.get(BindingProvider.USERNAME_PROPERTY);
            if (userId == null || userId == "") {
                throw ExceptionFactory
                        .makeWebServiceException(Messages.getMessage("checkUserName"));
            }

            String password = (String)properties.get(BindingProvider.PASSWORD_PROPERTY);
            if (password == null || password == "") {
                throw ExceptionFactory
                        .makeWebServiceException(Messages.getMessage("checkPassword"));
            }

            URL url = null;
            try {
                url = new URL((String)mc.getProperties()
                        .get(BindingProvider.ENDPOINT_ADDRESS_PROPERTY));
            }
            catch (MalformedURLException e) {
                throw ExceptionFactory.makeWebServiceException(e);
            }

            HttpTransportProperties.Authenticator basicAuthentication =
                    new HttpTransportProperties.Authenticator();
            basicAuthentication.setUsername(userId);
            basicAuthentication.setPassword(password);
            basicAuthentication.setHost(url.getHost());
            basicAuthentication.setPort(url.getPort());
            basicAuthentication.setPreemptiveAuthentication(true);

            mc.setProperty(HTTPConstants.AUTHENTICATE, basicAuthentication);
        } else if ((!properties.containsKey(BindingProvider.USERNAME_PROPERTY) &&
                properties.containsKey(BindingProvider.PASSWORD_PROPERTY)) ||
                (properties.containsKey(BindingProvider.USERNAME_PROPERTY) &&
                        !properties.containsKey(BindingProvider.PASSWORD_PROPERTY))) {
            throw ExceptionFactory
                    .makeWebServiceException(Messages.getMessage("checkUsernameAndPassword"));
        }
    }

    private static QName getOperationNameToUse(MessageContext requestMsgCtx, QName defaultOpName) {
        // We need the qname of the operation being invoked to know which 
        // AxisOperation the OperationClient should be based on.
        // Note that the OperationDesc is only set through use of the Proxy. Dispatch
        // clients do not use operations, so the operationDesc will be null.  In this
        // case an anonymous AxisService with anonymous AxisOperations for the supported
        // MEPs will be created; and it is that anonymous operation name which needs to
        // be specified
        QName operationName = null;
        OperationDescription opDesc = requestMsgCtx.getOperationDescription();
        if (opDesc != null && opDesc.getAxisOperation() != null)
            operationName = opDesc.getName();
        else
            operationName = defaultOpName;
        return operationName;
    }

    /**
     * Executes the OperationClient
     *
     * @param opClient   - Fully configured OperationClient
     * @param block      - Indicates if blocking or non-blocking execute
     * @param msgContext - Axis2 MessageContext
     * @throws AxisFault - All exceptions are returned as AxisFaults
     */
    private void execute(OperationClient opClient,
                         boolean block,
                         org.apache.axis2.context.MessageContext msgContext) throws AxisFault {
        try {
            // Pre-Execute logging and setup
            preExecute(opClient, block, msgContext);

            // Invoke the OperationClient
            opClient.execute(block);
        } catch (Throwable e) {
            // Catch all Throwable (including runtime exceptions and Errors) and
            // throw as AxisFault.
            // Since e could be a Throwable (or Error) instead of an Exception, we'll have to wrap it:
            throw AxisFault.makeFault(ExceptionFactory.makeWebServiceException(e));
        } finally {
            // Post-Execute logging and setup
            postExecute(opClient, block, msgContext);
        }
    }

    /**
     * Called by execute(OperationClient) to perform pre-execute tasks.
     *
     * @param opClient
     * @param block      - Indicates if blocking or non-blocking execute
     * @param msgContext - Axis2 MessageContext
     */
    private void preExecute(OperationClient opClient,
                            boolean block,
                            org.apache.axis2.context.MessageContext msgContext) throws AxisFault {
        // This assumes that we are on the ultimate execution thread

        ThreadContextMigratorUtil
                .performMigrationToContext(Constants.THREAD_CONTEXT_MIGRATOR_LIST_ID, msgContext);

        if (log.isDebugEnabled()) {
            log.debug("Start OperationClient.execute(" + block + ")");
        }
    }

    /**
     * Called by execute(OperationClient) to perform post-execute tasks.  Should be a mirror of
     * preExecute
     *
     * @param opClient
     * @param block      - Indicates if blocking or non-blocking execute
     * @param msgContext - Axis2 MessageContext
     */
    private void postExecute(OperationClient opClient,
                             boolean block,
                             org.apache.axis2.context.MessageContext msgContext) {
        if (log.isDebugEnabled()) {
            log.debug("End OperationClient.execute(" + block + ")");
        }

        /* TODO Currently this check causes SOAPMessageProviderTests to fail.
        if (log.isDebugEnabled()) {
            // Check for exploded OMSourcedElement
            OMElement bodyElement = null;
            if (msgContext.getEnvelope() != null &&
                msgContext.getEnvelope().getBody() != null) {
                bodyElement = msgContext.getEnvelope().getBody().getFirstElement();     
            }
            
            boolean expanded = false;
            if (bodyElement != null && bodyElement instanceof OMSourcedElementImpl) {
                expanded = ((OMSourcedElementImpl)bodyElement).isExpanded();
            }
            // An exploded xml block may indicate a performance problem.  
            // In general an xml block should remain unexploded unless there is an
            // outbound handler that touches the block.
            if (expanded) {
                log.debug("Developer Debug: Found an expanded xml block:" + bodyElement.getNamespace());
            }
        }
        */
        // Cleanup context
        ThreadContextMigratorUtil
                .performContextCleanup(Constants.THREAD_CONTEXT_MIGRATOR_LIST_ID, msgContext);
    }
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?