Search in sources :

Example 1 with GoogleAnalyticsData

use of org.wso2.carbon.ganalytics.publisher.GoogleAnalyticsData in project carbon-apimgt by wso2.

the class APIMgtGoogleAnalyticsUtilsTestCase method testPublishGATrackingData.

@Test
public void testPublishGATrackingData() {
    APIMgtGoogleAnalyticsUtils apiMgtGoogleAnalyticsUtils = new APIMgtGoogleAnalyticsUtils();
    GoogleAnalyticsData.DataBuilder dataBuilder = Mockito.mock(GoogleAnalyticsData.DataBuilder.class);
    // test when gaConfig == null
    apiMgtGoogleAnalyticsUtils.publishGATrackingData(dataBuilder, "abc", "567r637r6");
    // test when gaConfig !=  null
    PowerMockito.mockStatic(PrivilegedCarbonContext.class);
    PowerMockito.mockStatic(ServiceReferenceHolder.class);
    PrivilegedCarbonContext privilegedCarbonContext = Mockito.mock(PrivilegedCarbonContext.class);
    ServiceReferenceHolder serviceReferenceHolder = Mockito.mock(ServiceReferenceHolder.class);
    RegistryService registryService = Mockito.mock(RegistryService.class);
    UserRegistry userRegistry = Mockito.mock(UserRegistry.class);
    Resource resource = Mockito.mock(Resource.class);
    PowerMockito.when(PrivilegedCarbonContext.getThreadLocalCarbonContext()).thenReturn(privilegedCarbonContext);
    PowerMockito.when(ServiceReferenceHolder.getInstance()).thenReturn(serviceReferenceHolder);
    Mockito.when(serviceReferenceHolder.getRegistryService()).thenReturn(registryService);
    try {
        Mockito.when(resource.getContentStream()).thenReturn(new ByteArrayInputStream(Charset.forName("UTF-16").encode("<GoogleAnalyticsTracking>\n" + "\t<!--Enable/Disable Google Analytics Tracking -->\n" + "\t<Enabled>false</Enabled>\n" + "\n" + "\t<!-- Google Analytics Tracking ID -->\n" + "\t<TrackingID>UA-XXXXXXXX-X</TrackingID>\n" + "\n" + "</GoogleAnalyticsTracking>").array()));
        Mockito.when(userRegistry.get("/apimgt/statistics/ga-config.xml")).thenReturn(resource);
    } catch (RegistryException e) {
        fail("RegistryException is thrown when tesing .");
        e.printStackTrace();
    }
    try {
        Mockito.when(registryService.getGovernanceSystemRegistry()).thenReturn(userRegistry);
    } catch (RegistryException e) {
        fail("RegistryException is thrown.");
    }
    apiMgtGoogleAnalyticsUtils.init("abc.com");
    // test when gaconfig.enabled=false
    apiMgtGoogleAnalyticsUtils.publishGATrackingData(dataBuilder, "ishara", "jhgy");
    // test when gaconfig.enabled=true annonymous
    try {
        Mockito.when(resource.getContentStream()).thenReturn(new ByteArrayInputStream(Charset.forName("UTF-16").encode("<GoogleAnalyticsTracking>\n" + "\t<!--Enable/Disable Google Analytics Tracking -->\n" + "\t<Enabled>true</Enabled>\n" + "\n" + "\t<!-- Google Analytics Tracking ID -->\n" + "\t<TrackingID>UA-XXXXXXXX-X</TrackingID>\n" + "\n" + "</GoogleAnalyticsTracking>").array()));
        apiMgtGoogleAnalyticsUtils.init("abc.com");
        GoogleAnalyticsData.DataBuilder dataBuilder1 = Mockito.mock(GoogleAnalyticsData.DataBuilder.class);
        Mockito.when(dataBuilder.setProtocolVersion("1")).thenReturn(dataBuilder);
        Mockito.when(dataBuilder.setTrackingId("UA-XXXXXXXX-X")).thenReturn(dataBuilder);
        Mockito.when(dataBuilder.setClientId("0x05a823c101178dd5")).thenReturn(dataBuilder);
        Mockito.when(dataBuilder.setHitType("pageview")).thenReturn(dataBuilder);
        GoogleAnalyticsData data = Mockito.mock(GoogleAnalyticsData.class);
        Mockito.when(dataBuilder.build()).thenReturn(data);
        PowerMockito.mockStatic(GoogleAnalyticsDataPublisher.class);
        PowerMockito.when(GoogleAnalyticsDataPublisher.buildPayloadString(data)).thenReturn("payload");
    } catch (RegistryException e) {
        fail(e.getMessage());
    }
    apiMgtGoogleAnalyticsUtils.publishGATrackingData(dataBuilder, "ishara", "Autorization ishara");
}
Also used : ServiceReferenceHolder(org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder) ByteArrayInputStream(java.io.ByteArrayInputStream) Resource(org.wso2.carbon.registry.core.Resource) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) PrivilegedCarbonContext(org.wso2.carbon.context.PrivilegedCarbonContext) GoogleAnalyticsData(org.wso2.carbon.ganalytics.publisher.GoogleAnalyticsData) RegistryService(org.wso2.carbon.registry.core.service.RegistryService) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) Test(org.junit.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 2 with GoogleAnalyticsData

use of org.wso2.carbon.ganalytics.publisher.GoogleAnalyticsData in project carbon-apimgt by wso2.

the class APIMgtGoogleAnalyticsTrackingHandler method trackPageView.

/**
 * 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(org.wso2.carbon.apimgt.gateway.handlers.analytics.Constants.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()));
    }
}
Also used : GoogleAnalyticsData(org.wso2.carbon.ganalytics.publisher.GoogleAnalyticsData) HashMap(java.util.HashMap) Map(java.util.Map) SimpleDateFormat(java.text.SimpleDateFormat) Date(java.util.Date) Axis2MessageContext(org.apache.synapse.core.axis2.Axis2MessageContext)

Example 3 with GoogleAnalyticsData

use of org.wso2.carbon.ganalytics.publisher.GoogleAnalyticsData in project carbon-apimgt by wso2.

the class APIMgtGoogleAnalyticsUtils method publishGATrackingData.

/**
 * Publish page tracking data to google analytics
 *
 * @param analyticsData Attributes required to be sent to Google Analytics
 * @param userAgent User-Agent of the client who sent the request
 * @param authHeader authentication header value of the request
 */
public void publishGATrackingData(GoogleAnalyticsData.DataBuilder analyticsData, String userAgent, String authHeader) {
    try {
        if (gaConfig == null || !gaConfig.enabled) {
            return;
        }
        String clientId = getVisitorId(authHeader);
        GoogleAnalyticsData data = analyticsData.setProtocolVersion(GOOGLE_ANALYTICS_TRACKER_VERSION).setTrackingId(gaConfig.googleAnalyticsTrackingID).setClientId(clientId).setHitType(GoogleAnalyticsConstants.HIT_TYPE_PAGEVIEW).build();
        String payload = GoogleAnalyticsDataPublisher.buildPayloadString(data);
        GoogleAnalyticsDataPublisher.publishGET(payload, userAgent, false);
    } catch (Exception e) {
        // flow should not break if event publishing failed. Therefore catching generic Exception and ignoring
        log.error("Cannot publish event. " + e.getMessage(), e);
    }
}
Also used : GoogleAnalyticsData(org.wso2.carbon.ganalytics.publisher.GoogleAnalyticsData) IOException(java.io.IOException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) XMLStreamException(javax.xml.stream.XMLStreamException) UnsupportedEncodingException(java.io.UnsupportedEncodingException)

Aggregations

GoogleAnalyticsData (org.wso2.carbon.ganalytics.publisher.GoogleAnalyticsData)3 ByteArrayInputStream (java.io.ByteArrayInputStream)1 IOException (java.io.IOException)1 UnsupportedEncodingException (java.io.UnsupportedEncodingException)1 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)1 SimpleDateFormat (java.text.SimpleDateFormat)1 Date (java.util.Date)1 HashMap (java.util.HashMap)1 Map (java.util.Map)1 XMLStreamException (javax.xml.stream.XMLStreamException)1 Axis2MessageContext (org.apache.synapse.core.axis2.Axis2MessageContext)1 Test (org.junit.Test)1 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)1 ServiceReferenceHolder (org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder)1 PrivilegedCarbonContext (org.wso2.carbon.context.PrivilegedCarbonContext)1 Resource (org.wso2.carbon.registry.core.Resource)1 RegistryException (org.wso2.carbon.registry.core.exceptions.RegistryException)1 RegistryService (org.wso2.carbon.registry.core.service.RegistryService)1 UserRegistry (org.wso2.carbon.registry.core.session.UserRegistry)1