Java Code Examples for org.apache.synapse.MessageContext#setProperty()

The following examples show how to use org.apache.synapse.MessageContext#setProperty() . 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 File: BinaryExtractMediator.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
public boolean mediate(MessageContext msgCtx) {
    try {
        log.debug("BinaryExtractMediator Process, with offset: "+offset+" ,length "+length);
        SOAPBody soapBody = msgCtx.getEnvelope().getBody();
        OMElement firstElement = soapBody.getFirstElement();
        log.debug("First Element : "+firstElement.getLocalName());
        log.debug("First Element Text : "+firstElement.getText());
        OMText binaryNode =(OMText) firstElement.getFirstOMChild();
        log.debug("First Element Node Text : "+binaryNode.getText());
        DataHandler dataHandler =(DataHandler) binaryNode.getDataHandler();
        InputStream inputStream = dataHandler.getInputStream();
        byte[] searchByte = new byte[length];
        inputStream.skip(offset - 1);
        int readBytes = inputStream.read(searchByte,0,length);
        String outString = new String(searchByte,binaryEncoding);
        msgCtx.setProperty(variableName,outString);
        log.debug("Set property to MsgCtx, "+variableName+" = "+outString);
        inputStream.close();
    } catch (IOException e) {
        log.error("Excepton on mediation : "+e.getMessage());
    }
    return true;
}
 
Example 2
Source File: APIMgtLatencyStatsHandlerTest.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Test
public void handleResponse() throws Exception {
    PowerMockito.mockStatic(APIUtil.class);
    BDDMockito.given(APIUtil.isAnalyticsEnabled()).willReturn(true);
    SynapseConfiguration synCfg = new SynapseConfiguration();
    org.apache.axis2.context.MessageContext axisMsgCtx = new org.apache.axis2.context.MessageContext();
    AxisConfiguration axisConfig = new AxisConfiguration();
    ConfigurationContext cfgCtx = new ConfigurationContext(axisConfig);
    MessageContext synCtx = new Axis2MessageContext(axisMsgCtx, synCfg,
            new Axis2SynapseEnvironment(cfgCtx, synCfg));
    synCtx.setProperty(APIMgtGatewayConstants.BACKEND_REQUEST_START_TIME, "123456789");
    APIMgtLatencyStatsHandler apiMgtLatencyStatsHandler = new APIMgtLatencyStatsHandler();
    apiMgtLatencyStatsHandler.handleResponse(synCtx);
    long backeEndLatencyTime = Long.parseLong(String.valueOf(synCtx.getProperty(APIMgtGatewayConstants
            .BACKEND_LATENCY)));
    Assert.assertTrue(backeEndLatencyTime <= System.currentTimeMillis());
    Assert.assertTrue(Long.valueOf((Long) synCtx.getProperty(APIMgtGatewayConstants.BACKEND_REQUEST_END_TIME)) <=
            System.currentTimeMillis());
}
 
Example 3
Source File: APIMgtLatencyStatsHandler.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
public boolean handleResponse(MessageContext messageContext) {
    /*
     * The axis2 message context is set here so that the method level logging can access the
     * transport headers
     */
    org.apache.axis2.context.MessageContext axis2MC = ((Axis2MessageContext) messageContext)
            .getAxis2MessageContext();
    org.apache.axis2.context.MessageContext.setCurrentMessageContext(axis2MC);
    if (messageContext.getProperty(APIMgtGatewayConstants.BACKEND_REQUEST_END_TIME) == null) {
        messageContext.setProperty(APIMgtGatewayConstants.BACKEND_REQUEST_END_TIME, System.currentTimeMillis());
        if (APIUtil.isAnalyticsEnabled()) {
            long executionStartTime = Long.parseLong((String) messageContext.getProperty(APIMgtGatewayConstants
                    .BACKEND_REQUEST_START_TIME));
            messageContext.setProperty(APIMgtGatewayConstants.BACKEND_LATENCY, System.currentTimeMillis() -
                    executionStartTime);
        }
    }
    return true;
}
 
Example 4
Source File: APIMgtLatencyStatsHandler.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
private void setSwaggerToMessageContext(MessageContext messageContext) {
    // Read OpenAPI from local entry
    if (openAPI == null && apiUUID != null) {
        synchronized (this) {
            if (openAPI == null) {
                long startTime = System.currentTimeMillis();
                Entry localEntryObj = (Entry) messageContext.getConfiguration().getLocalRegistry().get(apiUUID);
                if (localEntryObj != null) {
                    swagger = localEntryObj.getValue().toString();
                    OpenAPIParser parser = new OpenAPIParser();
                    openAPI = parser.readContents(swagger,
                            null, null).getOpenAPI();
                }
                long endTime = System.currentTimeMillis();
                if (log.isDebugEnabled()) {
                    log.debug("Time to parse the swagger(ms) : " + (endTime - startTime));
                }
            }
        }
    }
    // Add OpenAPI to message context
    messageContext.setProperty(APIMgtGatewayConstants.OPEN_API_OBJECT, openAPI);
    // Add swagger String to message context
    messageContext.setProperty(APIMgtGatewayConstants.OPEN_API_STRING, swagger);
}
 
Example 5
Source File: InboundWebsocketSourceHandler.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
protected void handleWebsocketPassthroughTextFrame(WebSocketFrame frame, MessageContext synCtx) throws AxisFault {
    String endpointName = WebsocketEndpointManager.getInstance().getEndpointName(port, tenantDomain);

    InboundEndpoint endpoint = synCtx.getConfiguration().getInboundEndpoint(endpointName);

    if (endpoint == null) {
        log.error("Cannot find deployed inbound endpoint " + endpointName + "for process request");
        return;
    }

    synCtx.setProperty(InboundWebsocketConstants.WEBSOCKET_TEXT_FRAME_PRESENT, new Boolean(true));
    ((Axis2MessageContext) synCtx).getAxis2MessageContext()
            .setProperty(InboundWebsocketConstants.WEBSOCKET_TEXT_FRAME_PRESENT, new Boolean(true));
    synCtx.setProperty(InboundWebsocketConstants.WEBSOCKET_TEXT_FRAME, frame);
    ((Axis2MessageContext) synCtx).getAxis2MessageContext()
            .setProperty(InboundWebsocketConstants.WEBSOCKET_TEXT_FRAME, frame);

}
 
Example 6
Source File: ThrottleHandlerTest.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Test
public void testMsgDoContinueWhenAllThrottlingLevelsAreNotThrolled() {
    ThrottleDataHolder throttleDataHolder = new ThrottleDataHolder();
    ServiceReferenceHolder.getInstance().setThrottleDataPublisher(new ThrottleDataPublisher());
    ThrottleHandler throttleHandler = new ThrottlingHandlerWrapper(timer, throttleDataHolder, throttleEvaluator);
    MessageContext messageContext = TestUtils.getMessageContextWithAuthContext(apiContext, apiVersion);
    messageContext.setProperty(VERB_INFO_DTO, verbInfoDTO);
    ((Axis2MessageContext) messageContext).getAxis2MessageContext().getProperty(org.apache.axis2.context
            .MessageContext.TRANSPORT_HEADERS);
    AuthenticationContext authenticationContext = (AuthenticationContext) messageContext.getProperty
            (API_AUTH_CONTEXT);
    authenticationContext.setApiTier(throttlingTier);
    messageContext.setProperty(API_AUTH_CONTEXT, authenticationContext);
    //Should continue the message flow if API level, application level, resource level, subscription level,
    //subscription spike level and hard throttling limit levels are not throttled
    Assert.assertTrue(throttleHandler.handleRequest(messageContext));
}
 
Example 7
Source File: JMSReplySenderTest.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
/**
 * Test SendBackNoPayloadTypeByteMessages
 *
 * @throws Exception
 */
@Test
public void testSendBackNoPayloadTypeByteMessages() throws Exception {
    String replyQueueName = "testQueueNoPayloadTypeByte";
    Properties jmsProperties = JMSTestsUtils.getJMSPropertiesForDestination(replyQueueName, PROVIDER_URL, true);
    JMSBrokerController brokerController = new JMSBrokerController(PROVIDER_URL, jmsProperties);
    try {
        brokerController.startProcess();
        Queue replyQueue = brokerController.connect(replyQueueName, true);
        String content = "This is a test";
        BytesMessage message = brokerController.createBytesMessage(content.getBytes());
        CachedJMSConnectionFactory cachedJMSConnectionFactory = new CachedJMSConnectionFactory(jmsProperties);
        MessageContext messageContext = JMSTestsUtils.createMessageContext();
        String correlationID = UUID.randomUUID().toString();
        this.setSOAPEnvelopWithoutTypeByteMessageBody(messageContext, message);
        this.setTransportHeaders(((Axis2MessageContext) messageContext).getAxis2MessageContext(),
                                 JMSConstants.JMS_BYTE_MESSAGE, correlationID);
        messageContext.setProperty(JMSConstants.JMS_COORELATION_ID, correlationID);
        JMSReplySender replySender = new JMSReplySender(replyQueue, cachedJMSConnectionFactory, null, null);
        replySender.sendBack(messageContext);
        Message replyMsg = brokerController.receiveMessage(replyQueue);
        Assert.assertNotNull("The reply message cannot be null", replyMsg);
        Assert.assertEquals("The Message type of received message does not match", JMSConstants.JMS_BYTE_MESSAGE,
                            replyMsg.getJMSType());
    } finally {
        brokerController.disconnect();
        brokerController.stopProcess();
    }
}
 
Example 8
Source File: MITenantInfoConfigurator.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
@Override
public boolean extractTenantInfo(MessageContext messageContext) {
    if (logger.isDebugEnabled()) {
        logger.debug("Extracting Tenant Info...");
    }
    // Micro integrator does not support multi tenancy. It only have super tenant
    String tenantDomain = Constants.SUPER_TENANT_DOMAIN_NAME;
    int tenantId = Constants.SUPER_TENANT_ID;
    messageContext.setProperty("tenant.info.domain", tenantDomain);
    messageContext.setProperty("tenant.info.id", tenantId);
    if (logger.isDebugEnabled()) {
        logger.info("tenant domain: " + tenantDomain + ", tenant id: " + tenantId);
    }
    return true;
}
 
Example 9
Source File: JMSReplySenderTest.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
/**
 * Test SendBackByteMessages
 *
 * @throws Exception
 */
@Test
public void testSendBackByteMessages() throws Exception {
    String replyQueueName = "testQueueReplyBinary";
    Properties jmsProperties = JMSTestsUtils.getJMSPropertiesForDestination(replyQueueName, PROVIDER_URL, true);
    JMSBrokerController brokerController = new JMSBrokerController(PROVIDER_URL, jmsProperties);
    try {
        brokerController.startProcess();
        Queue replyQueue = brokerController.connect(replyQueueName, true);
        String content = "This is a test";
        BytesMessage message = brokerController.createBytesMessage(content.getBytes());
        CachedJMSConnectionFactory cachedJMSConnectionFactory = new CachedJMSConnectionFactory(jmsProperties);
        MessageContext messageContext = JMSTestsUtils.createMessageContext();
        String correlationID = UUID.randomUUID().toString();
        this.setSOAPEnvelopWithBinaryBody(messageContext, message);
        this.setTransportHeaders(((Axis2MessageContext) messageContext).getAxis2MessageContext(),
                                 JMSConstants.JMS_BYTE_MESSAGE, correlationID);
        messageContext.setProperty(JMSConstants.JMS_COORELATION_ID, correlationID);
        JMSReplySender replySender = new JMSReplySender(replyQueue, cachedJMSConnectionFactory, null, null);
        String soapAction = "urn:test";
        ((Axis2MessageContext) messageContext).getAxis2MessageContext().getOptions().setAction(soapAction);
        replySender.sendBack(messageContext);
        Message replyMsg = brokerController.receiveMessage(replyQueue);
        Assert.assertNotNull("The reply message cannot be null", replyMsg);
        Assert.assertEquals("The Message type of received message does not match", JMSConstants.JMS_BYTE_MESSAGE,
                            replyMsg.getJMSType());
        Assert.assertEquals("The Content of received message does not match", content,
                            new String(((ActiveMQBytesMessage) replyMsg).getContent().getData()));
    } finally {
        brokerController.disconnect();
        brokerController.stopProcess();
    }
}
 
Example 10
Source File: JMSReplySenderTest.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
/**
 * Test SendBackTextMessages
 *
 * @throws Exception
 */
@Test
public void testSendBackTextMessages() throws Exception {
    String replyQueueName = "testQueueReplyTxt";
    Properties jmsProperties = JMSTestsUtils.getJMSPropertiesForDestination(replyQueueName, PROVIDER_URL, true);
    JMSBrokerController brokerController = new JMSBrokerController(PROVIDER_URL, jmsProperties);
    try {
        brokerController.startProcess();
        Queue replyQueue = brokerController.connect(replyQueueName, true);
        CachedJMSConnectionFactory cachedJMSConnectionFactory = new CachedJMSConnectionFactory(jmsProperties);
        MessageContext messageContext = JMSTestsUtils.createMessageContext();
        String correlationID = UUID.randomUUID().toString();
        this.setSOAPEnvelopWithTextBody(messageContext);
        this.setTransportHeaders(((Axis2MessageContext) messageContext).getAxis2MessageContext(),
                                 JMSConstants.JMS_TEXT_MESSAGE, correlationID);
        messageContext.setProperty(JMSConstants.JMS_COORELATION_ID, correlationID);
        JMSReplySender replySender = new JMSReplySender(replyQueue, cachedJMSConnectionFactory, null, null);
        String soapAction = "urn:test";
        ((Axis2MessageContext) messageContext).getAxis2MessageContext().setServerSide(true);
        ((Axis2MessageContext) messageContext).getAxis2MessageContext()
                .setProperty(BaseConstants.SOAPACTION, soapAction);
        replySender.sendBack(messageContext);
        Message replyMsg = brokerController.receiveMessage(replyQueue);
        Assert.assertNotNull("The reply message cannot be null", replyMsg);
        Assert.assertEquals("The Message type of received message does not match", JMSConstants.JMS_TEXT_MESSAGE,
                            replyMsg.getJMSType());
        Assert.assertEquals("The Content of received message does not match", "TestSendBack",
                            ((ActiveMQTextMessage) replyMsg).getText());
    } finally {
        brokerController.disconnect();
        brokerController.stopProcess();
    }
}
 
Example 11
Source File: DataServiceResource.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
@Override
public boolean invoke(MessageContext msgCtx) {
    buildMessage(msgCtx);
    if (serviceAdmin == null) {
        serviceAdmin = Utils.getServiceAdmin(msgCtx);
    }
    String param = Utils.getQueryParameter(msgCtx, "dataServiceName");

    try {
        if (param != null) {
            // data-service specified by name
            populateDataServiceByName(msgCtx, param);
        } else {
            // list of all data-services
            populateDataServiceList(msgCtx);
        }
    } catch (Exception exception) {
        log.error("Error while populating service: ", exception);
        msgCtx.setProperty(Constants.HTTP_STATUS_CODE, Constants.INTERNAL_SERVER_ERROR);
    }

    org.apache.axis2.context.MessageContext axis2MessageContext = ((Axis2MessageContext) msgCtx)
            .getAxis2MessageContext();

    axis2MessageContext.removeProperty(Constants.NO_ENTITY_BODY);
    return true;
}
 
Example 12
Source File: InboundWebsocketSourceHandler.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
public org.apache.synapse.MessageContext getSynapseMessageContext(String tenantDomain) throws AxisFault {
    MessageContext synCtx = createSynapseMessageContext(tenantDomain);
    synCtx.setProperty(SynapseConstants.IS_INBOUND, true);
    ((Axis2MessageContext) synCtx).getAxis2MessageContext().setProperty(SynapseConstants.IS_INBOUND, true);
    synCtx.setProperty(InboundEndpointConstants.INBOUND_ENDPOINT_RESPONSE_WORKER, responseSender);
    ((Axis2MessageContext) synCtx).getAxis2MessageContext()
            .setProperty(InboundEndpointConstants.INBOUND_ENDPOINT_RESPONSE_WORKER, responseSender);
    synCtx.setProperty(InboundWebsocketConstants.WEBSOCKET_SOURCE_HANDLER_CONTEXT,
                       wrappedContext.getChannelHandlerContext());
    ((Axis2MessageContext) synCtx).getAxis2MessageContext()
            .setProperty(InboundWebsocketConstants.WEBSOCKET_SOURCE_HANDLER_CONTEXT,
                         wrappedContext.getChannelHandlerContext());
    if (outflowDispatchSequence != null) {
        synCtx.setProperty(InboundWebsocketConstants.WEBSOCKET_OUTFLOW_DISPATCH_SEQUENCE, outflowDispatchSequence);
        ((Axis2MessageContext) synCtx).getAxis2MessageContext()
                .setProperty(InboundWebsocketConstants.WEBSOCKET_OUTFLOW_DISPATCH_SEQUENCE,
                             outflowDispatchSequence);
    }
    if (outflowErrorSequence != null) {
        synCtx.setProperty(InboundWebsocketConstants.WEBSOCKET_OUTFLOW_DISPATCH_FAULT_SEQUENCE,
                           outflowErrorSequence);
        ((Axis2MessageContext) synCtx).getAxis2MessageContext()
                .setProperty(InboundWebsocketConstants.WEBSOCKET_OUTFLOW_DISPATCH_FAULT_SEQUENCE,
                             outflowErrorSequence);
    }
    synCtx.setProperty(InboundWebsocketConstants.WEBSOCKET_SUBSCRIBER_PATH, subscriberPath.toString());
    return synCtx;
}
 
Example 13
Source File: APIAuthenticationHandlerTestCase.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Test
public void testHandleRequestSecurityException() {
    SynapseEnvironment synapseEnvironment = Mockito.mock(SynapseEnvironment.class);
    MessageContext messageContext = Mockito.mock(Axis2MessageContext.class);
    org.apache.axis2.context.MessageContext axis2MsgCntxt = Mockito.mock(org.apache.axis2.context.MessageContext.class);
    Mockito.when(((Axis2MessageContext) messageContext).getAxis2MessageContext()).thenReturn(axis2MsgCntxt);
    APIAuthenticationHandler apiAuthenticationHandler = createAPIAuthenticationHandlerForExceptionTest();
    apiAuthenticationHandler.init(synapseEnvironment);

    Options options = Mockito.mock(Options.class);
    Mockito.when(options.getMessageId()).thenReturn("1");
    Mockito.when(axis2MsgCntxt.getOptions()).thenReturn(options);

    TreeMap transportHeaders = new TreeMap();
    transportHeaders.put(APIConstants.USER_AGENT, "");
    transportHeaders.put(APIMgtGatewayConstants.AUTHORIZATION, "gsu64r874tcin7ry8oe");
    messageContext.setProperty(RESTConstants.REST_FULL_REQUEST_PATH, "");
    Mockito.when(axis2MsgCntxt.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS)).thenReturn(transportHeaders);
    axis2MsgCntxt.setProperty(APIMgtGatewayConstants.REQUEST_RECEIVED_TIME, null);
    Assert.assertFalse(apiAuthenticationHandler.handleRequest(messageContext));

    Mockito.when(messageContext.isDoingGET()).thenReturn(true);

    Assert.assertFalse(apiAuthenticationHandler.handleRequest(messageContext));

    Assert.assertTrue(apiAuthenticationHandler.isAnalyticsEnabled());

}
 
Example 14
Source File: ThreatExceptionHandler.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * The method sets message context properties for error message.
 *
 * @param messageContext This message context contains the request message properties of the relevant API which was
 *                       enabled a Validator message mediation in flow.
 * @param errorMessage   specific error message for each validator.
 */
public static void handleException(MessageContext messageContext, String errorMessage) {
    messageContext.setProperty(ThreatProtectorConstants.STATUS, true);
    messageContext.setProperty(ThreatProtectorConstants.ERROR_CODE,
            ThreatProtectorConstants.HTTP_HEADER_THREAT_CODE);
    messageContext.setProperty(ThreatProtectorConstants.ERROR_MESSAGE, errorMessage);
    ((Axis2MessageContext) messageContext).getAxis2MessageContext().setProperty(
            ThreatProtectorConstants.HTTP_SC, ThreatProtectorConstants.HTTP_SC_CODE);
    throw new SynapseException(errorMessage);
}
 
Example 15
Source File: ThrottleHandler.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
private String getNextAccessTimeString(MessageContext messageContext) {
    Object timestampOb = messageContext.getProperty(APIThrottleConstants.THROTTLED_NEXT_ACCESS_TIMESTAMP);
    if (timestampOb != null) {
        long timestamp = (Long) timestampOb;
        SimpleDateFormat formatUTC = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ssZ");
        formatUTC.setTimeZone(TimeZone.getTimeZone(APIThrottleConstants.UTC));
        Date date = new Date(timestamp);
        String nextAccessTimeString = formatUTC.format(date) + " " + APIThrottleConstants.UTC;
        messageContext.setProperty(APIThrottleConstants.THROTTLED_NEXT_ACCESS_TIME, nextAccessTimeString);
        return nextAccessTimeString;
    }
    return null;
}
 
Example 16
Source File: ThrottleHandler.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
private boolean isHardLimitThrottled(MessageContext synCtx, AuthenticationContext authContext, String apiContext,
                                     String apiVersion) {
    boolean status = false;
    if (StringUtils.isNotEmpty(sandboxMaxCount) || StringUtils.isNotEmpty(productionMaxCount)) {
        ThrottleContext hardThrottleContext = throttle.getThrottleContext(APIThrottleConstants.HARD_THROTTLING_CONFIGURATION);
        try {
            org.apache.axis2.context.MessageContext axis2MC = ((Axis2MessageContext) synCtx).getAxis2MessageContext();
            ConfigurationContext cc = axis2MC.getConfigurationContext();
            apiContext = apiContext != null ? apiContext : "";
            apiVersion = apiVersion != null ? apiVersion : "";

            if (hardThrottleContext != null && authContext.getKeyType() != null) {
                String throttleKey = apiContext + ':' + apiVersion + ':' + authContext.getKeyType();
                AccessInformation info = null;
                if (isClusteringEnabled()) {
                    hardThrottleContext.setConfigurationContext(cc);
                }

                if (APIConstants.API_KEY_TYPE_PRODUCTION.equals(authContext.getKeyType())) {
                        hardThrottleContext.setThrottleId(id + APIThrottleConstants.PRODUCTION_HARD_LIMIT);
                    info = getAccessInformation(hardThrottleContext, throttleKey, APIThrottleConstants.PRODUCTION_HARD_LIMIT);
                } else if (APIConstants.API_KEY_TYPE_SANDBOX.equals(authContext.getKeyType())) {
                    hardThrottleContext.setThrottleId(id + APIThrottleConstants.SANDBOX_HARD_LIMIT);
                    info = getAccessInformation(hardThrottleContext, throttleKey, APIThrottleConstants.SANDBOX_HARD_LIMIT);
                }

                if (log.isDebugEnabled()) {
                    log.debug("Throttle by hard limit " + throttleKey);
                    log.debug("Allowed = " + (info != null ? info.isAccessAllowed() : "false"));
                }

                if (info != null && !info.isAccessAllowed()) {
                    synCtx.setProperty(APIThrottleConstants.THROTTLED_OUT_REASON, APIThrottleConstants
                            .HARD_LIMIT_EXCEEDED);
                    log.info("Hard Throttling limit exceeded.");
                    status = true;
                }
            }

        } catch (ThrottleException e) {
            log.warn("Exception occurred while performing role " +
                     "based throttling", e);
            synCtx.setProperty(APIThrottleConstants.THROTTLED_OUT_REASON, APIThrottleConstants.HARD_LIMIT_EXCEEDED);
            status = true;
        }
    }
    return status;
}
 
Example 17
Source File: TenantAwareLoadBalanceEndpoint.java    From attic-stratos with Apache License 2.0 4 votes vote down vote up
private void throwSynapseException(MessageContext synCtx, int errorCode, String errorMessage) {
    synCtx.setProperty(SynapseConstants.ERROR_CODE, errorCode);
    synCtx.setProperty(SynapseConstants.ERROR_MESSAGE, errorMessage);
    throw new SynapseException(errorMessage);
}
 
Example 18
Source File: APIMgtGoogleAnalyticsTrackingHandler.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
/**
    * Track a page view, updates all the cookies and campaign tracker, makes a
    * server side request to Google Analytics and writes the transparent gif
    * byte data to the response.
    *
    * @throws Exception
    */
   private void trackPageView(MessageContext msgCtx) throws Exception {
       @SuppressWarnings("rawtypes")
       Map headers = (Map) ((Axis2MessageContext) msgCtx).getAxis2MessageContext()
                                              .getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS);

       String host = (String) headers.get(HttpHeaders.HOST);
       String domainName = host;
       if (host != null && host.indexOf(":") != -1) {
           domainName = host.substring(0, host.indexOf(":"));
       }
       if (isEmpty(domainName)) {
           domainName = "";
       }

       // Get client IP
       String xForwardedFor = (String) headers.get(APIMgtUsagePublisherConstants.X_FORWARDED_FOR_HEADER);
       String userIP;
       if(xForwardedFor == null || xForwardedFor.isEmpty()) {
           userIP = (String) ((Axis2MessageContext) msgCtx).getAxis2MessageContext()
                   .getProperty(org.apache.axis2.context.MessageContext.REMOTE_ADDR);
       } else {
           userIP = xForwardedFor.split(",")[0];
       }
       String path = (String) msgCtx.getProperty(RESTConstants.REST_FULL_REQUEST_PATH);
       String documentPath = path;
       if (isEmpty(documentPath)) {
           documentPath = "";
       }

       String account = config.googleAnalyticsTrackingID;

       String userAgent = (String) headers.get(HttpHeaders.USER_AGENT);
       if (isEmpty(userAgent)) {
           userAgent = "";
       }

       String visitorId = getVisitorId(account, userAgent, msgCtx);

       /* Set the visitorId in MessageContext */
       msgCtx.setProperty(COOKIE_NAME, visitorId);

       String httpMethod =
                           (String) ((Axis2MessageContext) msgCtx).getAxis2MessageContext()
                                                                  .getProperty(Constants.Configuration.HTTP_METHOD);

	GoogleAnalyticsData data = new GoogleAnalyticsData
               .DataBuilder(account, GOOGLE_ANALYTICS_TRACKER_VERSION , visitorId , GoogleAnalyticsConstants.HIT_TYPE_PAGEVIEW)
               .setDocumentPath(documentPath)
               .setDocumentHostName(domainName)
               .setDocumentTitle(httpMethod)
               .setSessionControl("end")
               .setCacheBuster(APIMgtGoogleAnalyticsUtils.getCacheBusterId())
               .setIPOverride(userIP)
               .build();

       String payload = GoogleAnalyticsDataPublisher.buildPayloadString(data);
       if (log.isDebugEnabled()) {
           log.debug("Publishing https GET from gateway to Google analytics" + " with ID: " + msgCtx.getMessageID()
                   + " started at " + new SimpleDateFormat("[yyyy.MM.dd HH:mm:ss,SSS zzz]").format(new Date()));
       }
       GoogleAnalyticsDataPublisher.publishGET(payload, userAgent, false);
       if (log.isDebugEnabled()) {
           log.debug("Publishing https GET from gateway to Google analytics" + " with ID: " + msgCtx.getMessageID()
                   + " ended at " + new SimpleDateFormat("[yyyy.MM.dd HH:mm:ss,SSS zzz]").format(new Date()));
       }
}
 
Example 19
Source File: JWTValidator.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
/**
 * Authenticates the given request with a JWT token to see if an API consumer is allowed to access
 * a particular API or not.
 *
 * @param jwtToken The JWT token sent with the API request
 * @param synCtx   The message to be authenticated
 * @param openAPI  The OpenAPI object of the invoked API
 * @return an AuthenticationContext object which contains the authentication information
 * @throws APISecurityException in case of authentication failure
 */
@MethodStats
public AuthenticationContext authenticate(SignedJWT jwtToken, MessageContext synCtx, OpenAPI openAPI)
        throws APISecurityException {

    String tokenSignature = jwtToken.getSignature().toString();
    String apiContext = (String) synCtx.getProperty(RESTConstants.REST_API_CONTEXT);
    String apiVersion = (String) synCtx.getProperty(RESTConstants.SYNAPSE_REST_API_VERSION);
    String httpMethod = (String) ((Axis2MessageContext) synCtx).getAxis2MessageContext().
            getProperty(Constants.Configuration.HTTP_METHOD);
    String matchingResource = (String) synCtx.getProperty(APIConstants.API_ELECTED_RESOURCE);

    String jwtHeader = jwtToken.getHeader().toString();
    if (RevokedJWTDataHolder.isJWTTokenSignatureExistsInRevokedMap(tokenSignature)) {
        if (log.isDebugEnabled()) {
            log.debug("Token retrieved from the revoked jwt token map. Token: " + GatewayUtils.
                    getMaskedToken(jwtHeader));
        }
        log.error("Invalid JWT token. " + GatewayUtils.getMaskedToken(jwtHeader));
        throw new APISecurityException(APISecurityConstants.API_AUTH_INVALID_CREDENTIALS,
                "Invalid JWT token");
    }
    String cacheKey = GatewayUtils
            .getAccessTokenCacheKey(tokenSignature, apiContext, apiVersion, matchingResource, httpMethod);

    JWTValidationInfo jwtValidationInfo = getJwtValidationInfo(jwtToken, cacheKey);

    if (jwtValidationInfo != null) {
        if (jwtValidationInfo.isValid()) {
            // validate scopes
            validateScopes(synCtx, openAPI, jwtValidationInfo);
            // Validate subscriptions


            APIKeyValidationInfoDTO apiKeyValidationInfoDTO = null;
            
            log.debug("Begin subscription validation via Key Manager");
            apiKeyValidationInfoDTO = validateSubscriptionUsingKeyManager(synCtx, jwtValidationInfo);

            if (log.isDebugEnabled()) {
                log.debug("Subscription validation via Key Manager. Status: "
                        + apiKeyValidationInfoDTO.isAuthorized());
            }
            if (apiKeyValidationInfoDTO.isAuthorized()) {
                /*
                 * Set api.ut.apiPublisher of the subscribed api to the message context.
                 * This is necessary for the functionality of Publisher alerts.
                 * */
                synCtx.setProperty(APIMgtGatewayConstants.API_PUBLISHER, apiKeyValidationInfoDTO.getApiPublisher());
                log.debug("JWT authentication successful.");
            } else {
                log.debug(
                        "User is NOT authorized to access the Resource. API Subscription validation " + "failed.");
                throw new APISecurityException(apiKeyValidationInfoDTO.getValidationStatus(),
                        "User is NOT authorized to access the Resource. API Subscription validation " + "failed.");
            }
        
            log.debug("JWT authentication successful.");
            String endUserToken = null;
            try {
                if (jwtGenerationEnabled) {
                    JWTInfoDto jwtInfoDto =
                            GatewayUtils
                                    .generateJWTInfoDto(jwtValidationInfo, null, apiKeyValidationInfoDTO, synCtx);
                    endUserToken = generateAndRetrieveJWTToken(tokenSignature, jwtInfoDto);
                }
                return GatewayUtils
                        .generateAuthenticationContext(tokenSignature, jwtValidationInfo, null,
                                apiKeyValidationInfoDTO,
                                getApiLevelPolicy(), endUserToken, true);
            } catch (ParseException e) {
                throw new APISecurityException(APISecurityConstants.API_AUTH_GENERAL_ERROR,
                        APISecurityConstants.API_AUTH_GENERAL_ERROR_MESSAGE);
            }
        } else {
            throw new APISecurityException(jwtValidationInfo.getValidationCode(),
                    APISecurityConstants.getAuthenticationFailureMessage(jwtValidationInfo.getValidationCode()));
        }
    } else {
        throw new APISecurityException(APISecurityConstants.API_AUTH_GENERAL_ERROR,
                APISecurityConstants.API_AUTH_GENERAL_ERROR_MESSAGE);
    }
}
 
Example 20
Source File: APIThrottleHandler.java    From carbon-apimgt with 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);
    }