Search in sources :

Example 1 with Dispatcher

use of org.apache.synapse.endpoints.dispatch.Dispatcher in project wso2-synapse by wso2.

the class DynamicLoadbalanceEndpointFactory method createEndpoint.

protected Endpoint createEndpoint(OMElement epConfig, boolean anonymousEndpoint, Properties properties) {
    OMElement loadbalanceElement = epConfig.getFirstChildWithName(new QName(SynapseConstants.SYNAPSE_NAMESPACE, "dynamicLoadbalance"));
    if (loadbalanceElement != null) {
        DynamicLoadbalanceEndpoint loadbalanceEndpoint = new DynamicLoadbalanceEndpoint();
        // set endpoint name
        OMAttribute name = epConfig.getAttribute(new QName(XMLConfigConstants.NULL_NAMESPACE, "name"));
        if (name != null) {
            loadbalanceEndpoint.setName(name.getAttributeValue());
        }
        // get the session for this endpoint
        OMElement sessionElement = epConfig.getFirstChildWithName(new QName(SynapseConstants.SYNAPSE_NAMESPACE, "session"));
        if (sessionElement != null) {
            OMElement sessionTimeout = sessionElement.getFirstChildWithName(new QName(SynapseConstants.SYNAPSE_NAMESPACE, "sessionTimeout"));
            if (sessionTimeout != null) {
                try {
                    loadbalanceEndpoint.setSessionTimeout(Long.parseLong(sessionTimeout.getText().trim()));
                } catch (NumberFormatException nfe) {
                    handleException("Invalid session timeout value : " + sessionTimeout.getText());
                }
            }
            String type = sessionElement.getAttributeValue(new QName("type"));
            if (type.equalsIgnoreCase("soap")) {
                Dispatcher soapDispatcher = new SoapSessionDispatcher();
                loadbalanceEndpoint.setDispatcher(soapDispatcher);
            } else if (type.equalsIgnoreCase("http")) {
                Dispatcher httpDispatcher = new HttpSessionDispatcher();
                loadbalanceEndpoint.setDispatcher(httpDispatcher);
            }
            loadbalanceEndpoint.setSessionAffinity(true);
        }
        // set if failover is turned off
        String failover = loadbalanceElement.getAttributeValue(new QName("failover"));
        if (failover != null && failover.equalsIgnoreCase("false")) {
            loadbalanceEndpoint.setFailover(false);
        } else {
            loadbalanceEndpoint.setFailover(true);
        }
        OMElement eventHandler = loadbalanceElement.getFirstChildWithName(new QName(SynapseConstants.SYNAPSE_NAMESPACE, "membershipHandler"));
        if (eventHandler != null) {
            String clazz = eventHandler.getAttributeValue(new QName(XMLConfigConstants.NULL_NAMESPACE, "class")).trim();
            try {
                LoadBalanceMembershipHandler lbMembershipHandler = (LoadBalanceMembershipHandler) Class.forName(clazz).newInstance();
                Properties lbProperties = new Properties();
                for (Iterator props = eventHandler.getChildrenWithName(new QName(SynapseConstants.SYNAPSE_NAMESPACE, "property")); props.hasNext(); ) {
                    OMElement prop = (OMElement) props.next();
                    String propName = prop.getAttributeValue(new QName(XMLConfigConstants.NULL_NAMESPACE, "name")).trim();
                    String propValue = prop.getAttributeValue(new QName(XMLConfigConstants.NULL_NAMESPACE, "value")).trim();
                    lbProperties.put(propName, propValue);
                }
                // Set load balance algorithm
                LoadbalanceAlgorithm algorithm = LoadbalanceAlgorithmFactory.createLoadbalanceAlgorithm(loadbalanceElement, null);
                lbMembershipHandler.init(lbProperties, algorithm);
                loadbalanceEndpoint.setLoadBalanceMembershipHandler(lbMembershipHandler);
            } catch (Exception e) {
                String msg = "Could not instantiate " + "LoadBalanceMembershipHandler implementation " + clazz;
                log.error(msg, e);
                throw new SynapseException(msg, e);
            }
        }
        processProperties(loadbalanceEndpoint, epConfig);
        return loadbalanceEndpoint;
    }
    return null;
}
Also used : SynapseException(org.apache.synapse.SynapseException) QName(javax.xml.namespace.QName) OMElement(org.apache.axiom.om.OMElement) SoapSessionDispatcher(org.apache.synapse.endpoints.dispatch.SoapSessionDispatcher) Dispatcher(org.apache.synapse.endpoints.dispatch.Dispatcher) HttpSessionDispatcher(org.apache.synapse.endpoints.dispatch.HttpSessionDispatcher) Properties(java.util.Properties) DynamicLoadbalanceEndpoint(org.apache.synapse.endpoints.DynamicLoadbalanceEndpoint) SynapseException(org.apache.synapse.SynapseException) LoadBalanceMembershipHandler(org.apache.synapse.core.LoadBalanceMembershipHandler) Iterator(java.util.Iterator) LoadbalanceAlgorithm(org.apache.synapse.endpoints.algorithms.LoadbalanceAlgorithm) OMAttribute(org.apache.axiom.om.OMAttribute) HttpSessionDispatcher(org.apache.synapse.endpoints.dispatch.HttpSessionDispatcher) SoapSessionDispatcher(org.apache.synapse.endpoints.dispatch.SoapSessionDispatcher)

Example 2 with Dispatcher

use of org.apache.synapse.endpoints.dispatch.Dispatcher in project wso2-synapse by wso2.

the class SynapseCallbackReceiver method handleMessage.

/**
 * Handle the response or error (during a failed send) message received for an outgoing request
 *
 * @param messageID        Request message ID
 * @param response         the Axis2 MessageContext that has been received and has to be handled
 * @param synapseOutMsgCtx the corresponding (outgoing) Synapse MessageContext for the above
 *                         Axis2 MC, that holds Synapse specific information such as the error
 *                         handler stack and local properties etc.
 * @throws AxisFault       if the message cannot be processed
 */
private void handleMessage(String messageID, MessageContext response, org.apache.synapse.MessageContext synapseOutMsgCtx, AsyncCallback callback) throws AxisFault {
    // apply the tenant information to the out message context
    TenantInfoConfigurator configurator = synapseOutMsgCtx.getEnvironment().getTenantInfoConfigurator();
    if (configurator != null) {
        configurator.applyTenantInfo(synapseOutMsgCtx);
    }
    Boolean isConcurrencyThrottleEnabled = (Boolean) synapseOutMsgCtx.getProperty(SynapseConstants.SYNAPSE_CONCURRENCY_THROTTLE);
    if (isConcurrencyThrottleEnabled != null && isConcurrencyThrottleEnabled) {
        ConcurrentAccessController concurrentAccessController = (ConcurrentAccessController) synapseOutMsgCtx.getProperty(SynapseConstants.SYNAPSE_CONCURRENT_ACCESS_CONTROLLER);
        int available = concurrentAccessController.incrementAndGet();
        int concurrentLimit = concurrentAccessController.getLimit();
        if (log.isDebugEnabled()) {
            log.debug("Concurrency Throttle : Connection returned" + " :: " + available + " of available of " + concurrentLimit + " connections");
        }
        ConcurrentAccessReplicator concurrentAccessReplicator = (ConcurrentAccessReplicator) synapseOutMsgCtx.getProperty(SynapseConstants.SYNAPSE_CONCURRENT_ACCESS_REPLICATOR);
        String throttleKey = (String) synapseOutMsgCtx.getProperty(SynapseConstants.SYNAPSE_CONCURRENCY_THROTTLE_KEY);
        if (concurrentAccessReplicator != null) {
            concurrentAccessReplicator.replicate(throttleKey, true);
        }
    }
    Object o = response.getProperty(SynapseConstants.SENDING_FAULT);
    if (o != null && Boolean.TRUE.equals(o)) {
        // This path hits with a fault. Sequence mediator threads should not remove faultSequence.
        // SynapseCallbackReceiver thread should handle the faultStack.
        Pipe pipe = (Pipe) ((Axis2MessageContext) synapseOutMsgCtx).getAxis2MessageContext().getProperty(PassThroughConstants.PASS_THROUGH_PIPE);
        if (pipe != null && pipe.isSerializationComplete()) {
            NHttpServerConnection conn = (NHttpServerConnection) ((Axis2MessageContext) synapseOutMsgCtx).getAxis2MessageContext().getProperty("pass-through.Source-Connection");
            SourceConfiguration sourceConfiguration = (SourceConfiguration) ((Axis2MessageContext) synapseOutMsgCtx).getAxis2MessageContext().getProperty("PASS_THROUGH_SOURCE_CONFIGURATION");
            Pipe newPipe = new Pipe(conn, sourceConfiguration.getBufferFactory().getBuffer(), "source", sourceConfiguration);
            ((Axis2MessageContext) synapseOutMsgCtx).getAxis2MessageContext().setProperty(PassThroughConstants.PASS_THROUGH_PIPE, newPipe);
        }
        // there is a sending fault. propagate the fault to fault handlers.
        Stack faultStack = synapseOutMsgCtx.getFaultStack();
        if (faultStack != null && !faultStack.isEmpty()) {
            // fault envelope
            try {
                synapseOutMsgCtx.getEnvelope().build();
            } catch (Exception x) {
                synapseOutMsgCtx.setEnvelope(response.getEnvelope());
            }
            Exception e = (Exception) response.getProperty(SynapseConstants.ERROR_EXCEPTION);
            synapseOutMsgCtx.setProperty(SynapseConstants.SENDING_FAULT, Boolean.TRUE);
            synapseOutMsgCtx.setProperty(SynapseConstants.ERROR_CODE, response.getProperty(SynapseConstants.ERROR_CODE));
            synapseOutMsgCtx.setProperty(SynapseConstants.ERROR_MESSAGE, response.getProperty(SynapseConstants.ERROR_MESSAGE));
            synapseOutMsgCtx.setProperty(SynapseConstants.ERROR_DETAIL, response.getProperty(SynapseConstants.ERROR_DETAIL));
            synapseOutMsgCtx.setProperty(SynapseConstants.ERROR_EXCEPTION, e);
            if (synapseOutMsgCtx.getEnvironment().isContinuationEnabled()) {
                synapseOutMsgCtx.setContinuationEnabled(true);
            }
            if (log.isDebugEnabled()) {
                log.debug("[Failed Request Message ID : " + messageID + "]" + " [New to be Retried Request Message ID : " + synapseOutMsgCtx.getMessageID() + "]");
            }
            int errorCode = (Integer) response.getProperty(SynapseConstants.ERROR_CODE);
            // If a timeout has occured and the timeout action of the callback is to discard the message
            if (errorCode == SynapseConstants.NHTTP_CONNECTION_TIMEOUT && callback.getTimeOutAction() == SynapseConstants.DISCARD) {
                // Do not execute any fault sequences. Discard message
                if (log.isWarnEnabled()) {
                    log.warn("Synapse timed out for the request with Message ID : " + messageID + ". Ignoring fault handlers since the timeout action is DISCARD");
                }
                faultStack.removeAllElements();
            } else {
                ((FaultHandler) faultStack.pop()).handleFault(synapseOutMsgCtx, null);
            }
        }
    } else {
        // there can always be only one instance of an Endpoint in the faultStack of a message
        // if the send was successful, so remove it before we proceed any further
        Stack faultStack = synapseOutMsgCtx.getFaultStack();
        Endpoint successfulEndpoint = null;
        if (faultStack != null && !faultStack.isEmpty() && faultStack.peek() instanceof Endpoint) {
            successfulEndpoint = (Endpoint) faultStack.pop();
        }
        if (log.isDebugEnabled()) {
            log.debug("Synapse received an asynchronous response message");
            log.debug("Received To: " + (response.getTo() != null ? response.getTo().getAddress() : "null"));
            log.debug("SOAPAction: " + (response.getSoapAction() != null ? response.getSoapAction() : "null"));
            log.debug("WSA-Action: " + (response.getWSAAction() != null ? response.getWSAAction() : "null"));
            String[] cids = null;
            try {
                cids = response.getAttachmentMap().getAllContentIDs();
            } catch (Exception ex) {
                // partially read stream could lead to corrupted attachment map and hence this exception
                // corrupted attachment map leads to inconsistent runtime exceptions and behavior
                // discard the attachment map for the fault handler invocation
                // ensure the successful completion for fault handler flow
                response.setAttachmentMap(null);
                log.error("Synapse encountered an exception when reading attachments from bytes stream. " + "Hence Attachments map is dropped from the message context.", ex);
            }
            if (cids != null && cids.length > 0) {
                for (String cid : cids) {
                    log.debug("Attachment : " + cid);
                }
            }
            log.debug("Body : \n" + response.getEnvelope());
        }
        MessageContext axisOutMsgCtx = ((Axis2MessageContext) synapseOutMsgCtx).getAxis2MessageContext();
        // Processes 'Accept-Encoding'
        ResponseAcceptEncodingProcessor.process(response, axisOutMsgCtx);
        response.setServiceContext(null);
        response.setOperationContext(axisOutMsgCtx.getOperationContext());
        response.setAxisMessage(axisOutMsgCtx.getAxisOperation().getMessage(WSDLConstants.MESSAGE_LABEL_OUT_VALUE));
        // set properties on response
        response.setServerSide(true);
        response.setProperty(SynapseConstants.ISRESPONSE_PROPERTY, Boolean.TRUE);
        response.setProperty(MessageContext.TRANSPORT_OUT, axisOutMsgCtx.getProperty(MessageContext.TRANSPORT_OUT));
        response.setProperty(org.apache.axis2.Constants.OUT_TRANSPORT_INFO, axisOutMsgCtx.getProperty(org.apache.axis2.Constants.OUT_TRANSPORT_INFO));
        response.setTransportIn(axisOutMsgCtx.getTransportIn());
        response.setTransportOut(axisOutMsgCtx.getTransportOut());
        // response.setDoingREST(axisOutMsgCtx.isDoingREST()); This information already present, hence removing
        if (axisOutMsgCtx.isDoingMTOM() && (axisOutMsgCtx.getProperty(org.apache.axis2.Constants.Configuration.ENABLE_MTOM) == null || Boolean.getBoolean((String) axisOutMsgCtx.getProperty(org.apache.axis2.Constants.Configuration.ENABLE_MTOM)) == true)) {
            response.setDoingMTOM(true);
            response.setProperty(org.apache.axis2.Constants.Configuration.ENABLE_MTOM, org.apache.axis2.Constants.VALUE_TRUE);
        }
        if (axisOutMsgCtx.isDoingSwA()) {
            response.setDoingSwA(true);
            response.setProperty(org.apache.axis2.Constants.Configuration.ENABLE_SWA, org.apache.axis2.Constants.VALUE_TRUE);
        }
        // property state to original state.
        if (axisOutMsgCtx.getProperty(AddressingConstants.DISABLE_ADDRESSING_FOR_OUT_MESSAGES) != null) {
            response.setProperty(AddressingConstants.DISABLE_ADDRESSING_FOR_OUT_MESSAGES, axisOutMsgCtx.getProperty(AddressingConstants.DISABLE_ADDRESSING_FOR_OUT_MESSAGES));
        } else {
            response.removeProperty(AddressingConstants.DISABLE_ADDRESSING_FOR_OUT_MESSAGES);
        }
        Object messageType = axisOutMsgCtx.getProperty(org.apache.axis2.Constants.Configuration.MESSAGE_TYPE);
        if (!HTTPConstants.MEDIA_TYPE_X_WWW_FORM.equals(messageType)) {
            // copy the message type property that's used by the out message to the
            // response message
            response.setProperty(org.apache.axis2.Constants.Configuration.MESSAGE_TYPE, messageType);
        }
        if (axisOutMsgCtx.getMessageID() != null) {
            response.setRelationships(new RelatesTo[] { new RelatesTo(axisOutMsgCtx.getMessageID()) });
        }
        response.setReplyTo(axisOutMsgCtx.getReplyTo());
        response.setFaultTo(axisOutMsgCtx.getFaultTo());
        if (axisOutMsgCtx.isPropertyTrue(NhttpConstants.IGNORE_SC_ACCEPTED)) {
            response.setProperty(NhttpConstants.FORCE_SC_ACCEPTED, Constants.VALUE_TRUE);
        }
        // axis2 client options still contains properties such as policy files used in
        // outgoing request. Need to remove those.
        removeUnwantedClientOptions(response);
        // create the synapse message context for the response
        Axis2MessageContext synapseInMessageContext = new Axis2MessageContext(response, synapseOutMsgCtx.getConfiguration(), synapseOutMsgCtx.getEnvironment());
        synapseInMessageContext.setResponse(true);
        Object obj = synapseOutMsgCtx.getProperty(SynapseConstants.FORCE_ERROR_PROPERTY);
        String errorOnSOAPFault = (String) obj;
        if (Constants.VALUE_TRUE.equals(errorOnSOAPFault) && successfulEndpoint != null) {
            if (log.isDebugEnabled()) {
                log.debug("FORCE_ERROR_ON_SOAP_FAULT is true, checking for SOAPFault");
            }
            try {
                RelayUtils.buildMessage(((Axis2MessageContext) synapseInMessageContext).getAxis2MessageContext(), true);
            } catch (Exception e) {
            // handleException("Error while building message", e, synapseInMessageContext);
            }
            if ((synapseInMessageContext.getEnvelope() != null) && synapseInMessageContext.getEnvelope().hasFault()) {
                if (log.isDebugEnabled()) {
                    log.debug("SOAPFault found in response message, forcing endpoint " + successfulEndpoint.getName() + " to fail");
                }
                // setup new pipe configuration..if failure happens (this will be setup as the source writer and during the TargetContext
                // clean up operation the writer will be reset and pull to the buffer
                MessageContext axis2OUTMC = ((Axis2MessageContext) synapseOutMsgCtx).getAxis2MessageContext();
                NHttpServerConnection conn = (NHttpServerConnection) axis2OUTMC.getProperty("pass-through.Source-Connection");
                if (conn != null) {
                    SourceConfiguration sourceConfiguration = (SourceConfiguration) axis2OUTMC.getProperty("PASS_THROUGH_SOURCE_CONFIGURATION");
                    Pipe pipe = new Pipe(conn, sourceConfiguration.getBufferFactory().getBuffer(), "source", sourceConfiguration);
                    axis2OUTMC.setProperty(PassThroughConstants.PASS_THROUGH_PIPE, pipe);
                }
                synapseOutMsgCtx.setProperty(SynapseConstants.SENDING_FAULT, Boolean.TRUE);
                synapseOutMsgCtx.setProperty(SynapseConstants.ERROR_CODE, SynapseConstants.ENDPOINT_CUSTOM_ERROR);
                boolean failOver = false;
                if (successfulEndpoint instanceof AbstractEndpoint) {
                    Endpoint endpoint = ((AbstractEndpoint) successfulEndpoint).getParentEndpoint();
                    if (endpoint != null && (endpoint instanceof FailoverEndpoint)) {
                        failOver = true;
                    }
                }
                for (Object key : synapseOutMsgCtx.getPropertyKeySet()) {
                    synapseInMessageContext.setProperty((String) key, synapseOutMsgCtx.getProperty((String) key));
                }
                if (failOver) {
                    // we may required to handle same message for failover cases only other than that
                    // should treat based on the incoming message
                    ((FaultHandler) successfulEndpoint).handleFault(synapseOutMsgCtx, null);
                } else {
                    faultStack = synapseOutMsgCtx.getFaultStack();
                    if (faultStack != null) {
                        synapseInMessageContext.getFaultStack().addAll(faultStack);
                        ((FaultHandler) successfulEndpoint).handleFault(synapseInMessageContext, null);
                    }
                }
                return;
            } else {
                successfulEndpoint.onSuccess();
            }
        } else if (successfulEndpoint != null) {
            successfulEndpoint.onSuccess();
        }
        synapseInMessageContext.setTo(new EndpointReference(AddressingConstants.Final.WSA_ANONYMOUS_URL));
        synapseInMessageContext.setTracingState(synapseOutMsgCtx.getTracingState());
        synapseInMessageContext.setMessageFlowTracingState(synapseOutMsgCtx.getMessageFlowTracingState());
        for (Object key : synapseOutMsgCtx.getPropertyKeySet()) {
            synapseInMessageContext.setProperty((String) key, synapseOutMsgCtx.getProperty((String) key));
        }
        // Copy SequenceCallStack from original MC to the new MC
        Boolean isContinuationCall = (Boolean) synapseOutMsgCtx.getProperty(SynapseConstants.CONTINUATION_CALL);
        if (isContinuationCall != null && isContinuationCall) {
            // Set the message direction
            if (!synapseOutMsgCtx.isResponse()) {
                synapseInMessageContext.setResponse(false);
            }
            Stack<ContinuationState> seqContinuationStates = synapseOutMsgCtx.getContinuationStateStack();
            for (int i = 0; i < seqContinuationStates.size(); i++) {
                synapseInMessageContext.pushContinuationState(seqContinuationStates.get(i));
            }
        }
        // If this response is related to session affinity endpoints -Server initiated session
        Dispatcher dispatcher = (Dispatcher) synapseOutMsgCtx.getProperty(SynapseConstants.PROP_SAL_ENDPOINT_CURRENT_DISPATCHER);
        if (dispatcher != null && dispatcher.isServerInitiatedSession()) {
            dispatcher.updateSession(synapseInMessageContext);
        }
        // send the response message through the synapse mediation flow
        try {
            synapseOutMsgCtx.getEnvironment().injectMessage(synapseInMessageContext);
        } catch (Exception syne) {
            // introduced to handle runtime exceptions which are occurred inside Synapse handlers
            // partially read stream could lead to corrupted attachment map and hence this exception
            // corrupted attachment map leads to inconsistent runtime exceptions and behavior
            // discard the attachment map for the fault handler invocation
            // ensure the successful completion for fault handler flow
            // even we drop attachment map for both cases messages which have attachment /
            // messages which do not have attachments it would still not be any impact.
            // However setting attachment map to null for messages which do not have attachments is not required.
            // introduced due to the fact conflicts between Axiom exceptions for attachment/ non attachments cases
            // and performance impact that could cause of regular expression matching of exceptional stack traces.
            Axis2MessageContext axis2smc = (Axis2MessageContext) synapseInMessageContext;
            org.apache.axis2.context.MessageContext axis2MessageCtx = axis2smc.getAxis2MessageContext();
            // Set correct status code
            axis2MessageCtx.setProperty(PassThroughConstants.HTTP_SC, HttpStatus.SC_INTERNAL_SERVER_ERROR);
            axis2MessageCtx.setAttachmentMap(null);
            Stack stack = synapseInMessageContext.getFaultStack();
            if (stack != null && stack.isEmpty()) {
                registerFaultHandler(synapseInMessageContext);
            }
            if (stack != null && !stack.isEmpty()) {
                ((FaultHandler) stack.pop()).handleFault(synapseInMessageContext, syne);
            } else {
                log.error("Synapse encountered an exception, " + "No error handlers found - [Message Dropped]\n" + syne.getMessage());
            }
        }
    }
}
Also used : Dispatcher(org.apache.synapse.endpoints.dispatch.Dispatcher) FailoverEndpoint(org.apache.synapse.endpoints.FailoverEndpoint) RelatesTo(org.apache.axis2.addressing.RelatesTo) NHttpServerConnection(org.apache.http.nio.NHttpServerConnection) Endpoint(org.apache.synapse.endpoints.Endpoint) AbstractEndpoint(org.apache.synapse.endpoints.AbstractEndpoint) FailoverEndpoint(org.apache.synapse.endpoints.FailoverEndpoint) ConcurrentAccessController(org.apache.synapse.commons.throttle.core.ConcurrentAccessController) MessageContext(org.apache.axis2.context.MessageContext) FaultHandler(org.apache.synapse.FaultHandler) MediatorFaultHandler(org.apache.synapse.mediators.MediatorFaultHandler) AbstractEndpoint(org.apache.synapse.endpoints.AbstractEndpoint) Pipe(org.apache.synapse.transport.passthru.Pipe) Endpoint(org.apache.synapse.endpoints.Endpoint) AbstractEndpoint(org.apache.synapse.endpoints.AbstractEndpoint) FailoverEndpoint(org.apache.synapse.endpoints.FailoverEndpoint) ConcurrentAccessReplicator(org.apache.synapse.commons.throttle.core.ConcurrentAccessReplicator) Stack(java.util.Stack) EndpointReference(org.apache.axis2.addressing.EndpointReference) ContinuationState(org.apache.synapse.ContinuationState) TenantInfoConfigurator(org.apache.synapse.carbonext.TenantInfoConfigurator) SourceConfiguration(org.apache.synapse.transport.passthru.config.SourceConfiguration)

Example 3 with Dispatcher

use of org.apache.synapse.endpoints.dispatch.Dispatcher in project wso2-synapse by wso2.

the class SALoadbalanceEndpointFactory method createEndpoint.

protected Endpoint createEndpoint(OMElement epConfig, boolean anonymousEndpoint, Properties properties) {
    // create the endpoint, manager and the algorithms
    SALoadbalanceEndpoint loadbalanceEndpoint = new SALoadbalanceEndpoint();
    // get the session for this endpoint
    OMElement sessionElement = epConfig.getFirstChildWithName(new QName(SynapseConstants.SYNAPSE_NAMESPACE, "session"));
    if (sessionElement != null) {
        OMElement sessionTimeout = sessionElement.getFirstChildWithName(new QName(SynapseConstants.SYNAPSE_NAMESPACE, "sessionTimeout"));
        if (sessionTimeout != null) {
            try {
                loadbalanceEndpoint.setSessionTimeout(Long.parseLong(sessionTimeout.getText().trim()));
            } catch (NumberFormatException nfe) {
                handleException("Invalid session timeout value : " + sessionTimeout.getText());
            }
        }
        String type = sessionElement.getAttributeValue(new QName("type"));
        if (type.equalsIgnoreCase("soap")) {
            Dispatcher soapDispatcher = new SoapSessionDispatcher();
            loadbalanceEndpoint.setDispatcher(soapDispatcher);
        } else if (type.equalsIgnoreCase("http")) {
            Dispatcher httpDispatcher = new HttpSessionDispatcher();
            loadbalanceEndpoint.setDispatcher(httpDispatcher);
        } else if (type.equalsIgnoreCase("simpleClientSession")) {
            Dispatcher csDispatcher = new SimpleClientSessionDispatcher();
            loadbalanceEndpoint.setDispatcher(csDispatcher);
        }
    } else {
        handleException("Session affinity endpoints should " + "have a session element in the configuration.");
    }
    // set endpoint name
    OMAttribute name = epConfig.getAttribute(new QName(org.apache.synapse.config.xml.XMLConfigConstants.NULL_NAMESPACE, "name"));
    if (name != null) {
        loadbalanceEndpoint.setName(name.getAttributeValue());
    }
    OMElement loadbalanceElement;
    loadbalanceElement = epConfig.getFirstChildWithName(new QName(SynapseConstants.SYNAPSE_NAMESPACE, "loadbalance"));
    if (loadbalanceElement != null) {
        // set endpoints
        List<Endpoint> endpoints = getEndpoints(loadbalanceElement, loadbalanceEndpoint, properties);
        loadbalanceEndpoint.setChildren(endpoints);
        // set load balance algorithm
        LoadbalanceAlgorithm algorithm = LoadbalanceAlgorithmFactory.createLoadbalanceAlgorithm(loadbalanceElement, endpoints);
        loadbalanceEndpoint.setAlgorithm(algorithm);
        // set buildMessage attribute
        String buildMessageAtt = loadbalanceElement.getAttributeValue(new QName(XMLConfigConstants.BUILD_MESSAGE));
        if (buildMessageAtt != null) {
            loadbalanceEndpoint.setBuildMessageAttAvailable(true);
            if (JavaUtils.isTrueExplicitly(buildMessageAtt)) {
                loadbalanceEndpoint.setBuildMessageAtt(true);
            }
        }
        // process the parameters
        processProperties(loadbalanceEndpoint, epConfig);
        return loadbalanceEndpoint;
    }
    return null;
}
Also used : QName(javax.xml.namespace.QName) OMElement(org.apache.axiom.om.OMElement) SoapSessionDispatcher(org.apache.synapse.endpoints.dispatch.SoapSessionDispatcher) Dispatcher(org.apache.synapse.endpoints.dispatch.Dispatcher) HttpSessionDispatcher(org.apache.synapse.endpoints.dispatch.HttpSessionDispatcher) SimpleClientSessionDispatcher(org.apache.synapse.endpoints.dispatch.SimpleClientSessionDispatcher) SimpleClientSessionDispatcher(org.apache.synapse.endpoints.dispatch.SimpleClientSessionDispatcher) SALoadbalanceEndpoint(org.apache.synapse.endpoints.SALoadbalanceEndpoint) Endpoint(org.apache.synapse.endpoints.Endpoint) SALoadbalanceEndpoint(org.apache.synapse.endpoints.SALoadbalanceEndpoint) LoadbalanceAlgorithm(org.apache.synapse.endpoints.algorithms.LoadbalanceAlgorithm) HttpSessionDispatcher(org.apache.synapse.endpoints.dispatch.HttpSessionDispatcher) OMAttribute(org.apache.axiom.om.OMAttribute) SoapSessionDispatcher(org.apache.synapse.endpoints.dispatch.SoapSessionDispatcher)

Example 4 with Dispatcher

use of org.apache.synapse.endpoints.dispatch.Dispatcher in project wso2-synapse by wso2.

the class ServiceDynamicLoadbalanceEndpointSerializer method serializeEndpoint.

protected OMElement serializeEndpoint(Endpoint endpoint) {
    if (!(endpoint instanceof ServiceDynamicLoadbalanceEndpoint)) {
        handleException("Invalid endpoint type.");
    }
    fac = OMAbstractFactory.getOMFactory();
    OMElement endpointElement = fac.createOMElement("endpoint", SynapseConstants.SYNAPSE_OMNAMESPACE);
    ServiceDynamicLoadbalanceEndpoint dynamicLoadbalanceEndpoint = (ServiceDynamicLoadbalanceEndpoint) endpoint;
    // serialize the parameters
    serializeProperties(dynamicLoadbalanceEndpoint, endpointElement);
    serializeCommonAttributes(endpoint, endpointElement);
    Dispatcher dispatcher = dynamicLoadbalanceEndpoint.getDispatcher();
    if (dispatcher != null) {
        OMElement sessionElement = fac.createOMElement("session", SynapseConstants.SYNAPSE_OMNAMESPACE);
        if (dispatcher instanceof SoapSessionDispatcher) {
            sessionElement.addAttribute("type", "soap", null);
        } else if (dispatcher instanceof HttpSessionDispatcher) {
            sessionElement.addAttribute("type", "http", null);
        } else if (dispatcher instanceof SimpleClientSessionDispatcher) {
            sessionElement.addAttribute("type", "simpleClientSession", null);
        } else {
            handleException("invalid session dispatcher : " + dispatcher.getClass().getName());
        }
        long sessionTimeout = dynamicLoadbalanceEndpoint.getSessionTimeout();
        if (sessionTimeout != -1) {
            OMElement sessionTimeoutElement = fac.createOMElement("sessionTimeout", SynapseConstants.SYNAPSE_OMNAMESPACE);
            sessionTimeoutElement.setText(String.valueOf(sessionTimeout));
            sessionElement.addChild(sessionTimeoutElement);
        }
        endpointElement.addChild(sessionElement);
    }
    OMElement dynamicLoadbalanceElement = fac.createOMElement("serviceDynamicLoadbalance", SynapseConstants.SYNAPSE_OMNAMESPACE);
    endpointElement.addChild(dynamicLoadbalanceElement);
    // Load balance algorithm
    dynamicLoadbalanceElement.addAttribute(XMLConfigConstants.LOADBALANCE_ALGORITHM, dynamicLoadbalanceEndpoint.getAlgorithm().getClass().getName(), null);
    // Host-domain map
    OMElement servicesEle = fac.createOMElement("services", SynapseConstants.SYNAPSE_OMNAMESPACE);
    dynamicLoadbalanceElement.addChild(servicesEle);
    Map<String, String> hostDomainMap = dynamicLoadbalanceEndpoint.getHostDomainMap();
    for (Map.Entry<String, String> entry : hostDomainMap.entrySet()) {
        OMElement serviceEle = fac.createOMElement("service", SynapseConstants.SYNAPSE_OMNAMESPACE);
        servicesEle.addChild(serviceEle);
        OMElement hostEle = fac.createOMElement("host", SynapseConstants.SYNAPSE_OMNAMESPACE);
        hostEle.setText(entry.getKey());
        serviceEle.addChild(hostEle);
        OMElement domainEle = fac.createOMElement("domain", SynapseConstants.SYNAPSE_OMNAMESPACE);
        domainEle.setText(entry.getValue());
        serviceEle.addChild(domainEle);
    }
    return endpointElement;
}
Also used : ServiceDynamicLoadbalanceEndpoint(org.apache.synapse.endpoints.ServiceDynamicLoadbalanceEndpoint) OMElement(org.apache.axiom.om.OMElement) HttpSessionDispatcher(org.apache.synapse.endpoints.dispatch.HttpSessionDispatcher) SoapSessionDispatcher(org.apache.synapse.endpoints.dispatch.SoapSessionDispatcher) Dispatcher(org.apache.synapse.endpoints.dispatch.Dispatcher) SimpleClientSessionDispatcher(org.apache.synapse.endpoints.dispatch.SimpleClientSessionDispatcher) SimpleClientSessionDispatcher(org.apache.synapse.endpoints.dispatch.SimpleClientSessionDispatcher) HttpSessionDispatcher(org.apache.synapse.endpoints.dispatch.HttpSessionDispatcher) Map(java.util.Map) SoapSessionDispatcher(org.apache.synapse.endpoints.dispatch.SoapSessionDispatcher)

Example 5 with Dispatcher

use of org.apache.synapse.endpoints.dispatch.Dispatcher in project wso2-synapse by wso2.

the class DynamicLoadbalanceEndpointSerializer method serializeEndpoint.

protected OMElement serializeEndpoint(Endpoint endpoint) {
    if (!(endpoint instanceof DynamicLoadbalanceEndpoint)) {
        handleException("Invalid endpoint type.");
    }
    fac = OMAbstractFactory.getOMFactory();
    OMElement endpointElement = fac.createOMElement("endpoint", SynapseConstants.SYNAPSE_OMNAMESPACE);
    DynamicLoadbalanceEndpoint dynamicLoadbalanceEndpoint = (DynamicLoadbalanceEndpoint) endpoint;
    // serialize the parameters
    serializeProperties(dynamicLoadbalanceEndpoint, endpointElement);
    serializeCommonAttributes(endpoint, endpointElement);
    Dispatcher dispatcher = dynamicLoadbalanceEndpoint.getDispatcher();
    if (dispatcher != null) {
        OMElement sessionElement = fac.createOMElement("session", SynapseConstants.SYNAPSE_OMNAMESPACE);
        if (dispatcher instanceof SoapSessionDispatcher) {
            sessionElement.addAttribute("type", "soap", null);
        } else if (dispatcher instanceof HttpSessionDispatcher) {
            sessionElement.addAttribute("type", "http", null);
        } else if (dispatcher instanceof SimpleClientSessionDispatcher) {
            sessionElement.addAttribute("type", "simpleClientSession", null);
        } else {
            handleException("invalid session dispatcher : " + dispatcher.getClass().getName());
        }
        long sessionTimeout = dynamicLoadbalanceEndpoint.getSessionTimeout();
        if (sessionTimeout != -1) {
            OMElement sessionTimeoutElement = fac.createOMElement("sessionTimeout", SynapseConstants.SYNAPSE_OMNAMESPACE);
            sessionTimeoutElement.setText(String.valueOf(sessionTimeout));
            sessionElement.addChild(sessionTimeoutElement);
        }
        endpointElement.addChild(sessionElement);
    }
    OMElement dynamicLoadbalanceElement = fac.createOMElement("dynamicLoadbalance", SynapseConstants.SYNAPSE_OMNAMESPACE);
    endpointElement.addChild(dynamicLoadbalanceElement);
    // set if failover is turned off in the endpoint
    if (!dynamicLoadbalanceEndpoint.isFailover()) {
        dynamicLoadbalanceElement.addAttribute("failover", "false", null);
    }
    LoadBalanceMembershipHandler loadBalanceMembershipHandler = dynamicLoadbalanceEndpoint.getLbMembershipHandler();
    dynamicLoadbalanceElement.addAttribute(XMLConfigConstants.LOADBALANCE_ALGORITHM, loadBalanceMembershipHandler.getLoadbalanceAlgorithm().getClass().getName(), null);
    OMElement membershipHandlerElement = fac.createOMElement("membershipHandler", SynapseConstants.SYNAPSE_OMNAMESPACE);
    dynamicLoadbalanceElement.addChild(membershipHandlerElement);
    membershipHandlerElement.addAttribute("class", loadBalanceMembershipHandler.getClass().getName(), null);
    Properties membershipHandlerProperties = loadBalanceMembershipHandler.getProperties();
    OMElement propertyElement;
    for (Object property : membershipHandlerProperties.keySet()) {
        propertyElement = fac.createOMElement("property", SynapseConstants.SYNAPSE_OMNAMESPACE);
        membershipHandlerElement.addChild(propertyElement);
        propertyElement.addAttribute("name", property.toString(), null);
        propertyElement.addAttribute("value", membershipHandlerProperties.getProperty((String) property), null);
    }
    return endpointElement;
}
Also used : LoadBalanceMembershipHandler(org.apache.synapse.core.LoadBalanceMembershipHandler) OMElement(org.apache.axiom.om.OMElement) HttpSessionDispatcher(org.apache.synapse.endpoints.dispatch.HttpSessionDispatcher) SoapSessionDispatcher(org.apache.synapse.endpoints.dispatch.SoapSessionDispatcher) Dispatcher(org.apache.synapse.endpoints.dispatch.Dispatcher) SimpleClientSessionDispatcher(org.apache.synapse.endpoints.dispatch.SimpleClientSessionDispatcher) SimpleClientSessionDispatcher(org.apache.synapse.endpoints.dispatch.SimpleClientSessionDispatcher) Properties(java.util.Properties) DynamicLoadbalanceEndpoint(org.apache.synapse.endpoints.DynamicLoadbalanceEndpoint) HttpSessionDispatcher(org.apache.synapse.endpoints.dispatch.HttpSessionDispatcher) SoapSessionDispatcher(org.apache.synapse.endpoints.dispatch.SoapSessionDispatcher)

Aggregations

Dispatcher (org.apache.synapse.endpoints.dispatch.Dispatcher)8 OMElement (org.apache.axiom.om.OMElement)6 HttpSessionDispatcher (org.apache.synapse.endpoints.dispatch.HttpSessionDispatcher)6 SoapSessionDispatcher (org.apache.synapse.endpoints.dispatch.SoapSessionDispatcher)6 SimpleClientSessionDispatcher (org.apache.synapse.endpoints.dispatch.SimpleClientSessionDispatcher)4 QName (javax.xml.namespace.QName)3 OMAttribute (org.apache.axiom.om.OMAttribute)3 Endpoint (org.apache.synapse.endpoints.Endpoint)3 LoadbalanceAlgorithm (org.apache.synapse.endpoints.algorithms.LoadbalanceAlgorithm)3 Properties (java.util.Properties)2 LoadBalanceMembershipHandler (org.apache.synapse.core.LoadBalanceMembershipHandler)2 DynamicLoadbalanceEndpoint (org.apache.synapse.endpoints.DynamicLoadbalanceEndpoint)2 SALoadbalanceEndpoint (org.apache.synapse.endpoints.SALoadbalanceEndpoint)2 ServiceDynamicLoadbalanceEndpoint (org.apache.synapse.endpoints.ServiceDynamicLoadbalanceEndpoint)2 URL (java.net.URL)1 Iterator (java.util.Iterator)1 Map (java.util.Map)1 Stack (java.util.Stack)1 StAXOMBuilder (org.apache.axiom.om.impl.builder.StAXOMBuilder)1 EndpointReference (org.apache.axis2.addressing.EndpointReference)1