Search in sources :

Example 76 with URL

use of org.apache.axis2.util.URL in project wso2-synapse by wso2.

the class HTTPEndpoint method processUrlTemplate.

private void processUrlTemplate(MessageContext synCtx) throws VariableExpansionException {
    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 (VariableExpansionException 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 (VariableExpansionException 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) 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) JSONObject(org.json.JSONObject) VariableExpansionException(com.damnhandy.uri.template.VariableExpansionException)

Example 77 with URL

use of org.apache.axis2.util.URL in project wso2-synapse by wso2.

the class LoadbalanceEndpoint method sendToApplicationMember.

private void sendToApplicationMember(MessageContext synCtx, EndpointReference to, LoadbalanceFaultHandler faultHandler) {
    org.apache.axis2.context.MessageContext axis2MsgCtx = ((Axis2MessageContext) synCtx).getAxis2MessageContext();
    String transport = axis2MsgCtx.getTransportIn().getName();
    algorithm.setApplicationMembers(activeMembers);
    Member currentMember = algorithm.getNextApplicationMember(algorithmContext);
    faultHandler.setCurrentMember(currentMember);
    if (currentMember != null) {
        // URL rewrite
        if (transport.equals("http") || transport.equals("https")) {
            String address = to.getAddress();
            if (address.indexOf(":") != -1) {
                try {
                    address = new URL(address).getPath();
                } catch (MalformedURLException e) {
                    String msg = "URL " + address + " is malformed";
                    log.error(msg, e);
                    throw new SynapseException(msg, e);
                }
            }
            EndpointReference epr = new EndpointReference(transport + "://" + currentMember.getHostName() + ":" + ("http".equals(transport) ? currentMember.getHttpPort() : currentMember.getHttpsPort()) + address);
            synCtx.setTo(epr);
            if (failover) {
                synCtx.getEnvelope().build();
            }
            AddressEndpoint endpoint = new AddressEndpoint();
            EndpointDefinition definition = new EndpointDefinition();
            endpoint.setDefinition(definition);
            endpoint.init(synCtx.getEnvironment());
            endpoint.send(synCtx);
        } else {
            log.error("Cannot load balance for non-HTTP/S transport " + transport);
        }
    } else {
        // Remove the LoadbalanceFaultHandler
        synCtx.getFaultStack().pop();
        String msg = "No application members available";
        log.error(msg);
        throw new SynapseException(msg);
    }
}
Also used : MalformedURLException(java.net.MalformedURLException) SynapseException(org.apache.synapse.SynapseException) Member(org.apache.axis2.clustering.Member) URL(java.net.URL) Axis2MessageContext(org.apache.synapse.core.axis2.Axis2MessageContext) EndpointReference(org.apache.axis2.addressing.EndpointReference)

Example 78 with URL

use of org.apache.axis2.util.URL in project wso2-synapse by wso2.

the class RecipientListEndpoint method sendToApplicationMembers.

/**
 *<p>Iterates the <b>members</b> list, creates Address Endpoints
 * from each member element and routes cloned copies of the message
 * to each Address Endpoint.</p>
 * @param synCtx - The Original Message received by Synapse
 */
private void sendToApplicationMembers(MessageContext synCtx) {
    int i = 0;
    boolean foundEndpoint = false;
    for (Member member : members) {
        org.apache.axis2.context.MessageContext axis2MsgCtx = ((Axis2MessageContext) synCtx).getAxis2MessageContext();
        String transport = axis2MsgCtx.getTransportIn().getName();
        // If the transport is not HTTP nor HTTPS
        if (!transport.equals("http") && !transport.equals("https")) {
            // Skip member.
            log.error("Cannot deliver for non-HTTP/S transport " + transport);
            continue;
        }
        MessageContext newCtx = null;
        try {
            newCtx = MessageHelper.cloneMessageContext(synCtx);
        } catch (AxisFault e) {
            handleException("Error cloning the message context", e, synCtx);
        }
        // Used when aggregating responses
        newCtx.setProperty(EIPConstants.MESSAGE_SEQUENCE, String.valueOf(i++) + EIPConstants.MESSAGE_SEQUENCE_DELEMITER + members.size());
        // evaluate the endpoint properties
        evaluateProperties(newCtx);
        // URL rewrite
        String address = newCtx.getTo().getAddress();
        if (address.indexOf(":") != -1) {
            try {
                address = new URL(address).getPath();
            } catch (MalformedURLException e) {
                String msg = "URL " + address + " is malformed";
                log.error(msg, e);
                throw new SynapseException(msg, e);
            }
        }
        EndpointReference epr = new EndpointReference(transport + "://" + member.getHostName() + ":" + ("http".equals(transport) ? member.getHttpPort() : member.getHttpsPort()) + address);
        newCtx.setTo(epr);
        newCtx.pushFaultHandler(this);
        AddressEndpoint endpoint = new AddressEndpoint();
        EndpointDefinition definition = new EndpointDefinition();
        endpoint.setDefinition(definition);
        endpoint.init(newCtx.getEnvironment());
        if (endpoint.readyToSend()) {
            foundEndpoint = true;
            endpoint.send(newCtx);
        }
    }
    if (!foundEndpoint) {
        String msg = "Recipient List endpoint : " + (getName() != null ? getName() : SynapseConstants.ANONYMOUS_ENDPOINT) + " - no ready child members";
        log.warn(msg);
        informFailure(synCtx, SynapseConstants.ENDPOINT_RL_NONE_READY, msg);
    }
}
Also used : AxisFault(org.apache.axis2.AxisFault) MalformedURLException(java.net.MalformedURLException) SynapseException(org.apache.synapse.SynapseException) URL(java.net.URL) EndpointReference(org.apache.axis2.addressing.EndpointReference) MessageContext(org.apache.synapse.MessageContext) Axis2MessageContext(org.apache.synapse.core.axis2.Axis2MessageContext) Member(org.apache.axis2.clustering.Member) Axis2MessageContext(org.apache.synapse.core.axis2.Axis2MessageContext)

Example 79 with URL

use of org.apache.axis2.util.URL in project wso2-synapse by wso2.

the class DynamicLoadbalanceEndpoint method getEndpointReferenceAfterURLRewrite.

private EndpointReference getEndpointReferenceAfterURLRewrite(Member currentMember, String transport, String address, int incomingPort) {
    if (transport.startsWith("https")) {
        transport = "https";
    } else if (transport.startsWith("http")) {
        transport = "http";
    } else {
        String msg = "Cannot load balance for non-HTTP/S transport " + transport;
        log.error(msg);
        throw new SynapseException(msg);
    }
    // URL Rewrite
    if (transport.startsWith("http") || transport.startsWith("https")) {
        if (address.startsWith("http://") || address.startsWith("https://")) {
            try {
                String _address = address.indexOf("?") > 0 ? address.substring(address.indexOf("?"), address.length()) : "";
                address = new URL(address).getPath() + _address;
            } catch (MalformedURLException e) {
                String msg = "URL " + address + " is malformed";
                log.error(msg, e);
                throw new SynapseException(msg, e);
            }
        }
        int port;
        Properties memberProperties = currentMember.getProperties();
        String mappedPort = memberProperties.getProperty(PORT_MAPPING_PREFIX + incomingPort);
        if (mappedPort != null) {
            port = Integer.parseInt(mappedPort);
        } else if (transport.startsWith("https")) {
            port = currentMember.getHttpsPort();
        } else {
            port = currentMember.getHttpPort();
        }
        String remoteHost = memberProperties.getProperty("remoteHost");
        String hostName = (remoteHost == null) ? currentMember.getHostName() : remoteHost;
        return new EndpointReference(transport + "://" + hostName + ":" + port + address);
    } else {
        String msg = "Cannot load balance for non-HTTP/S transport " + transport;
        log.error(msg);
        throw new SynapseException(msg);
    }
}
Also used : MalformedURLException(java.net.MalformedURLException) SynapseException(org.apache.synapse.SynapseException) URL(java.net.URL) EndpointReference(org.apache.axis2.addressing.EndpointReference)

Example 80 with URL

use of org.apache.axis2.util.URL in project wso2-synapse by wso2.

the class TargetRequest method start.

public void start(NHttpClientConnection conn) throws IOException, HttpException {
    if (pipe != null) {
        TargetContext.get(conn).setWriter(pipe);
    }
    String path = fullUrl || (route.getProxyHost() != null && !route.isTunnelled()) ? url.toString() : url.getPath() + (url.getQuery() != null ? "?" + url.getQuery() : "");
    long contentLength = -1;
    String contentLengthHeader = null;
    LinkedHashSet<String> httpContentLengthHeader = headers.get(HTTP.CONTENT_LEN);
    if (httpContentLengthHeader != null && httpContentLengthHeader.iterator().hasNext()) {
        contentLengthHeader = httpContentLengthHeader.iterator().next();
    }
    if (contentLengthHeader != null) {
        contentLength = Long.parseLong(contentLengthHeader);
        headers.remove(HTTP.CONTENT_LEN);
    }
    MessageContext requestMsgCtx = TargetContext.get(conn).getRequestMsgCtx();
    if (requestMsgCtx.getProperty(PassThroughConstants.PASSTROUGH_MESSAGE_LENGTH) != null) {
        contentLength = (Long) requestMsgCtx.getProperty(PassThroughConstants.PASSTROUGH_MESSAGE_LENGTH);
    }
    // fix for  POST_TO_URI
    if (requestMsgCtx.isPropertyTrue(NhttpConstants.POST_TO_URI)) {
        path = url.toString();
    }
    // fix GET request empty body
    if ((PassThroughConstants.HTTP_GET.equals(requestMsgCtx.getProperty(Constants.Configuration.HTTP_METHOD))) || (RelayUtils.isDeleteRequestWithoutPayload(requestMsgCtx))) {
        hasEntityBody = false;
        MessageFormatter formatter = MessageProcessorSelector.getMessageFormatter(requestMsgCtx);
        OMOutputFormat format = PassThroughTransportUtils.getOMOutputFormat(requestMsgCtx);
        if (formatter != null && format != null) {
            URL _url = formatter.getTargetAddress(requestMsgCtx, format, url);
            if (_url != null && !_url.toString().isEmpty()) {
                if (requestMsgCtx.getProperty(NhttpConstants.POST_TO_URI) != null && Boolean.TRUE.toString().equals(requestMsgCtx.getProperty(NhttpConstants.POST_TO_URI))) {
                    path = _url.toString();
                } else {
                    path = _url.getPath() + ((_url.getQuery() != null && !_url.getQuery().isEmpty()) ? ("?" + _url.getQuery()) : "");
                }
            }
            headers.remove(HTTP.CONTENT_TYPE);
        }
    }
    Object o = requestMsgCtx.getProperty(MessageContext.TRANSPORT_HEADERS);
    if (o != null && o instanceof TreeMap) {
        Map _headers = (Map) o;
        String trpContentType = (String) _headers.get(HTTP.CONTENT_TYPE);
        if (trpContentType != null && !trpContentType.equals("")) {
            if (!TargetRequestFactory.isMultipartContent(trpContentType) && !requestMsgCtx.isDoingSwA()) {
                addHeader(HTTP.CONTENT_TYPE, trpContentType);
            }
        }
    }
    if (hasEntityBody) {
        request = new BasicHttpEntityEnclosingRequest(method, path, version != null ? version : HttpVersion.HTTP_1_1);
        BasicHttpEntity entity = new BasicHttpEntity();
        boolean forceContentLength = requestMsgCtx.isPropertyTrue(NhttpConstants.FORCE_HTTP_CONTENT_LENGTH);
        boolean forceContentLengthCopy = requestMsgCtx.isPropertyTrue(PassThroughConstants.COPY_CONTENT_LENGTH_FROM_INCOMING);
        if (forceContentLength) {
            entity.setChunked(false);
            if (forceContentLengthCopy && contentLength != -1) {
                entity.setContentLength(contentLength);
            }
        } else {
            if (contentLength != -1) {
                entity.setChunked(false);
                entity.setContentLength(contentLength);
            } else {
                entity.setChunked(chunk);
            }
        }
        ((BasicHttpEntityEnclosingRequest) request).setEntity(entity);
    } else {
        request = new BasicHttpRequest(method, path, version != null ? version : HttpVersion.HTTP_1_1);
    }
    Set<Map.Entry<String, LinkedHashSet<String>>> entries = headers.entrySet();
    for (Map.Entry<String, LinkedHashSet<String>> entry : entries) {
        if (entry.getKey() != null) {
            Iterator<String> i = entry.getValue().iterator();
            while (i.hasNext()) {
                request.addHeader(entry.getKey(), i.next());
            }
        }
    }
    // setup wsa action..
    if (request != null) {
        String soapAction = requestMsgCtx.getSoapAction();
        if (soapAction == null) {
            soapAction = requestMsgCtx.getWSAAction();
            requestMsgCtx.getAxisOperation().getInputAction();
        }
        if (requestMsgCtx.isSOAP11() && soapAction != null && soapAction.length() > 0) {
            Header existingHeader = request.getFirstHeader(HTTPConstants.HEADER_SOAP_ACTION);
            if (existingHeader != null) {
                request.removeHeader(existingHeader);
            }
            MessageFormatter messageFormatter = MessageFormatterDecoratorFactory.createMessageFormatterDecorator(requestMsgCtx);
            request.setHeader(HTTPConstants.HEADER_SOAP_ACTION, messageFormatter.formatSOAPAction(requestMsgCtx, null, soapAction));
        // request.setHeader(HTTPConstants.USER_AGENT,"Synapse-PT-HttpComponents-NIO");
        }
    }
    request.setParams(new DefaultedHttpParams(request.getParams(), targetConfiguration.getHttpParams()));
    // Chunking is not performed for request has "http 1.0" and "GET" http method
    if (!((request.getProtocolVersion().equals(HttpVersion.HTTP_1_0)) || (PassThroughConstants.HTTP_GET.equals(requestMsgCtx.getProperty(Constants.Configuration.HTTP_METHOD))) || RelayUtils.isDeleteRequestWithoutPayload(requestMsgCtx) || !(hasEntityBody))) {
        this.processChunking(conn, requestMsgCtx);
    }
    if (!keepAlive) {
        request.setHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_CLOSE);
    }
    // Pre-process HTTP request
    HttpContext httpContext = conn.getContext();
    httpContext.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
    if (port == -1) {
        httpContext.setAttribute(ExecutionContext.HTTP_TARGET_HOST, new HttpHost(url.getHost()));
    } else {
        httpContext.setAttribute(ExecutionContext.HTTP_TARGET_HOST, new HttpHost(url.getHost(), port));
    }
    conn.getContext().setAttribute(ExecutionContext.HTTP_REQUEST, request);
    httpContext.setAttribute(PassThroughConstants.PROXY_PROFILE_TARGET_HOST, requestMsgCtx.getProperty(PassThroughConstants.PROXY_PROFILE_TARGET_HOST));
    // start the request
    targetConfiguration.getHttpProcessor().process(request, httpContext);
    if (targetConfiguration.getProxyAuthenticator() != null && route.getProxyHost() != null && !route.isTunnelled()) {
        targetConfiguration.getProxyAuthenticator().authenticatePreemptively(request, httpContext);
    }
    conn.submitRequest(request);
    if (hasEntityBody) {
        TargetContext.updateState(conn, ProtocolState.REQUEST_HEAD);
    } else {
        TargetContext.updateState(conn, ProtocolState.REQUEST_DONE);
    }
}
Also used : LinkedHashSet(java.util.LinkedHashSet) HttpContext(org.apache.http.protocol.HttpContext) BasicHttpEntity(org.apache.http.entity.BasicHttpEntity) MessageFormatter(org.apache.axis2.transport.MessageFormatter) TreeMap(java.util.TreeMap) DefaultedHttpParams(org.apache.http.params.DefaultedHttpParams) URL(java.net.URL) BasicHttpRequest(org.apache.http.message.BasicHttpRequest) Header(org.apache.http.Header) HttpHost(org.apache.http.HttpHost) MessageContext(org.apache.axis2.context.MessageContext) OMOutputFormat(org.apache.axiom.om.OMOutputFormat) HashMap(java.util.HashMap) Map(java.util.Map) TreeMap(java.util.TreeMap) BasicHttpEntityEnclosingRequest(org.apache.http.message.BasicHttpEntityEnclosingRequest)

Aggregations

IOException (java.io.IOException)31 EndpointReference (org.apache.axis2.addressing.EndpointReference)29 AxisFault (org.apache.axis2.AxisFault)27 URL (java.net.URL)21 ConfigurationContext (org.apache.axis2.context.ConfigurationContext)19 URL (org.apache.axis2.util.URL)19 HttpClient (org.apache.http.client.HttpClient)19 Options (org.apache.axis2.client.Options)18 MalformedURLException (java.net.MalformedURLException)17 OMElement (org.apache.axiom.om.OMElement)17 MessageContext (org.apache.axis2.context.MessageContext)16 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)16 ServiceClient (org.apache.axis2.client.ServiceClient)13 SynapseException (org.apache.synapse.SynapseException)13 AxisConfiguration (org.apache.axis2.engine.AxisConfiguration)12 AxisService (org.apache.axis2.description.AxisService)10 StringEntity (org.apache.http.entity.StringEntity)9 SynapseConfiguration (org.apache.synapse.config.SynapseConfiguration)9 Map (java.util.Map)7 JSONObject (org.json.JSONObject)7