|
| 1 | +/** |
| 2 | + * Copyright 2015 Google Inc. All Rights Reserved. |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | + |
| 17 | +package com.example.appengine.analytics; |
| 18 | + |
| 19 | +import com.google.appengine.api.urlfetch.URLFetchService; |
| 20 | +import com.google.appengine.api.urlfetch.URLFetchServiceFactory; |
| 21 | + |
| 22 | +import org.apache.http.client.utils.URIBuilder; |
| 23 | + |
| 24 | +import java.io.IOException; |
| 25 | +import java.net.URI; |
| 26 | +import java.net.URISyntaxException; |
| 27 | +import java.net.URL; |
| 28 | + |
| 29 | +import javax.servlet.ServletException; |
| 30 | +import javax.servlet.http.HttpServlet; |
| 31 | +import javax.servlet.http.HttpServletRequest; |
| 32 | +import javax.servlet.http.HttpServletResponse; |
| 33 | + |
| 34 | +// [START example] |
| 35 | +@SuppressWarnings("serial") |
| 36 | +public class AnalyticsServlet extends HttpServlet { |
| 37 | + |
| 38 | + @Override |
| 39 | + public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, |
| 40 | + ServletException { |
| 41 | + String trackingId = System.getenv("GA_TRACKING_ID"); |
| 42 | +// HttpClient client = HttpClientBuilder.create().build(); |
| 43 | + URIBuilder builder = new URIBuilder(); |
| 44 | + builder.setScheme("http").setHost("www.google-analytics.com").setPath("/collect") |
| 45 | + .addParameter("v", "1") // API Version. |
| 46 | + .addParameter("tid", trackingId) // Tracking ID / Property ID. |
| 47 | + // Anonymous Client Identifier. Ideally, this should be a UUID that |
| 48 | + // is associated with particular user, device, or browser instance. |
| 49 | + .addParameter("cid", "555") |
| 50 | + .addParameter("t", "event") // Event hit type. |
| 51 | + .addParameter("ec", "example") // Event category. |
| 52 | + .addParameter("ea", "test action"); // Event action. |
| 53 | + URI uri = null; |
| 54 | + try { |
| 55 | + uri = builder.build(); |
| 56 | + } catch (URISyntaxException e) { |
| 57 | + throw new ServletException("Problem building URI", e); |
| 58 | + } |
| 59 | + URLFetchService fetcher = URLFetchServiceFactory.getURLFetchService(); |
| 60 | + URL url = uri.toURL(); |
| 61 | + fetcher.fetch(url); |
| 62 | + resp.getWriter().println("Event tracked."); |
| 63 | + } |
| 64 | +} |
| 65 | +// [END example] |
0 commit comments