<commit_before>/*
 * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.wso2.carbon.apimgt.gateway.handlers.analytics;

import org.apache.axiom.om.OMElement;
import org.apache.axis2.Constants;
import org.apache.axis2.util.JavaUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpHeaders;
import org.apache.synapse.MessageContext;
import org.apache.synapse.SynapseException;
import org.apache.synapse.config.Entry;
import org.apache.synapse.core.axis2.Axis2MessageContext;
import org.apache.synapse.rest.AbstractHandler;
import org.apache.synapse.rest.RESTConstants;
import org.wso2.carbon.apimgt.gateway.APIMgtGatewayConstants;
import org.wso2.carbon.apimgt.gateway.MethodStats;
import org.wso2.carbon.apimgt.gateway.handlers.security.APISecurityUtils;
import org.wso2.carbon.apimgt.gateway.handlers.security.AuthenticationContext;
import org.wso2.carbon.apimgt.gateway.internal.ServiceReferenceHolder;
import org.wso2.carbon.apimgt.gateway.utils.APIMgtGoogleAnalyticsUtils;
import org.wso2.carbon.apimgt.tracing.TracingSpan;
import org.wso2.carbon.apimgt.tracing.TracingTracer;
import org.wso2.carbon.apimgt.tracing.Util;
import org.wso2.carbon.apimgt.tracing.telemetry.TelemetrySpan;
import org.wso2.carbon.apimgt.tracing.telemetry.TelemetryTracer;
import org.wso2.carbon.apimgt.tracing.telemetry.TelemetryUtil;
import org.wso2.carbon.ganalytics.publisher.GoogleAnalyticsConstants;
import org.wso2.carbon.ganalytics.publisher.GoogleAnalyticsData;
import org.wso2.carbon.ganalytics.publisher.GoogleAnalyticsDataPublisher;

import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.xml.namespace.QName;

public class APIMgtGoogleAnalyticsTrackingHandler extends AbstractHandler {

    private static final Log log = LogFactory.getLog(APIMgtGoogleAnalyticsTrackingHandler.class);

	private static final String GOOGLE_ANALYTICS_TRACKER_VERSION = "1";

	private static final String COOKIE_NAME = "__utmmobile";

	private static final String ANONYMOUS_USER_ID = "anonymous";
	
	/** The key for getting the google analytics configuration - key refers to a/an [registry] entry    */
    private String configKey = null;
    /** Version number of the throttle policy */
    private long version;

    protected GoogleAnalyticsConfig config = null;

    @MethodStats
    @Override
    public boolean handleRequest(MessageContext msgCtx) {

        TracingSpan tracingSpan = null;
        TracingTracer tracingTracer = null;
        TelemetrySpan span = null;
        TelemetryTracer tracer = null;
        Map<String, String> tracerSpecificCarrier = new HashMap<>();
        if (TelemetryUtil.telemetryEnabled()) {
            if (Util.legacy()) {
                TracingSpan responseLatencySpan =
                        (TracingSpan) msgCtx.getProperty(APIMgtGatewayConstants.RESOURCE_SPAN);
                tracingTracer = Util.getGlobalTracer();
                tracingSpan = Util.startSpan(APIMgtGatewayConstants.GOOGLE_ANALYTICS_HANDLER, responseLatencySpan,
                        tracingTracer);
            } else {
                TelemetrySpan responseLatencySpan =
                        (TelemetrySpan) msgCtx.getProperty(APIMgtGatewayConstants.RESOURCE_SPAN);
                tracer = ServiceReferenceHolder.getInstance().getTelemetryTracer();
                span = TelemetryUtil.startSpan(APIMgtGatewayConstants.GOOGLE_ANALYTICS_HANDLER, responseLatencySpan,
                        tracer);
            }
        }
        try {
            if (configKey == null) {
                throw new SynapseException("Google Analytics configuration unspecified for the API");
            }

            Entry entry = msgCtx.getConfiguration().getEntryDefinition(configKey);
            if (entry == null) {
                log.warn("Cannot find Google Analytics configuration using key: " + configKey);
                return true;
            }
            Object entryValue = null;
            boolean reCreate = false;

            if (entry.isDynamic()) {
                if ((!entry.isCached()) || (entry.isExpired()) || config == null) {
                    entryValue = msgCtx.getEntry(this.configKey);
                    if (this.version != entry.getVersion()) {
                        reCreate = true;
                    }
                }
            } else if (config == null) {
                entryValue = msgCtx.getEntry(this.configKey);
            }

            if (reCreate || config == null) {
                if (entryValue == null || !(entryValue instanceof OMElement)) {
                    log.warn("Unable to load Google Analytics configuration using key: " + configKey);
                    return true;
                }
                version = entry.getVersion();
                config = getGoogleAnalyticsConfig((OMElement) entryValue);
            }

            if (config == null) {
                log.warn("Unable to create Google Analytics configuration using key: " + configKey);
                return true;
            }
            if (!config.isEnabled()) {
                return true;
            }
            try {
                if (TelemetryUtil.telemetryEnabled()) {
                    if (Util.legacy()) {
                        Util.inject(tracingSpan, tracingTracer, tracerSpecificCarrier);
                        if (org.apache.axis2.context.MessageContext.getCurrentMessageContext() != null) {
                            Map headers =
                                    (Map) org.apache.axis2.context.MessageContext.getCurrentMessageContext().getProperty(
                                            org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS);
                            headers.putAll(tracerSpecificCarrier);
                            org.apache.axis2.context.MessageContext.getCurrentMessageContext()
                                    .setProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS, headers);
                        }
                    } else {
                        TelemetryUtil.inject(span, tracerSpecificCarrier);
                        if (org.apache.axis2.context.MessageContext.getCurrentMessageContext() != null) {
                            Map headers =
                                    (Map) org.apache.axis2.context.MessageContext.getCurrentMessageContext().getProperty(
                                            org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS);
                            headers.putAll(tracerSpecificCarrier);
                            org.apache.axis2.context.MessageContext.getCurrentMessageContext()
                                    .setProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS, headers);
                        }
                    }
                }
                trackPageView(msgCtx);
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
            return true;
        } catch (Exception e) {
            if (TelemetryUtil.telemetryEnabled()) {
                if (Util.legacy() && tracingSpan != null) {
                    Util.setTag(tracingSpan, APIMgtGatewayConstants.ERROR,
                            APIMgtGatewayConstants.GOOGLE_ANALYTICS_ERROR);
                } else if (!Util.legacy() && span != null) {
                    TelemetryUtil.setTag(span, APIMgtGatewayConstants.ERROR,
                            APIMgtGatewayConstants.GOOGLE_ANALYTICS_ERROR);
                }
            }
            throw e;
        } finally {
            if (TelemetryUtil.telemetryEnabled()) {
                if (Util.legacy()) {<commit_msg>extracted the message context null condition outside of if-else in util.legacy<commit_after>/*
 * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.wso2.carbon.apimgt.gateway.handlers.analytics;

import org.apache.axiom.om.OMElement;
import org.apache.axis2.Constants;
import org.apache.axis2.util.JavaUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpHeaders;
import org.apache.synapse.MessageContext;
import org.apache.synapse.SynapseException;
import org.apache.synapse.config.Entry;
import org.apache.synapse.core.axis2.Axis2MessageContext;
import org.apache.synapse.rest.AbstractHandler;
import org.apache.synapse.rest.RESTConstants;
import org.wso2.carbon.apimgt.gateway.APIMgtGatewayConstants;
import org.wso2.carbon.apimgt.gateway.MethodStats;
import org.wso2.carbon.apimgt.gateway.handlers.security.APISecurityUtils;
import org.wso2.carbon.apimgt.gateway.handlers.security.AuthenticationContext;
import org.wso2.carbon.apimgt.gateway.internal.ServiceReferenceHolder;
import org.wso2.carbon.apimgt.gateway.utils.APIMgtGoogleAnalyticsUtils;
import org.wso2.carbon.apimgt.tracing.TracingSpan;
import org.wso2.carbon.apimgt.tracing.TracingTracer;
import org.wso2.carbon.apimgt.tracing.Util;
import org.wso2.carbon.apimgt.tracing.telemetry.TelemetrySpan;
import org.wso2.carbon.apimgt.tracing.telemetry.TelemetryTracer;
import org.wso2.carbon.apimgt.tracing.telemetry.TelemetryUtil;
import org.wso2.carbon.ganalytics.publisher.GoogleAnalyticsConstants;
import org.wso2.carbon.ganalytics.publisher.GoogleAnalyticsData;
import org.wso2.carbon.ganalytics.publisher.GoogleAnalyticsDataPublisher;

import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.xml.namespace.QName;

public class APIMgtGoogleAnalyticsTrackingHandler extends AbstractHandler {

    private static final Log log = LogFactory.getLog(APIMgtGoogleAnalyticsTrackingHandler.class);

	private static final String GOOGLE_ANALYTICS_TRACKER_VERSION = "1";

	private static final String COOKIE_NAME = "__utmmobile";

	private static final String ANONYMOUS_USER_ID = "anonymous";
	
	/** The key for getting the google analytics configuration - key refers to a/an [registry] entry    */
    private String configKey = null;
    /** Version number of the throttle policy */
    private long version;

    protected GoogleAnalyticsConfig config = null;

    @MethodStats
    @Override
    public boolean handleRequest(MessageContext msgCtx) {

        TracingSpan tracingSpan = null;
        TracingTracer tracingTracer = null;
        TelemetrySpan span = null;
        TelemetryTracer tracer = null;
        Map<String, String> tracerSpecificCarrier = new HashMap<>();
        if (TelemetryUtil.telemetryEnabled()) {
            if (Util.legacy()) {
                TracingSpan responseLatencySpan =
                        (TracingSpan) msgCtx.getProperty(APIMgtGatewayConstants.RESOURCE_SPAN);
                tracingTracer = Util.getGlobalTracer();
                tracingSpan = Util.startSpan(APIMgtGatewayConstants.GOOGLE_ANALYTICS_HANDLER, responseLatencySpan,
                        tracingTracer);
            } else {
                TelemetrySpan responseLatencySpan =
                        (TelemetrySpan) msgCtx.getProperty(APIMgtGatewayConstants.RESOURCE_SPAN);
                tracer = ServiceReferenceHolder.getInstance().getTelemetryTracer();
                span = TelemetryUtil.startSpan(APIMgtGatewayConstants.GOOGLE_ANALYTICS_HANDLER, responseLatencySpan,
                        tracer);
            }
        }
        try {
            if (configKey == null) {
                throw new SynapseException("Google Analytics configuration unspecified for the API");
            }

            Entry entry = msgCtx.getConfiguration().getEntryDefinition(configKey);
            if (entry == null) {
                log.warn("Cannot find Google Analytics configuration using key: " + configKey);
                return true;
            }
            Object entryValue = null;
            boolean reCreate = false;

            if (entry.isDynamic()) {
                if ((!entry.isCached()) || (entry.isExpired()) || config == null) {
                    entryValue = msgCtx.getEntry(this.configKey);
                    if (this.version != entry.getVersion()) {
                        reCreate = true;
                    }
                }
            } else if (config == null) {
                entryValue = msgCtx.getEntry(this.configKey);
            }

            if (reCreate || config == null) {
                if (entryValue == null || !(entryValue instanceof OMElement)) {
                    log.warn("Unable to load Google Analytics configuration using key: " + configKey);
                    return true;
                }
                version = entry.getVersion();
                config = getGoogleAnalyticsConfig((OMElement) entryValue);
            }

            if (config == null) {
                log.warn("Unable to create Google Analytics configuration using key: " + configKey);
                return true;
            }
            if (!config.isEnabled()) {
                return true;
            }
            try {
                if (TelemetryUtil.telemetryEnabled()) {
                    if (Util.legacy()) {
                        Util.inject(tracingSpan, tracingTracer, tracerSpecificCarrier);
                    } else {
                        TelemetryUtil.inject(span, tracerSpecificCarrier);
                    }
                    if (org.apache.axis2.context.MessageContext.getCurrentMessageContext() != null) {
                        Map headers =
                                (Map) org.apache.axis2.context.MessageContext.getCurrentMessageContext().getProperty(
                                        org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS);
                        headers.putAll(tracerSpecificCarrier);
                        org.apache.axis2.context.MessageContext.getCurrentMessageContext()
                                .setProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS, headers);
                    }
                }
                trackPageView(msgCtx);
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
            return true;
        } catch (Exception e) {
            if (TelemetryUtil.telemetryEnabled()) {
                if (Util.legacy() && tracingSpan != null) {
                    Util.setTag(tracingSpan, APIMgtGatewayConstants.ERROR,
                            APIMgtGatewayConstants.GOOGLE_ANALYTICS_ERROR);
                } else if (!Util.legacy() && span != null) {
                    TelemetryUtil.setTag(span, APIMgtGatewayConstants.ERROR,
                            APIMgtGatewayConstants.GOOGLE_ANALYTICS_ERROR);
                }
            }
            throw e;
        } finally {
            if (TelemetryUtil.telemetryEnabled()) {
                if (Util.legacy()) {
{'fraction_non_alphanumeric': 0.08813247470101196, 'fraction_numerical': 0.004722477767555964, 'mean_word_length': 2.238530287984111, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 7, 'https://': 0, 'lorem ipsum': 0, 'www.': 4, 'xml': 2}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 9, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6993882', 'n_tokens_mistral': 4410, 'n_tokens_neox': 4233, 'n_words': 876}