Search in sources :

Example 16 with MediatorProperty

use of org.apache.synapse.mediators.MediatorProperty in project wso2-synapse by wso2.

the class HTTPEndpoint method processUrlTemplate.

private void processUrlTemplate(MessageContext synCtx) throws ExpressionParseException {
    Map<String, Object> variables = new HashMap<String, Object>();
    /*The properties with uri.var.* are only considered for Outbound REST Endpoints*/
    Set propertySet = synCtx.getPropertyKeySet();
    // We have to create a local UriTemplate object, or else the UriTemplate.set(variables) call will fill up a list of variables and since uriTemplate
    // is not thread safe, this list won't be clearing.
    UriTemplate template = null;
    String evaluatedUri = "";
    // legacySupport for backward compatibility where URI Template decoding handled via HTTPEndpoint
    if (legacySupport) {
        for (Object propertyKey : propertySet) {
            if (propertyKey.toString() != null && (propertyKey.toString().startsWith(RESTConstants.REST_URI_VARIABLE_PREFIX) || propertyKey.toString().startsWith(RESTConstants.REST_QUERY_PARAM_PREFIX))) {
                Object objProperty = synCtx.getProperty(propertyKey.toString());
                if (objProperty != null) {
                    if (objProperty instanceof String) {
                        variables.put(propertyKey.toString(), decodeString((String) synCtx.getProperty(propertyKey.toString())));
                    } else {
                        variables.put(propertyKey.toString(), decodeString(String.valueOf(synCtx.getProperty(propertyKey.toString()))));
                    }
                }
            }
        }
        // Include properties defined at endpoint.
        Iterator endpointProperties = getProperties().iterator();
        while (endpointProperties.hasNext()) {
            MediatorProperty property = (MediatorProperty) endpointProperties.next();
            if (property.getName().toString() != null && (property.getName().toString().startsWith(RESTConstants.REST_URI_VARIABLE_PREFIX) || property.getName().toString().startsWith(RESTConstants.REST_QUERY_PARAM_PREFIX))) {
                variables.put(property.getName(), decodeString((String) property.getValue()));
            }
        }
        template = UriTemplate.fromTemplate(uriTemplate.getTemplate());
        if (template != null) {
            template.set(variables);
        }
        if (variables.isEmpty()) {
            evaluatedUri = template.getTemplate();
        } else {
            try {
                // Decode needs to avoid replacing special characters(e.g %20 -> %2520) when creating URL.
                String decodedString = URLDecoder.decode(template.expand(), "UTF-8");
                URL url = new URL(decodedString);
                URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(), url.getQuery(), // this to avoid url.toURI which causes exceptions
                url.getRef());
                evaluatedUri = uri.toURL().toString();
                if (log.isDebugEnabled()) {
                    log.debug("Expanded URL : " + evaluatedUri);
                }
            } catch (URISyntaxException e) {
                if (log.isDebugEnabled()) {
                    log.debug("Invalid URL syntax for HTTP Endpoint: " + this.getName(), e);
                }
                evaluatedUri = template.getTemplate();
            } catch (ExpressionParseException e) {
                log.debug("No URI Template variables defined in HTTP Endpoint: " + this.getName());
                evaluatedUri = template.getTemplate();
            } catch (MalformedURLException e) {
                log.debug("Invalid URL for HTTP Endpoint: " + this.getName());
                evaluatedUri = template.getTemplate();
            } catch (UnsupportedEncodingException e) {
                log.debug("Exception while decoding the URL in HTTP Endpoint: " + this.getName());
                evaluatedUri = template.getTemplate();
            }
        }
    } else {
        // URI Template encoding not handled by HTTP Endpoint, compliant with RFC6570
        for (Object propertyKey : propertySet) {
            if (propertyKey.toString() != null && (propertyKey.toString().startsWith(RESTConstants.REST_URI_VARIABLE_PREFIX) || propertyKey.toString().startsWith(RESTConstants.REST_QUERY_PARAM_PREFIX))) {
                Object objProperty = synCtx.getProperty(propertyKey.toString());
                if (objProperty != null) {
                    if (objProperty instanceof String) {
                        variables.put(propertyKey.toString(), (String) synCtx.getProperty(propertyKey.toString()));
                    } else {
                        variables.put(propertyKey.toString(), (String) String.valueOf(synCtx.getProperty(propertyKey.toString())));
                    }
                }
            }
        }
        // Include properties defined at endpoint.
        Iterator endpointProperties = getProperties().iterator();
        while (endpointProperties.hasNext()) {
            MediatorProperty property = (MediatorProperty) endpointProperties.next();
            if (property.getName().toString() != null && (property.getName().toString().startsWith(RESTConstants.REST_URI_VARIABLE_PREFIX) || property.getName().toString().startsWith(RESTConstants.REST_QUERY_PARAM_PREFIX))) {
                variables.put(property.getName(), (String) property.getValue());
            }
        }
        String tmpl;
        // this was used in connectors Eg:- uri-template="{uri.var.variable}"
        if (uriTemplate.getTemplate().charAt(0) == '{' && uriTemplate.getTemplate().charAt(1) != '+') {
            tmpl = "{+" + uriTemplate.getTemplate().substring(1);
        } else {
            tmpl = uriTemplate.getTemplate();
        }
        template = UriTemplate.fromTemplate(tmpl);
        if (template != null) {
            template.set(variables);
        }
        if (variables.isEmpty()) {
            evaluatedUri = template.getTemplate();
        } else {
            try {
                URI uri = new URI(template.expand());
                evaluatedUri = uri.toString();
                if (log.isDebugEnabled()) {
                    log.debug("Expanded URL : " + evaluatedUri);
                }
            } catch (URISyntaxException e) {
                if (log.isDebugEnabled()) {
                    log.debug("Invalid URL syntax for HTTP Endpoint: " + this.getName(), e);
                }
                evaluatedUri = template.getTemplate();
            } catch (ExpressionParseException e) {
                log.debug("No URI Template variables defined in HTTP Endpoint: " + this.getName());
                evaluatedUri = template.getTemplate();
            }
        }
    }
    if (evaluatedUri != null) {
        synCtx.setTo(new EndpointReference(evaluatedUri));
        if (super.getDefinition() != null) {
            synCtx.setProperty(EndpointDefinition.DYNAMIC_URL_VALUE, evaluatedUri);
        }
    }
}
Also used : Set(java.util.Set) HashMap(java.util.HashMap) ExpressionParseException(com.damnhandy.uri.template.impl.ExpressionParseException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) UriTemplate(com.damnhandy.uri.template.UriTemplate) EndpointReference(org.apache.axis2.addressing.EndpointReference) MediatorProperty(org.apache.synapse.mediators.MediatorProperty) Iterator(java.util.Iterator)

Example 17 with MediatorProperty

use of org.apache.synapse.mediators.MediatorProperty in project wso2-synapse by wso2.

the class AbstractEndpoint method send.

public void send(MessageContext synCtx) {
    logSetter();
    Integer statisticReportingIndex = null;
    boolean isStatisticsEnabled = RuntimeStatisticCollector.isStatisticsEnabled();
    if (isStatisticsEnabled) {
        statisticReportingIndex = OpenEventCollector.reportEntryEvent(synCtx, getReportingName(), definition.getAspectConfiguration(), ComponentType.ENDPOINT);
    }
    boolean traceOn = isTraceOn(synCtx);
    boolean traceOrDebugOn = isTraceOrDebugOn(traceOn);
    if (!initialized) {
        // can't send to a non-initialized endpoint. This is a program fault
        throw new IllegalStateException("not initialized, " + "endpoint must be in initialized state");
    }
    prepareForEndpointStatistics(synCtx);
    if (traceOrDebugOn) {
        String address = definition.getAddress();
        if (address == null && synCtx.getTo() != null && synCtx.getTo().getAddress() != null) {
            // compute address for the default endpoint only for logging purposes
            address = synCtx.getTo().getAddress();
        }
        traceOrDebug(traceOn, "Sending message through endpoint : " + getName() + " resolving to address = " + address);
        traceOrDebug(traceOn, "SOAPAction: " + (synCtx.getSoapAction() != null ? synCtx.getSoapAction() : "null"));
        traceOrDebug(traceOn, "WSA-Action: " + (synCtx.getWSAAction() != null ? synCtx.getWSAAction() : "null"));
        if (traceOn && trace.isTraceEnabled()) {
            trace.trace("Envelope : \n" + synCtx.getEnvelope());
        }
    }
    // push the errorHandler sequence into the current message as the fault handler
    if (errorHandler != null) {
        Mediator errorHandlerMediator = synCtx.getSequence(errorHandler);
        if (errorHandlerMediator != null) {
            if (traceOrDebugOn) {
                traceOrDebug(traceOn, "Setting the onError handler : " + errorHandler + " for the endpoint : " + endpointName);
            }
            synCtx.pushFaultHandler(new MediatorFaultHandler(errorHandlerMediator));
        } else {
            log.warn("onError handler sequence : " + errorHandler + " for : " + endpointName + " cannot be found");
        }
    }
    // register this as the immediate fault handler for this message.
    synCtx.pushFaultHandler(this);
    // add this as the last endpoint to process this message - used by statistics counting code
    synCtx.setProperty(SynapseConstants.LAST_ENDPOINT, this);
    // set message level metrics collector
    org.apache.axis2.context.MessageContext axis2Ctx = ((Axis2MessageContext) synCtx).getAxis2MessageContext();
    axis2Ctx.setProperty(BaseConstants.METRICS_COLLECTOR, metricsMBean);
    if (contentAware) {
        try {
            RelayUtils.buildMessage(((Axis2MessageContext) synCtx).getAxis2MessageContext(), false);
            axis2Ctx.setProperty(RelayConstants.FORCE_RESPONSE_EARLY_BUILD, Boolean.TRUE);
            if (forceBuildMC) {
                ((Axis2MessageContext) synCtx).getAxis2MessageContext().getEnvelope().build();
            }
        } catch (Exception e) {
            handleException("Error while building message", e);
        }
    }
    evaluateProperties(synCtx);
    // if the envelope preserving set build the envelope
    MediatorProperty preserveEnv = getProperty(SynapseConstants.PRESERVE_ENVELOPE);
    if (preserveEnv != null && JavaUtils.isTrueExplicitly(preserveEnv.getValue() != null ? preserveEnv.getValue() : preserveEnv.getEvaluatedExpression(synCtx))) {
        if (traceOrDebugOn) {
            traceOrDebug(traceOn, "Preserving the envelope by building it before " + "sending, since it is explicitly set");
        }
        synCtx.getEnvelope().build();
    }
    // Send the message through this endpoint
    synCtx.getEnvironment().send(definition, synCtx);
    if (isStatisticsEnabled) {
        CloseEventCollector.closeEntryEvent(synCtx, getReportingName(), ComponentType.ENDPOINT, statisticReportingIndex, false);
    }
}
Also used : MediatorFaultHandler(org.apache.synapse.mediators.MediatorFaultHandler) MediatorProperty(org.apache.synapse.mediators.MediatorProperty) Mediator(org.apache.synapse.Mediator) SynapseException(org.apache.synapse.SynapseException) Axis2MessageContext(org.apache.synapse.core.axis2.Axis2MessageContext)

Example 18 with MediatorProperty

use of org.apache.synapse.mediators.MediatorProperty in project wso2-synapse by wso2.

the class ValidateMediator method addFeature.

/**
 * add a feature which need to set for the Schema Factory
 *
 * @param  featureName The name of the feature
 * @param isFeatureEnable should this feature enable?(true|false)
 * @see #getFeature(String)
 * @throws SAXException on an unknown feature
 */
public void addFeature(String featureName, boolean isFeatureEnable) throws SAXException {
    MediatorProperty mp = new MediatorProperty();
    mp.setName(featureName);
    if (isFeatureEnable) {
        mp.setValue("true");
    } else {
        mp.setValue("false");
    }
    explicityFeatures.add(mp);
    factory.setFeature(featureName, isFeatureEnable);
}
Also used : MediatorProperty(org.apache.synapse.mediators.MediatorProperty)

Example 19 with MediatorProperty

use of org.apache.synapse.mediators.MediatorProperty in project wso2-synapse by wso2.

the class WeightedRRLCAlgorithmTest method createLoadBalanceEndpoint.

private LoadbalanceEndpoint createLoadBalanceEndpoint() {
    LoadbalanceEndpoint loadbalanceEndpoint = new LoadbalanceEndpoint();
    List<Endpoint> endpoints = createEndpoints();
    WeightedRRLCAlgorithm algorithm = new WeightedRRLCAlgorithm();
    MediatorProperty property = new MediatorProperty();
    property.setName(WeightedRRLCAlgorithm.LB_WEIGHTED_RRLC_ROUNDS_PER_RECAL);
    property.setValue("2");
    loadbalanceEndpoint.addProperty(property);
    algorithm.setEndpoints(endpoints);
    algorithm.setLoadBalanceEndpoint(loadbalanceEndpoint);
    loadbalanceEndpoint.setChildren(endpoints);
    loadbalanceEndpoint.setAlgorithm(algorithm);
    SynapseEnvironment env = new Axis2SynapseEnvironment(new ConfigurationContext(new AxisConfiguration()), new SynapseConfiguration());
    loadbalanceEndpoint.init(env);
    return loadbalanceEndpoint;
}
Also used : Axis2SynapseEnvironment(org.apache.synapse.core.axis2.Axis2SynapseEnvironment) ConfigurationContext(org.apache.axis2.context.ConfigurationContext) AxisConfiguration(org.apache.axis2.engine.AxisConfiguration) LoadbalanceEndpoint(org.apache.synapse.endpoints.LoadbalanceEndpoint) MediatorProperty(org.apache.synapse.mediators.MediatorProperty) AddressEndpoint(org.apache.synapse.endpoints.AddressEndpoint) Endpoint(org.apache.synapse.endpoints.Endpoint) LoadbalanceEndpoint(org.apache.synapse.endpoints.LoadbalanceEndpoint) Axis2SynapseEnvironment(org.apache.synapse.core.axis2.Axis2SynapseEnvironment) SynapseEnvironment(org.apache.synapse.core.SynapseEnvironment) SynapseConfiguration(org.apache.synapse.config.SynapseConfiguration)

Example 20 with MediatorProperty

use of org.apache.synapse.mediators.MediatorProperty in project wso2-synapse by wso2.

the class WeightedRRLCAlgorithmTest method createEndpoints.

private List<Endpoint> createEndpoints() {
    List<Endpoint> endpoints = new ArrayList<Endpoint>();
    for (int i = 0; i < hosts.length; i++) {
        AddressEndpoint addressEndpoint = new AddressEndpoint();
        EndpointDefinition definition = new EndpointDefinition();
        definition.setAddress("http://" + hosts[i] + "/");
        addressEndpoint.setDefinition(definition);
        MediatorProperty property = new MediatorProperty();
        property.setName(WeightedRRLCAlgorithm.LB_WEIGHTED_RRLC_WEIGHT);
        property.setValue(weights[i]);
        addressEndpoint.addProperty(property);
        endpoints.add(addressEndpoint);
    }
    return endpoints;
}
Also used : AddressEndpoint(org.apache.synapse.endpoints.AddressEndpoint) MediatorProperty(org.apache.synapse.mediators.MediatorProperty) AddressEndpoint(org.apache.synapse.endpoints.AddressEndpoint) Endpoint(org.apache.synapse.endpoints.Endpoint) LoadbalanceEndpoint(org.apache.synapse.endpoints.LoadbalanceEndpoint) ArrayList(java.util.ArrayList) EndpointDefinition(org.apache.synapse.endpoints.EndpointDefinition) AddressEndpoint(org.apache.synapse.endpoints.AddressEndpoint) Endpoint(org.apache.synapse.endpoints.Endpoint) LoadbalanceEndpoint(org.apache.synapse.endpoints.LoadbalanceEndpoint)

Aggregations

MediatorProperty (org.apache.synapse.mediators.MediatorProperty)21 OMElement (org.apache.axiom.om.OMElement)8 SynapseException (org.apache.synapse.SynapseException)8 ArrayList (java.util.ArrayList)5 Endpoint (org.apache.synapse.endpoints.Endpoint)4 AddressEndpoint (org.apache.synapse.endpoints.AddressEndpoint)3 SynapseXPath (org.apache.synapse.util.xpath.SynapseXPath)3 Test (org.junit.Test)3 Iterator (java.util.Iterator)2 QName (javax.xml.namespace.QName)2 TransformerConfigurationException (javax.xml.transform.TransformerConfigurationException)2 OMAttribute (org.apache.axiom.om.OMAttribute)2 PropertyInclude (org.apache.synapse.PropertyInclude)2 Axis2MessageContext (org.apache.synapse.core.axis2.Axis2MessageContext)2 LoadbalanceEndpoint (org.apache.synapse.endpoints.LoadbalanceEndpoint)2 Value (org.apache.synapse.mediators.Value)2 UriTemplate (com.damnhandy.uri.template.UriTemplate)1 ExpressionParseException (com.damnhandy.uri.template.impl.ExpressionParseException)1 IOException (java.io.IOException)1 InputStream (java.io.InputStream)1