Java Code Examples for org.wso2.carbon.apimgt.impl.utils.APIUtil#isAnalyticsEnabled()

The following examples show how to use org.wso2.carbon.apimgt.impl.utils.APIUtil#isAnalyticsEnabled() . 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: WebsocketHandler.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {

    if ((msg instanceof CloseWebSocketFrame) || (msg instanceof PongWebSocketFrame)) {
        //if the inbound frame is a closed frame, throttling, analytics will not be published.
        outboundHandler().write(ctx, msg, promise);

    } else if (msg instanceof WebSocketFrame) {
        if (isAllowed(ctx, (WebSocketFrame) msg)) {
            outboundHandler().write(ctx, msg, promise);
            // publish analytics events if analytics is enabled
            if (APIUtil.isAnalyticsEnabled()) {
                String clientIp = getClientIp(ctx);
                inboundHandler().publishRequestEvent(clientIp, true);
            }
        } else {
            if (log.isDebugEnabled()){
                log.debug("Outbound Websocket frame is throttled. " + ctx.channel().toString());
            }
        }
    } else {
        outboundHandler().write(ctx, msg, promise);
    }
}
 
Example 2
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 3
Source File: BotDetectionDataApiServiceImpl.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * Get all bot detected data
 *
 * @param messageContext
 * @return list of all bot detected data
 * @throws APIManagementException
 */
public Response getBotDetectionData(MessageContext messageContext) throws APIManagementException {

    if (APIUtil.isAnalyticsEnabled()) {
        APIAdmin apiAdmin = new APIAdminImpl();
        List<BotDetectionData> botDetectionDataList = apiAdmin.retrieveBotDetectionData();
        BotDetectionDataListDTO listDTO = BotDetectionMappingUtil.fromBotDetectionModelToDTO(botDetectionDataList);
        return Response.ok().entity(listDTO).build();
    } else {
        throw new APIManagementException("Analytics Not Enabled",
                ExceptionCodes.from(ExceptionCodes.ANALYTICS_NOT_ENABLED, "Bot Detection Data is",
                        "Bot Detection Data"));
    }
}
 
Example 4
Source File: WorkflowExecutor.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * This method is to publish workflow events
 *
 * @param workflowDTO workflow DTO
 */
public void publishEvents(WorkflowDTO workflowDTO) {
    boolean enabled = APIUtil.isAnalyticsEnabled();
    if (enabled) {
        APIMgtWorkflowDataPublisher publisher = ServiceReferenceHolder.getInstance()
                .getApiMgtWorkflowDataPublisher();
        publisher.publishEvent(workflowDTO);
    }
}
 
Example 5
Source File: BAMMediatorConfigContext.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
public VelocityContext getContext() {
    VelocityContext context = super.getContext();
    boolean enabledStats = APIUtil.isAnalyticsEnabled();
    if (enabledStats) {
        context.put("statsEnabled", Boolean.TRUE);
    } else {
        context.put("statsEnabled", Boolean.FALSE);
    }

    return context;
}
 
Example 6
Source File: AlertTypesPublisher.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
public AlertTypesPublisher() {
    enabled = APIUtil.isAnalyticsEnabled();
    skipEventReceiverConnection = DataPublisherUtil.getApiManagerAnalyticsConfiguration().
            isSkipEventReceiverConnection();
}
 
Example 7
Source File: APIAuthenticationHandler.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
protected boolean isAnalyticsEnabled() {
    return APIUtil.isAnalyticsEnabled();
}
 
Example 8
Source File: WebsocketInboundHandler.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

    //check if the request is a handshake
    if (msg instanceof FullHttpRequest) {
        FullHttpRequest req = (FullHttpRequest) msg;
        uri = req.getUri();
        URI uriTemp = new URI(uri);
        apiContextUri = new URI(uriTemp.getScheme(), uriTemp.getAuthority(), uriTemp.getPath(),
                 null, uriTemp.getFragment()).toString();

        if (req.getUri().contains("/t/")) {
            tenantDomain = MultitenantUtils.getTenantDomainFromUrl(req.getUri());
        } else {
            tenantDomain = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
        }

        String useragent = req.headers().get(HttpHeaders.USER_AGENT);

        // '-' is used for empty values to avoid possible errors in DAS side.
        // Required headers are stored one by one as validateOAuthHeader()
        // removes some of the headers from the request
        useragent = useragent != null ? useragent : "-";
        headers.add(HttpHeaders.USER_AGENT, useragent);

        if (validateOAuthHeader(req)) {
            if (!MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
                // carbon-mediation only support websocket invocation from super tenant APIs.
                // This is a workaround to mimic the the invocation came from super tenant.
                req.setUri(req.getUri().replaceFirst("/", "-"));
                String modifiedUri = uri.replaceFirst("/t/", "-t/");
                req.setUri(modifiedUri);
                msg = req;
            } else {
                req.setUri(uri); // Setting endpoint appended uri
            }

            if (StringUtils.isNotEmpty(token)) {
                ((FullHttpRequest) msg).headers().set(APIMgtGatewayConstants.WS_JWT_TOKEN_HEADER, token);
            }
            ctx.fireChannelRead(msg);

            // publish google analytics data
            GoogleAnalyticsData.DataBuilder gaData = new GoogleAnalyticsData.DataBuilder(null, null, null, null)
                    .setDocumentPath(uri)
                    .setDocumentHostName(DataPublisherUtil.getHostAddress())
                    .setSessionControl("end")
                    .setCacheBuster(APIMgtGoogleAnalyticsUtils.getCacheBusterId())
                    .setIPOverride(ctx.channel().remoteAddress().toString());
            APIMgtGoogleAnalyticsUtils gaUtils = new APIMgtGoogleAnalyticsUtils();
            gaUtils.init(tenantDomain);
            gaUtils.publishGATrackingData(gaData, req.headers().get(HttpHeaders.USER_AGENT),
                    headers.get(HttpHeaders.AUTHORIZATION));
        } else {
            ctx.writeAndFlush(new TextWebSocketFrame(APISecurityConstants.API_AUTH_INVALID_CREDENTIALS_MESSAGE));
            if (log.isDebugEnabled()) {
                log.debug("Authentication Failure for the websocket context: " + apiContextUri);
            }
            throw new APISecurityException(APISecurityConstants.API_AUTH_INVALID_CREDENTIALS,
                    APISecurityConstants.API_AUTH_INVALID_CREDENTIALS_MESSAGE);
        }
    } else if ((msg instanceof CloseWebSocketFrame) || (msg instanceof PingWebSocketFrame)) {
        //if the inbound frame is a closed frame, throttling, analytics will not be published.
        ctx.fireChannelRead(msg);
    } else if (msg instanceof WebSocketFrame) {

        boolean isAllowed = doThrottle(ctx, (WebSocketFrame) msg);

        if (isAllowed) {
            ctx.fireChannelRead(msg);
            String clientIp = getRemoteIP(ctx);
            // publish analytics events if analytics is enabled
            if (APIUtil.isAnalyticsEnabled()) {
                publishRequestEvent(clientIp, true);
            }
        } else {
            ctx.writeAndFlush(new TextWebSocketFrame("Websocket frame throttled out"));
            if (log.isDebugEnabled()) {
                log.debug("Inbound Websocket frame is throttled. " + ctx.channel().toString());
            }
        }
    }
}
 
Example 9
Source File: WebsocketInboundHandler.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
/**
 * Checks if the request is throttled
 *
 * @param ctx ChannelHandlerContext
 * @return false if throttled
 * @throws APIManagementException
 */
public boolean doThrottle(ChannelHandlerContext ctx, WebSocketFrame msg) {

    String applicationLevelTier = infoDTO.getApplicationTier();
    String apiLevelTier = infoDTO.getApiTier();
    String subscriptionLevelTier = infoDTO.getTier();
    String resourceLevelTier = apiLevelTier;
    String authorizedUser;
    if (MultitenantConstants.SUPER_TENANT_DOMAIN_NAME
            .equalsIgnoreCase(infoDTO.getSubscriberTenantDomain())) {
        authorizedUser = infoDTO.getSubscriber() + "@" + infoDTO.getSubscriberTenantDomain();
    } else {
        authorizedUser = infoDTO.getSubscriber();
    }
    String apiName = infoDTO.getApiName();
    String apiContext = apiContextUri;
    String apiVersion = version;
    String appTenant = infoDTO.getSubscriberTenantDomain();
    String apiTenant = tenantDomain;
    String appId = infoDTO.getApplicationId();
    String applicationLevelThrottleKey = appId + ":" + authorizedUser;
    String apiLevelThrottleKey = apiContext + ":" + apiVersion;
    String resourceLevelThrottleKey = apiLevelThrottleKey;
    String subscriptionLevelThrottleKey = appId + ":" + apiContext + ":" + apiVersion;
    String messageId = UIDGenerator.generateURNString();
    String remoteIP = getRemoteIP(ctx);
    if (log.isDebugEnabled()) {
        log.debug("Remote IP address : " + remoteIP);
    }
    if (remoteIP.indexOf(":") > 0) {
        remoteIP = remoteIP.substring(1, remoteIP.indexOf(":"));
    }
    JSONObject jsonObMap = new JSONObject();
    if (remoteIP != null && remoteIP.length() > 0) {
        try {
            InetAddress address = APIUtil.getAddress(remoteIP);
            if (address instanceof Inet4Address) {
                jsonObMap.put(APIThrottleConstants.IP, APIUtil.ipToLong(remoteIP));
            } else if (address instanceof Inet6Address) {
                jsonObMap.put(APIThrottleConstants.IPv6, APIUtil.ipToBigInteger(remoteIP));
            }
        } catch (UnknownHostException e) {
            //ignore the error and log it
            log.error("Error while parsing host IP " + remoteIP, e);
        }
    }
    jsonObMap.put(APIThrottleConstants.MESSAGE_SIZE, msg.content().capacity());
    try {
        PrivilegedCarbonContext.startTenantFlow();
        PrivilegedCarbonContext.getThreadLocalCarbonContext()
                .setTenantDomain(tenantDomain, true);
        boolean isThrottled = WebsocketUtil
                .isThrottled(resourceLevelThrottleKey, subscriptionLevelThrottleKey,
                        applicationLevelThrottleKey);
        if (isThrottled) {
            if (APIUtil.isAnalyticsEnabled()) {
                publishThrottleEvent();
            }
            return false;
        }
    } finally {
        PrivilegedCarbonContext.endTenantFlow();
    }
    Object[] objects =
            new Object[]{messageId, applicationLevelThrottleKey, applicationLevelTier,
                    apiLevelThrottleKey, apiLevelTier, subscriptionLevelThrottleKey,
                    subscriptionLevelTier, resourceLevelThrottleKey, resourceLevelTier,
                    authorizedUser, apiContext, apiVersion, appTenant, apiTenant, appId,
                    apiName, jsonObMap.toString()};
    org.wso2.carbon.databridge.commons.Event event =
            new org.wso2.carbon.databridge.commons.Event(
                    "org.wso2.throttle.request.stream:1.0.0", System.currentTimeMillis(), null,
                    null, objects);
    ServiceReferenceHolder.getInstance().getThrottleDataPublisher().getDataPublisher().tryPublish(event);
    return true;
}
 
Example 10
Source File: HostObjectUtils.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
protected static boolean isStatPublishingEnabled() {
        return APIUtil.isAnalyticsEnabled();
}
 
Example 11
Source File: AlertConfigManager.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
private AlertConfigManager() throws AlertManagementException {
    if (!APIUtil.isAnalyticsEnabled()) {
        throw new AlertManagementException("Analytics Not Enabled");
    }
}
 
Example 12
Source File: HostObjectUtils.java    From carbon-apimgt with Apache License 2.0 2 votes vote down vote up
/**
*This methods is to check whether stat publishing is enabled
* @return boolean
 */
protected static boolean checkDataPublishingEnabled() {
    return APIUtil.isAnalyticsEnabled();
}