<commit_before>/*
 * Copyright 2008-2009 the original author or authors.
 *
 * 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.broadleafcommerce.core.web.catalog.taglib;

import java.io.IOException;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.SimpleTagSupport;

import org.broadleafcommerce.core.order.domain.DiscreteOrderItem;
import org.broadleafcommerce.core.order.domain.FulfillmentGroup;
import org.broadleafcommerce.core.order.domain.FulfillmentGroupItem;
import org.broadleafcommerce.core.order.domain.Order;
import org.broadleafcommerce.profile.core.domain.Address;

public class GoogleAnalyticsTag extends SimpleTagSupport {

    private static final long serialVersionUID = 1L;
    private String webPropertyId;
    private Order order;

    public void setOrder(Order order) {
        this.order = order;
    }

    public void setWebPropertyId(String webPropertyId) {
        this.webPropertyId = webPropertyId;
    }

    @Override
    public void doTag() throws JspException, IOException {
        JspWriter out = getJspContext().getOut();
        out.println(analytics(webPropertyId, order));
        super.doTag();
    }

    protected String analytics(String webPropertyId, Order order) {
        StringBuffer sb = new StringBuffer();

        if (order != null) {
            sb.append("<script type=\"text/javascript\">");
            sb.append("var gaJsHost = ((\"https:\" == document.location.protocol) ? \"https://ssl.\" : \"http://www.\");");
            sb.append("document.write(unescape(\"%3Cscript src='\" + gaJsHost + \"google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E\"))");
            sb.append("</script> <script type=\"text/javascript\">");
            sb.append(" try { var pageTracker = _gat._getTracker(\"" + webPropertyId + "\");");
            sb.append("pageTracker._trackPageview();");

            Address paymentAddress = order.getPaymentInfos().get(0).getAddress();

            sb.append("pageTracker._addTrans(" + order.getId() + "," + order.getName() + "," +
                    order.getTotal() + "," + order.getTotalTax() + "," + order.getTotalShipping() + "," +
                    paymentAddress.getCity() + "," + paymentAddress.getState().getName() + "," +
                    paymentAddress.getCountry().getName() + ");" );

            for (FulfillmentGroup fulfillmentGroup : order.getFulfillmentGroups()) {
                for (FulfillmentGroupItem fulfillmentGroupItem : fulfillmentGroup.getFulfillmentGroupItems()) {
                    DiscreteOrderItem orderItem = (DiscreteOrderItem) fulfillmentGroupItem.getOrderItem();
                    sb.append("pageTracker._addItem(" + order.getId() + "," + orderItem.getSku().getId() + "," +
                            orderItem.getSku().getName() + "," + null + "," +
                            orderItem.getPrice() + "," + orderItem.getQuantity() + ");" );
                }
            }

            sb.append("pageTracker._trackTrans();");
            sb.append("} catch(err) {}</script>");
        }
        else {
            sb.append("<script type=\"text/javascript\">");
            sb.append("var gaJsHost = ((\"https:\" == document.location.protocol) ? \"https://ssl.\" : \"http://www.\");");
            sb.append("document.write(unescape(\"%3Cscript src='\" + gaJsHost + \"google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E\"))");
            sb.append("</script> <script type=\"text/javascript\">");
            sb.append(" try { var pageTracker = _gat._getTracker(\"" + webPropertyId + "\");");
            sb.append("pageTracker._trackPageview();");
            sb.append("} catch(err) {}</script>");
        }

        return sb.toString();<commit_msg>BLC-328 - Refactored the Google Analytics tag to be in line with the recommended asynchronous Javascript version<commit_after>/*
 * Copyright 2008-2009 the original author or authors.
 *
 * 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.broadleafcommerce.core.web.catalog.taglib;

import java.io.IOException;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.SimpleTagSupport;

import org.broadleafcommerce.core.order.domain.DiscreteOrderItem;
import org.broadleafcommerce.core.order.domain.FulfillmentGroup;
import org.broadleafcommerce.core.order.domain.FulfillmentGroupItem;
import org.broadleafcommerce.core.order.domain.Order;
import org.broadleafcommerce.profile.core.domain.Address;

public class GoogleAnalyticsTag extends SimpleTagSupport {

    private static final long serialVersionUID = 1L;
    private String webPropertyId;
    private Order order;

    public void setOrder(Order order) {
        this.order = order;
    }

    public void setWebPropertyId(String webPropertyId) {
        this.webPropertyId = webPropertyId;
    }

    @Override
    public void doTag() throws JspException, IOException {
        JspWriter out = getJspContext().getOut();
        out.println(analytics(webPropertyId, order));
        super.doTag();
    }

    /**
     * Documentation for the recommended asynchronous GA tag is at:
     * http://code.google.com/apis/analytics/docs/tracking/gaTrackingEcommerce.html
     * 
     * @param webPropertyId - Google Analytics ID
     * @param order - optionally track the order submission. This should be included on the
     * page after the order has been sucessfully submitted. If null, this will just track the current page
     * @return the relevant Javascript to render on the page
     */
    protected String analytics(String webPropertyId, Order order) {
        StringBuffer sb = new StringBuffer();
        
        sb.append("<script type=\"text/javascript\">");
        sb.append("var _gaq = _gaq || [];");
        sb.append("_gaq.push(['_setAccount', '" + webPropertyId + "']);");
        sb.append("_gaq.push(['_trackPageview']);");
        
        if (order != null) {
            Address paymentAddress = order.getPaymentInfos().get(0).getAddress();

            sb.append("_gaq.push(['_addTrans','" + order.getId() + "'");
            sb.append(",'" + order.getName() + "'");
            sb.append(",'" + order.getTotal() + "'");
            sb.append(",'" + order.getTotalTax() + "'");
            sb.append(",'" + order.getTotalShipping() + "'");
            sb.append(",'" + paymentAddress.getCity() + "'");
            sb.append(",'" + paymentAddress.getState().getName() + "'");
            sb.append(",'" + paymentAddress.getCountry().getName() + "'");
            sb.append("]);");

            for (FulfillmentGroup fulfillmentGroup : order.getFulfillmentGroups()) {
                for (FulfillmentGroupItem fulfillmentGroupItem : fulfillmentGroup.getFulfillmentGroupItems()) {
                	DiscreteOrderItem orderItem = (DiscreteOrderItem) fulfillmentGroupItem.getOrderItem();
                    sb.append("_gaq.push(['_addItem','" + order.getId() + "'");
                    sb.append(",'" + orderItem.getSku().getId() + "'");
                    sb.append(",'" + orderItem.getSku().getName() + "'");
                    sb.append(",' " + orderItem.getProduct().getDefaultCategory() + "'");
                    sb.append(",'" + orderItem.getPrice() + "'");
                    sb.append(",'" + orderItem.getQuantity() + "'");
                    sb.append("]);");
                }
            }
            sb.append("_gaq.push(['_trackTrans']);");
        }
        
        sb.append(" (function() {"
				+ "var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;"
				+ "ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';"
				+ "var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);"
				+ "})();");
        sb.append("</script>");

        return sb.toString();
{'fraction_non_alphanumeric': 0.14683204827355012, 'fraction_numerical': 0.00446977315901218, 'mean_word_length': 2.8478073946689597, 'pattern_counts': {'":': 0, '<': 13, '<?xml version=': 0, '>': 13, 'https://': 3, 'lorem ipsum': 0, 'www.': 5, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6445997', 'n_tokens_mistral': 2509, 'n_tokens_neox': 2445, 'n_words': 554}