Skip to content

Instantly share code, notes, and snippets.

@Qkyrie
Created December 3, 2013 13:47
Show Gist options
  • Save Qkyrie/7769370 to your computer and use it in GitHub Desktop.
Save Qkyrie/7769370 to your computer and use it in GitHub Desktop.
GoogleAnalytics as a jsp-tag
<?xml version="1.0" encoding="ISO-8859-1"?>
<taglib xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-jsptaglibrary_2_1.xsd"
version="2.1">
<tlib-version>1.0</tlib-version>
<short-name>googleAnalytics</short-name>
<uri>https://storm.ipc.be</uri>
<tag>
<name>googleAnalytics</name>
<tag-class>be.ipc.storm.common.tags.GoogleAnalyticsHandler</tag-class>
<body-content>empty</body-content>
</tag>
<!-- Invoke 'Generate' action to add tags or functions -->
</taglib>
package be.ipc.storm.common.tags;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;
import java.io.IOException;
import java.util.Properties;
/**
* Created by Davy van Roy.
* Date: 06/06/12
* Time: 11:38
*/
public class GoogleAnalyticsHandler extends TagSupport {
private static final String ACCOUNT_ID = "UA-32402572-1";
private static final boolean ANALYTICS_ENABLED;
@Override
public int doStartTag() throws JspException {
StringBuilder html = new StringBuilder();
if (ANALYTICS_ENABLED) {
html.append("<script type=\"text/javascript\">\n" +
"\n" +
" var _gaq = _gaq || [];\n" +
" _gaq.push(['_setAccount', '" + ACCOUNT_ID + "']);\n" +
" _gaq.push(['_setDomainName', 'ipc.be']);\n" +
" _gaq.push(['_trackPageview']);\n" +
"\n" +
" (function() {\n" +
" var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;\n" +
" ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';\n" +
" var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);\n" +
" })();\n" +
"\n" +
" </script>");
}
JspWriter out = this.pageContext.getOut();
try {
out.print(html);
} catch (IOException e) {
e.printStackTrace();
}
return TagSupport.SKIP_BODY;
}
static {
Properties PROPERTIES = null;
try {
PROPERTIES = new Properties();
PROPERTIES.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("storm.properties"));
} catch (IOException e) {
e.printStackTrace();
}
ANALYTICS_ENABLED = PROPERTIES.get("google.analytics.enabled") == null ? false : Boolean.valueOf((String) PROPERTIES.get("google.analytics.enabled"));
}
}
-- include --
<%@taglib prefix="google" uri="/WEB-INF/google-analytics-tag.tld" %>
-- usage --
<google:googleAnalytics/>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment