Java Code Examples for org.apache.synapse.transport.passthru.util.RelayUtils

The following examples show how to use org.apache.synapse.transport.passthru.util.RelayUtils. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: micro-integrator   Source File: ODataPassThroughHandler.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public boolean handleRequestInFlow(MessageContext messageContext) {
    try {
        org.apache.axis2.context.MessageContext axis2MessageContext =
                ((Axis2MessageContext) messageContext).getAxis2MessageContext();
        Object isODataService = axis2MessageContext.getProperty("IsODataService");
        // In this if block we are skipping proxy services, inbound related message contexts & api.
        if (axis2MessageContext.getProperty("TransportInURL") != null && isODataService != null) {
            RelayUtils.buildMessage(axis2MessageContext);
            ODataServletRequest request = new ODataServletRequest(axis2MessageContext);
            ODataServletResponse response = new ODataServletResponse(axis2MessageContext);
            ODataEndpoint.process(request, response);
            setContent(axis2MessageContext, response);
            setHeaders(axis2MessageContext, response);
            messageContext.setTo(null);
            messageContext.setResponse(true);
            Axis2Sender.sendBack(messageContext);
        }
        return true;
    } catch (Exception e) {
        this.handleException("Error occurred in integrator handler.", e, messageContext);
        return true;
    }
}
 
Example 2
Source Project: micro-integrator   Source File: APIResource.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Builds the message by consuming the input stream.
 *
 * @param synCtx the Synapse Message Context
 */
public final void buildMessage(MessageContext synCtx) {
    try {
        RelayUtils.buildMessage(((Axis2MessageContext) synCtx).getAxis2MessageContext(), false);
    } catch (Exception e) {
        throw new SynapseException("Error while building the message. " + e.getMessage(), e);
    }
}
 
Example 3
Source Project: carbon-apimgt   Source File: LogsHandler.java    License: Apache License 2.0 5 votes vote down vote up
private long buildRequestMessage(org.apache.synapse.MessageContext messageContext) {
    long requestSize = 0;
    org.apache.axis2.context.MessageContext axis2MC = ((Axis2MessageContext) messageContext)
            .getAxis2MessageContext();
    Map headers = (Map) axis2MC.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS);
    String contentLength = (String) headers.get(HttpHeaders.CONTENT_LENGTH);
    if (contentLength != null) {
        requestSize = Integer.parseInt(contentLength);
    } else {
        // When chunking is enabled
        try {
            RelayUtils.buildMessage(axis2MC);
        } catch (IOException | XMLStreamException ex) {
            // In case of an exception, it won't be propagated up,and set response size to 0
            log.error(REQUEST_BODY_SIZE_ERROR, ex);
        }
        SOAPEnvelope env = messageContext.getEnvelope();
        if (env != null) {
            SOAPBody soapbody = env.getBody();
            if (soapbody != null) {
                byte[] size = soapbody.toString().getBytes(Charset.defaultCharset());
                requestSize = size.length;
            }

        }
    }
    return requestSize;
}
 
Example 4
Source Project: carbon-apimgt   Source File: LogsHandler.java    License: Apache License 2.0 5 votes vote down vote up
private long buildResponseMessage(org.apache.synapse.MessageContext messageContext) {
    long responseSize = 0;
    org.apache.axis2.context.MessageContext axis2MC = ((Axis2MessageContext) messageContext)
            .getAxis2MessageContext();
    Map headers = (Map) axis2MC.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS);
    String contentLength = (String) headers.get(HttpHeaders.CONTENT_LENGTH);
    if (contentLength != null) {
        responseSize = Integer.parseInt(contentLength);
    } else {
        // When chunking is enabled
        try {
            RelayUtils.buildMessage(axis2MC);
        } catch (IOException | XMLStreamException ex) {
            // In case of an exception, it won't be propagated up,and set response size to 0
            log.error(REQUEST_BODY_SIZE_ERROR, ex);
        }
    }
    SOAPEnvelope env = messageContext.getEnvelope();
    if (env != null) {
        SOAPBody soapbody = env.getBody();
        if (soapbody != null) {
            byte[] size = soapbody.toString().getBytes(Charset.defaultCharset());
            responseSize = size.length;
        }

    }
    return responseSize;

}
 
Example 5
Source Project: carbon-apimgt   Source File: BotDetectionMediator.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public boolean mediate(MessageContext messageContext) {
    org.apache.axis2.context.MessageContext msgContext = ((Axis2MessageContext) messageContext).
            getAxis2MessageContext();

    String clientIP = DataPublisherUtil.getClientIp(msgContext);
    if (isThrottledOut(clientIP)) {
        messageContext.setProperty("BOT_THROTTLED_OUT", true);
        messageContext.setProperty("BOT_IP", clientIP);
        return true;
    }
    String messageBody;
    long currentTime = System.currentTimeMillis();
    String messageId = messageContext.getMessageID();
    String apiMethod = (String) msgContext.getProperty("HTTP_METHOD");
    try {
        RelayUtils.buildMessage(msgContext);
        SOAPEnvelope messageEnvelop = msgContext.getEnvelope();
        if (messageEnvelop != null && messageEnvelop.getBody() != null) {
            messageBody = String.valueOf(messageEnvelop.getBody());
        } else {
            messageBody = "Empty Message";
        }
    } catch (Exception e) {
        messageBody = "Malformed Message";
    }

    String headerSet = getPassedHeaderSet(msgContext);

    log.info(String.format("MessageId : %s | Request Method : %s | Message Body : %s | client Ip : %s | " +
            "Headers set : %s", messageId, apiMethod, messageBody, clientIP, headerSet));

    /**
     * check whether analytics enabled or not
     */
    if (!enabled) {
        return true;
    }

    BotDataDTO botDataDTO = new BotDataDTO();
    botDataDTO.setCurrentTime(currentTime);
    botDataDTO.setMessageID(messageId);
    botDataDTO.setApiMethod(apiMethod);
    botDataDTO.setHeaderSet(headerSet);
    botDataDTO.setMessageBody(messageBody);
    botDataDTO.setClientIp(clientIP);
    publisher.publishEvent(botDataDTO);
    return true;
}
 
Example 6
Source Project: carbon-apimgt   Source File: APIAuthenticationHandler.java    License: Apache License 2.0 4 votes vote down vote up
private void handleAuthFailure(MessageContext messageContext, APISecurityException e) {
    messageContext.setProperty(SynapseConstants.ERROR_CODE, e.getErrorCode());
    messageContext.setProperty(SynapseConstants.ERROR_MESSAGE,
            APISecurityConstants.getAuthenticationFailureMessage(e.getErrorCode()));
    messageContext.setProperty(SynapseConstants.ERROR_EXCEPTION, e);

    Mediator sequence = messageContext.getSequence(APISecurityConstants.API_AUTH_FAILURE_HANDLER);

    //Setting error description which will be available to the handler
    String errorDetail = APISecurityConstants.getFailureMessageDetailDescription(e.getErrorCode(), e.getMessage());
    // if custom auth header is configured, the error message should specify its name instead of default value
    if (e.getErrorCode() == APISecurityConstants.API_AUTH_MISSING_CREDENTIALS) {
        errorDetail =
                APISecurityConstants.getFailureMessageDetailDescription(e.getErrorCode(), e.getMessage()) + "'"
                        + authorizationHeader + " : Bearer ACCESS_TOKEN' or '" + authorizationHeader +
                        " : Basic ACCESS_TOKEN' or 'apikey: API_KEY'" ;
    }
    messageContext.setProperty(SynapseConstants.ERROR_DETAIL, errorDetail);

    // By default we send a 401 response back
    org.apache.axis2.context.MessageContext axis2MC = ((Axis2MessageContext) messageContext).
            getAxis2MessageContext();
    // This property need to be set to avoid sending the content in pass-through pipe (request message)
    // as the response.
    axis2MC.setProperty(PassThroughConstants.MESSAGE_BUILDER_INVOKED, Boolean.TRUE);
    try {
        RelayUtils.consumeAndDiscardMessage(axis2MC);
    } catch (AxisFault axisFault) {
        //In case of an error it is logged and the process is continued because we're setting a fault message in the payload.
        log.error("Error occurred while consuming and discarding the message", axisFault);
    }
    axis2MC.setProperty(Constants.Configuration.MESSAGE_TYPE, "application/soap+xml");
    int status;
    if (e.getErrorCode() == APISecurityConstants.API_AUTH_GENERAL_ERROR ||
            e.getErrorCode() == APISecurityConstants.API_AUTH_MISSING_OPEN_API_DEF) {
        status = HttpStatus.SC_INTERNAL_SERVER_ERROR;
    } else if (e.getErrorCode() == APISecurityConstants.API_AUTH_INCORRECT_API_RESOURCE ||
            e.getErrorCode() == APISecurityConstants.API_AUTH_FORBIDDEN ||
            e.getErrorCode() == APISecurityConstants.INVALID_SCOPE) {
        status = HttpStatus.SC_FORBIDDEN;
    } else {
        status = HttpStatus.SC_UNAUTHORIZED;
        Map<String, String> headers =
                (Map) axis2MC.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS);
        if (headers != null) {
            headers.put(HttpHeaders.WWW_AUTHENTICATE, getAuthenticatorsChallengeString() +
                    ", error=\"invalid_token\"" +
                    ", error_description=\"The access token expired\"");
            axis2MC.setProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS, headers);
        }
    }

    messageContext.setProperty(APIMgtGatewayConstants.HTTP_RESPONSE_STATUS_CODE, status);
    // Invoke the custom error handler specified by the user
    if (sequence != null && !sequence.mediate(messageContext)) {
        // If needed user should be able to prevent the rest of the fault handling
        // logic from getting executed
        return;
    }

    if (messageContext.isDoingPOX() || messageContext.isDoingGET()) {
        setFaultPayload(messageContext, e);
    } else {
        setSOAPFault(messageContext, e);
    }
    sendFault(messageContext, status);
}
 
Example 7
Source Project: carbon-apimgt   Source File: GraphQLAPIHandler.java    License: Apache License 2.0 4 votes vote down vote up
public boolean handleRequest(MessageContext messageContext) {
    try {
        String payload;
        Parser parser = new Parser();

        org.apache.axis2.context.MessageContext axis2MC = ((Axis2MessageContext) messageContext).
                getAxis2MessageContext();
        String requestPath = messageContext.getProperty(REST_SUB_REQUEST_PATH).toString();
        if (requestPath != null && !requestPath.isEmpty()) {
            String[] queryParams = ((Axis2MessageContext) messageContext).getProperties().
                    get(REST_SUB_REQUEST_PATH).toString().split(QUERY_PATH_STRING);
            if (queryParams.length > 1) {
                payload = URLDecoder.decode(queryParams[1], UNICODE_TRANSFORMATION_FORMAT);
            } else {
                RelayUtils.buildMessage(axis2MC);
                OMElement body = axis2MC.getEnvelope().getBody().getFirstElement();
                if (body != null && body.getFirstElement() != null) {
                    payload = body.getFirstElement().getText();
                } else {
                    if (log.isDebugEnabled()) {
                        log.debug("Invalid query parameter " + queryParams[0]);
                    }
                    handleFailure(messageContext, "Invalid query parameter");
                    return false;
                }
            }
            messageContext.setProperty(APIConstants.GRAPHQL_PAYLOAD, payload);
        } else {
            handleFailure(messageContext, "Request path cannot be empty");
            return false;
        }

        // Validate payload with graphQLSchema
        Document document = parser.parseDocument(payload);

        if (validatePayloadWithSchema(messageContext, document)) {
            supportForBasicAndAuthentication(messageContext);

            // Extract the operation type and operations from the payload
            for (Definition definition : document.getDefinitions()) {
                if (definition instanceof OperationDefinition) {
                    OperationDefinition operation = (OperationDefinition) definition;
                    if (operation.getOperation() != null) {
                        String httpVerb = ((Axis2MessageContext) messageContext).getAxis2MessageContext().
                                getProperty(HTTP_METHOD).toString();
                        messageContext.setProperty(HTTP_VERB, httpVerb);
                        ((Axis2MessageContext) messageContext).getAxis2MessageContext().setProperty(HTTP_METHOD,
                                operation.getOperation().toString());
                        String operationList = getOperationList(messageContext, operation);
                        messageContext.setProperty(APIConstants.API_ELECTED_RESOURCE, operationList);
                        if (log.isDebugEnabled()) {
                            log.debug("Operation list has been successfully added to elected property");
                        }
                        return true;
                    }
                } else {
                    handleFailure(messageContext, "Operation definition cannot be empty");
                    return false;
                }
            }
        } else {
            return false;
        }
    } catch (IOException | XMLStreamException | InvalidSyntaxException e) {
        log.error(e.getMessage());
        handleFailure(messageContext, e.getMessage());
    }
    return false;
}
 
Example 8
Source Project: carbon-apimgt   Source File: APIThrottleHandler.java    License: Apache License 2.0 4 votes vote down vote up
private void handleThrottleOut(MessageContext messageContext) {

        String errorMessage = null;
        String errorDescription = null;
        int errorCode = -1;
        int httpErrorCode = -1;

        if (APIThrottleConstants.HARD_LIMIT_EXCEEDED.equals(
                messageContext.getProperty(APIThrottleConstants.THROTTLED_OUT_REASON))) {
            errorCode = APIThrottleConstants.HARD_LIMIT_EXCEEDED_ERROR_CODE;
            errorMessage = "API Limit Reached";
            errorDescription = "API not accepting requests";
            // It it's a hard limit exceeding, we tell it as service not being available.
            httpErrorCode = HttpStatus.SC_SERVICE_UNAVAILABLE;
        } else if (APIThrottleConstants.API_LIMIT_EXCEEDED
                .equals(messageContext.getProperty(APIThrottleConstants.THROTTLED_OUT_REASON))) {
            errorCode = APIThrottleConstants.API_THROTTLE_OUT_ERROR_CODE;
            errorMessage = "Message throttled out";
            // By default we send a 429 response back
            httpErrorCode = APIThrottleConstants.SC_TOO_MANY_REQUESTS;
            errorDescription = "You have exceeded your quota";
        } else if (APIThrottleConstants.RESOURCE_LIMIT_EXCEEDED
                .equals(messageContext.getProperty(APIThrottleConstants.THROTTLED_OUT_REASON))) {
            errorCode = APIThrottleConstants.RESOURCE_THROTTLE_OUT_ERROR_CODE;
            errorMessage = "Message throttled out";
            // By default we send a 429 response back
            httpErrorCode = APIThrottleConstants.SC_TOO_MANY_REQUESTS;
            errorDescription = "You have exceeded your quota";
        } else {
            errorCode = APIThrottleConstants.APPLICATION_THROTTLE_OUT_ERROR_CODE;
            errorMessage = "Message throttled out";
            // By default we send a 429 response back
            httpErrorCode = APIThrottleConstants.SC_TOO_MANY_REQUESTS;
            errorDescription = "You have exceeded your quota";
        }

        messageContext.setProperty(SynapseConstants.ERROR_CODE, errorCode);
        messageContext.setProperty(SynapseConstants.ERROR_MESSAGE, errorMessage);
        Mediator sequence = messageContext.getSequence(APIThrottleConstants.API_THROTTLE_OUT_HANDLER);

        // Invoke the custom error handler specified by the user
        if (sequence != null && !sequence.mediate(messageContext)) {
            // If needed user should be able to prevent the rest of the fault handling
            // logic from getting executed
            return;
        }
        org.apache.axis2.context.MessageContext axis2MC = ((Axis2MessageContext) messageContext).
                getAxis2MessageContext();
        // This property need to be set to avoid sending the content in pass-through pipe (request message)
        // as the response.
        axis2MC.setProperty(PassThroughConstants.MESSAGE_BUILDER_INVOKED, Boolean.TRUE);
        try {
            RelayUtils.consumeAndDiscardMessage(axis2MC);
        } catch (AxisFault axisFault) {
            //In case of an error it is logged and the process is continued because we're setting a fault message in the payload.
            log.error("Error occurred while consuming and discarding the message", axisFault);
        }

        if (messageContext.isDoingPOX() || messageContext.isDoingGET()) {
            Utils.setFaultPayload(messageContext, getFaultPayload(errorCode, errorMessage, errorDescription));
        } else {
            setSOAPFault(messageContext, errorMessage, errorDescription);
        }

        sendFault(messageContext, httpErrorCode);
    }
 
Example 9
protected void buildMessage(org.apache.axis2.context.MessageContext axis2MessageContext) throws IOException,
        XMLStreamException {
    RelayUtils.buildMessage(axis2MessageContext);
}