Search in sources :

Example 21 with URI

use of org.apache.axis2.databinding.types.URI in project carbon-business-process by wso2.

the class HTRenderingApiImpl method setTaskOutput.

public SetTaskOutputResponse setTaskOutput(URI taskIdentifier, SetOutputValuesType values) throws SetTaskOutputFaultException {
    // Retrieve task information
    TaskDAO htTaskDAO;
    try {
        htTaskDAO = getTaskDAO(taskIdentifier);
    } catch (Exception e) {
        log.error("Error occurred while retrieving task data", e);
        throw new SetTaskOutputFaultException(e);
    }
    QName taskName = QName.valueOf(htTaskDAO.getName());
    // Check hash map for output message template
    Element outputMsgTemplate = outputTemplates.get(taskName);
    if (outputMsgTemplate == null) {
        try {
            // generate output message template
            int tenantID = CarbonContext.getThreadLocalCarbonContext().getTenantId();
            HumanTaskBaseConfiguration htConf = HumanTaskServiceComponent.getHumanTaskServer().getTaskStoreManager().getHumanTaskStore(tenantID).getTaskConfiguration(taskName);
            TaskConfiguration taskConf = (TaskConfiguration) htConf;
            // retrieve response binding
            Service callbackService = (Service) taskConf.getResponseWSDL().getServices().get(taskConf.getCallbackServiceName());
            Port callbackPort = (Port) callbackService.getPorts().get(taskConf.getCallbackPortName());
            String callbackBinding = callbackPort.getBinding().getQName().getLocalPart();
            outputMsgTemplate = createSoapTemplate(taskConf.getResponseWSDL().getDocumentBaseURI(), taskConf.getResponsePortType().getLocalPart(), taskConf.getResponseOperation(), callbackBinding);
        } catch (Exception e) {
            log.error("Error occurred while output message template generation", e);
            throw new SetTaskOutputFaultException("Unable to generate output message", e);
        }
        // add to the template HashMap
        if (outputMsgTemplate != null) {
            outputTemplates.put(taskName, outputMsgTemplate);
        } else {
            log.error("Unable to create output message template");
            throw new SetTaskOutputFaultException("Unable to generate output message");
        }
    }
    // update template with new values
    try {
        // TODO improve this section with caching
        QName renderingType = new QName(htRenderingNS, "output", "wso2");
        String outputRenderings = (String) taskOps.getRendering(taskIdentifier, renderingType);
        SetOutputvalueType[] valueSet = values.getValue();
        if (outputRenderings != null && valueSet.length > 0) {
            Element outputRenderingsElement = DOMUtils.stringToDOM(outputRenderings);
            // update elements in the template to create output xml
            for (int i = 0; i < valueSet.length; i++) {
                Element outElement = getOutputElementById(valueSet[i].getId(), outputRenderingsElement);
                if (outElement != null) {
                    outputMsgTemplate = updateXmlByXpath(outputMsgTemplate, outElement.getElementsByTagNameNS(htRenderingNS, "xpath").item(0).getTextContent(), valueSet[i].getString(), outputRenderingsElement.getOwnerDocument());
                }
            }
        } else {
            log.error("Retrieving output renderings failed");
            throw new SetTaskOutputFaultException("Retrieving output renderings failed");
        }
        // TODO what is this NCName?
        taskOps.setOutput(taskIdentifier, new NCName("message"), DOMUtils.domToString(outputMsgTemplate));
    } catch (IllegalArgumentFault illegalArgumentFault) {
        // Error occurred while retrieving HT renderings and set output message
        throw new SetTaskOutputFaultException(illegalArgumentFault);
    } catch (SAXException e) {
        log.error("Error occured while parsing output renderings", e);
        throw new SetTaskOutputFaultException("Response message generation failed");
    } catch (XPathExpressionException e) {
        // Error occured while updating elements in the template to create output xml
        log.error("XPath evaluation failed", e);
        throw new SetTaskOutputFaultException("Internal Error Occurred");
    } catch (Exception e) {
        // Error occurred while updating template with new values
        log.error("Error occurred while updating template with new values", e);
        throw new SetTaskOutputFaultException("Internal Error Occurred");
    }
    SetTaskOutputResponse response = new SetTaskOutputResponse();
    response.setSuccess(true);
    return response;
}
Also used : QName(javax.xml.namespace.QName) XPathExpressionException(javax.xml.xpath.XPathExpressionException) Element(org.w3c.dom.Element) Port(javax.wsdl.Port) SetTaskOutputResponse(org.wso2.carbon.humantask.rendering.api.SetTaskOutputResponse) TaskConfiguration(org.wso2.carbon.humantask.core.store.TaskConfiguration) Service(javax.wsdl.Service) HumanTaskBaseConfiguration(org.wso2.carbon.humantask.core.store.HumanTaskBaseConfiguration) XPathExpressionException(javax.xml.xpath.XPathExpressionException) SetTaskOutputFaultException(org.wso2.carbon.humantask.rendering.api.SetTaskOutputFaultException) GetRenderingsFaultException(org.wso2.carbon.humantask.rendering.api.GetRenderingsFaultException) SAXException(org.xml.sax.SAXException) CompleteTaskFaultException(org.wso2.carbon.humantask.rendering.api.CompleteTaskFaultException) IOException(java.io.IOException) HumanTaskIllegalAccessException(org.wso2.carbon.humantask.core.engine.runtime.api.HumanTaskIllegalAccessException) NCName(org.apache.axis2.databinding.types.NCName) SAXException(org.xml.sax.SAXException) SetOutputvalueType(org.wso2.carbon.humantask.rendering.api.SetOutputvalueType) TaskDAO(org.wso2.carbon.humantask.core.dao.TaskDAO) IllegalArgumentFault(org.wso2.carbon.humantask.client.api.IllegalArgumentFault) SetTaskOutputFaultException(org.wso2.carbon.humantask.rendering.api.SetTaskOutputFaultException)

Example 22 with URI

use of org.apache.axis2.databinding.types.URI in project wso2-synapse by wso2.

the class URLRewriteMediator method mediate.

public boolean mediate(MessageContext messageContext) {
    if (messageContext.getEnvironment().isDebuggerEnabled()) {
        if (super.divertMediationRoute(messageContext)) {
            return true;
        }
    }
    URIFragments fragments;
    URI inputURI = getInputAddress(messageContext);
    if (inputURI != null) {
        /*try {
                URL url = new URL(inputURI.toString());
            } catch (MalformedURLException e) {
                handleException("Malformed URL when processing " + inputURI, e, messageContext);
            }*/
        fragments = new URIFragments(inputURI);
    } else {
        fragments = new URIFragments();
    }
    try {
        for (RewriteRule r : rules) {
            r.rewrite(fragments, messageContext);
        }
        if (outputProperty != null) {
            messageContext.setProperty(outputProperty, fragments.toURIString());
        } else {
            messageContext.setTo(new EndpointReference(fragments.toURIString()));
        }
        if (log.isDebugEnabled()) {
            log.debug("URL Rewrite Mediator has rewritten the address url : \n " + messageContext.getEnvelope());
        }
    } catch (URISyntaxException e) {
        handleException("Error while constructing a URI from the fragments", e, messageContext);
    }
    return true;
}
Also used : URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) EndpointReference(org.apache.axis2.addressing.EndpointReference)

Example 23 with URI

use of org.apache.axis2.databinding.types.URI in project wso2-synapse by wso2.

the class PassThroughNHttpGetProcessor method process.

public void process(HttpRequest request, HttpResponse response, MessageContext msgContext, NHttpServerConnection conn, OutputStream ostream, boolean isRestDispatching) {
    String uri = request.getRequestLine().getUri();
    String serviceName = getServiceName(request);
    Map<String, String> parameters = new HashMap<String, String>();
    int pos = uri.indexOf("?");
    if (pos != -1) {
        msgContext.setTo(new EndpointReference(uri.substring(0, pos)));
        StringTokenizer st = new StringTokenizer(uri.substring(pos + 1), "&");
        while (st.hasMoreTokens()) {
            String param = st.nextToken();
            pos = param.indexOf("=");
            if (pos != -1) {
                parameters.put(param.substring(0, pos), param.substring(pos + 1));
            } else {
                parameters.put(param, null);
            }
        }
    } else {
        msgContext.setTo(new EndpointReference(uri));
    }
    SimpleOutputBuffer outputBuffer = (SimpleOutputBuffer) conn.getContext().getAttribute(PASS_THROUGH_RESPONSE_SOURCE_BUFFER);
    ContentOutputStream os = new ContentOutputStream(outputBuffer);
    if (isServiceListBlocked(uri)) {
        sendResponseAndFinish(response, HttpStatus.SC_FORBIDDEN, conn, os, msgContext);
    } else if (uri.equals("/favicon.ico")) {
        response.addHeader(LOCATION, "http://ws.apache.org/favicon.ico");
        sendResponseAndFinish(response, HttpStatus.SC_MOVED_PERMANENTLY, conn, os, msgContext);
    } else if (serviceName != null && parameters.containsKey("wsdl")) {
        generateWsdl(response, msgContext, conn, os, serviceName, parameters);
    } else if (serviceName != null && parameters.containsKey("wsdl2")) {
        generateWsdl2(response, msgContext, conn, os, serviceName);
    } else if (serviceName != null && parameters.containsKey("xsd")) {
        generateXsd(response, msgContext, conn, os, serviceName, parameters);
    } else {
        msgContext.setProperty(PassThroughConstants.REST_GET_DELETE_INVOKE, true);
    }
}
Also used : StringTokenizer(java.util.StringTokenizer) SimpleOutputBuffer(org.apache.http.nio.util.SimpleOutputBuffer) HashMap(java.util.HashMap) ContentOutputStream(org.apache.http.nio.entity.ContentOutputStream) EndpointReference(org.apache.axis2.addressing.EndpointReference)

Example 24 with URI

use of org.apache.axis2.databinding.types.URI in project wso2-synapse by wso2.

the class ServerWorker method processHttpRequestUri.

/**
 * Get Uri of underlying SourceRequest and  calculate service prefix and add to message context
 * create response buffers for  HTTP GET, DELETE, OPTION and HEAD methods
 * @param msgContext Axis2MessageContext of the request
 * @param method HTTP Method of the request
 */
public void processHttpRequestUri(MessageContext msgContext, String method) {
    String servicePrefixIndex = "://";
    ConfigurationContext cfgCtx = sourceConfiguration.getConfigurationContext();
    msgContext.setProperty(Constants.Configuration.HTTP_METHOD, request.getMethod());
    // String uri = request.getUri();
    String oriUri = request.getUri();
    String restUrlPostfix = NhttpUtil.getRestUrlPostfix(oriUri, cfgCtx.getServicePath());
    String servicePrefix = oriUri.substring(0, oriUri.indexOf(restUrlPostfix));
    if (servicePrefix.indexOf(servicePrefixIndex) == -1) {
        HttpInetConnection inetConn = (HttpInetConnection) request.getConnection();
        InetAddress localAddr = inetConn.getLocalAddress();
        if (localAddr != null) {
            servicePrefix = sourceConfiguration.getScheme().getName() + servicePrefixIndex + localAddr.getHostAddress() + ":" + inetConn.getLocalPort() + servicePrefix;
        }
    }
    msgContext.setProperty(PassThroughConstants.SERVICE_PREFIX, servicePrefix);
    msgContext.setTo(new EndpointReference(restUrlPostfix));
    msgContext.setProperty(PassThroughConstants.REST_URL_POSTFIX, restUrlPostfix);
    if (PassThroughConstants.HTTP_GET.equals(method) || PassThroughConstants.HTTP_HEAD.equals(method) || PassThroughConstants.HTTP_OPTIONS.equals(method)) {
        HttpResponse response = sourceConfiguration.getResponseFactory().newHttpResponse(request.getVersion(), HttpStatus.SC_OK, request.getConnection().getContext());
        // create a basic HttpEntity using the source channel of the response pipe
        BasicHttpEntity entity = new BasicHttpEntity();
        if (request.getVersion().greaterEquals(HttpVersion.HTTP_1_1)) {
            entity.setChunked(true);
        }
        response.setEntity(entity);
        httpGetRequestProcessor.process(request.getRequest(), response, msgContext, request.getConnection(), os, isRestDispatching);
    }
}
Also used : ConfigurationContext(org.apache.axis2.context.ConfigurationContext) HttpResponse(org.apache.http.HttpResponse) HttpInetConnection(org.apache.http.HttpInetConnection) BasicHttpEntity(org.apache.http.entity.BasicHttpEntity) InetAddress(java.net.InetAddress) EndpointReference(org.apache.axis2.addressing.EndpointReference)

Example 25 with URI

use of org.apache.axis2.databinding.types.URI in project wso2-synapse by wso2.

the class RESTUtil method prepareMessageContext.

/**
 * prepare message context prior to call axis2 RestUtils
 *
 * @param msgContext  The MessageContext of the Request Message
 * @param requestURI  The URL that the request came to
 * @param httpMethod  The http method of the request
 * @param out         The output stream of the response
 * @param contentType The content type of the request
 * @param dispatching weather we should do dispatching
 * @throws AxisFault Thrown in case a fault occurs
 */
private static void prepareMessageContext(MessageContext msgContext, String requestURI, String httpMethod, OutputStream out, String contentType, boolean dispatching) throws AxisFault {
    msgContext.setTo(new EndpointReference(requestURI));
    msgContext.setProperty(HTTPConstants.HTTP_METHOD, httpMethod);
    msgContext.setServerSide(true);
    msgContext.setDoingREST(true);
    msgContext.setProperty(MessageContext.TRANSPORT_OUT, out);
    msgContext.setProperty(NhttpConstants.REST_REQUEST_CONTENT_TYPE, contentType);
    // workaround to get REST working in the case of
    // 1) Based on the request URI , it is possible to find a service name and operation.
    // However, there is no actual service deployed in the synapse ( no  i.e proxy or other)
    // e.g  http://localhost:8280/services/StudentService/students where there  is no proxy
    // service with name StudentService.This is a senario where StudentService is in an external
    // server and it is needed to call it from synapse using the main sequence
    // 2) request is to be injected into  the main sequence  .i.e. http://localhost:8280
    // This method does not cause any performance issue ...
    // Proper fix should be refractoring axis2 RestUtil in a proper way
    /**
     * This reverseProxyMode was introduce to avoid the LB exposing it's own web service when REST call was initiated
     */
    boolean reverseProxyMode = Boolean.parseBoolean(System.getProperty("reverseProxyMode"));
    AxisService axisService = null;
    if (!reverseProxyMode) {
        axisService = requestDispatcher.findService(msgContext);
    }
    boolean isCustomRESTDispatcher = false;
    if (requestURI.matches(NHttpConfiguration.getInstance().getRestUriApiRegex()) || requestURI.matches(NHttpConfiguration.getInstance().getRestUriProxyRegex())) {
        isCustomRESTDispatcher = true;
    }
    if (dispatching || !isCustomRESTDispatcher) {
        if (axisService == null) {
            String defaultSvcName = NHttpConfiguration.getInstance().getStringValue("nhttp.default.service", "__SynapseService");
            axisService = msgContext.getConfigurationContext().getAxisConfiguration().getService(defaultSvcName);
        }
        msgContext.setAxisService(axisService);
        // When receiving rest request axis2 checks whether axis operation is set in the message context to build
        // the request message. Therefore we have to set axis operation before we handed over request to axis
        // engine. If axis operation is already set in the message context take it from there. If not take the
        // axis operation from axis service.
        setAxisOperation(msgContext, axisService);
    } else {
        String multiTenantDispatchService = NHttpConfiguration.getInstance().getRESTDispatchService();
        axisService = msgContext.getConfigurationContext().getAxisConfiguration().getService(multiTenantDispatchService);
        msgContext.setAxisService(axisService);
        setAxisOperation(msgContext, axisService);
    }
}
Also used : AxisService(org.apache.axis2.description.AxisService) EndpointReference(org.apache.axis2.addressing.EndpointReference)

Aggregations

AxisConfiguration (org.apache.axis2.engine.AxisConfiguration)16 SynapseConfiguration (org.apache.synapse.config.SynapseConfiguration)15 OMElement (org.apache.axiom.om.OMElement)13 ConfigurationContext (org.apache.axis2.context.ConfigurationContext)13 Parameter (org.apache.axis2.description.Parameter)11 SynapseEnvironment (org.apache.synapse.core.SynapseEnvironment)10 URI (java.net.URI)9 Axis2SynapseEnvironment (org.apache.synapse.core.axis2.Axis2SynapseEnvironment)9 Test (org.junit.Test)9 EndpointReference (org.apache.axis2.addressing.EndpointReference)8 URI (org.apache.axis2.databinding.types.URI)7 IOException (java.io.IOException)5 SynapseException (org.apache.synapse.SynapseException)5 MalformedURLException (java.net.MalformedURLException)4 Calendar (java.util.Calendar)4 HumanTaskRuntimeException (org.wso2.carbon.humantask.core.engine.runtime.api.HumanTaskRuntimeException)4 InputStream (java.io.InputStream)3 URISyntaxException (java.net.URISyntaxException)3 URL (java.net.URL)3 HashMap (java.util.HashMap)3