Package com.sourcetap.sfa.chart

Source Code of com.sourcetap.sfa.chart.ChartServlet

/*
*
* Copyright (c) 2004 SourceTap - www.sourcetap.com
*
*  The contents of this file are subject to the SourceTap Public License
* ("License"); You may not use this file except in compliance with the
* License. You may obtain a copy of the License at http://www.sourcetap.com/license.htm
* Software distributed under the License is distributed on an  "AS IS"  basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
* the specific language governing rights and limitations under the License.
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
*/

package com.sourcetap.sfa.chart;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Paint;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Enumeration;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.jCharts.axisChart.BarChart;
import org.jCharts.chartData.SingleDataSet;
import org.jCharts.properties.AxisProperties;
import org.jCharts.properties.BarChartProperties;
import org.jCharts.properties.LineChartProperties;
import org.ofbiz.base.util.Debug;
import org.ofbiz.base.util.UtilHttp;
import org.ofbiz.base.util.UtilTimer;
import org.ofbiz.base.util.UtilValidate;
import org.ofbiz.content.webapp.control.RequestHandler;
import org.ofbiz.entity.GenericDelegator;
import org.ofbiz.entity.GenericValue;
import org.ofbiz.entity.condition.EntityExpr;
import org.ofbiz.entity.condition.EntityOperator;

import com.sourcetap.sfa.activity.CalendarUtil;
import com.sourcetap.sfa.util.UserInfo;

/**
* ChartServlet.java - Generate Charts and stream to browser as jpeg images
*
* @author     <a href="mailto:sfowler@sourcetap.com">Steve Fowler</a>
* @since      2.0
*/
public class ChartServlet extends HttpServlet {
   
    public static final String module = ChartServlet.class.getName();
         
    public ChartServlet() {
        super();
    }

    /**
     * @see javax.servlet.Servlet#init(javax.servlet.ServletConfig)
     */
    public void init(ServletConfig config) throws ServletException {
        super.init(config);       
    }

    /**
     * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
     */
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    /**
     * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
     */
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {               
        // setup content type
        String contentType = "image/jpeg";
        response.setContentType(contentType);

        long requestStartTime = System.currentTimeMillis();
        HttpSession session = request.getSession();

        GenericValue userLogin = (GenericValue) session.getAttribute("userLogin");
    UserInfo userInfo  = (UserInfo) session.getAttribute("userInfo");
        //Debug.log("Cert Chain: " + request.getAttribute("javax.servlet.request.X509Certificate"), module);

        // workaraound if we are in the root webapp
        String webappName = UtilHttp.getApplicationName(request);

        String rname = "";
        if (request.getPathInfo() != null) {
            rname = request.getPathInfo().substring(1);
        }
        if (rname.indexOf('/') > 0) {
            rname = rname.substring(0, rname.indexOf('/'));
        }

        UtilTimer timer = null;
        if (Debug.timingOn()) {
            timer = new UtilTimer();
            timer.setLog(true);
            timer.timerString("[" + rname + "] Servlet Starting, doing setup", module);
        }
       
        // Setup the CONTROL_PATH for JSP dispatching.
        request.setAttribute("_CONTROL_PATH_", request.getContextPath() + request.getServletPath());
        if (Debug.verboseOn())
            Debug.logVerbose("Control Path: " + request.getAttribute("_CONTROL_PATH_"), module);

        // for convenience, and necessity with event handlers, make security and delegator available in the request:
        // try to get it from the session first so that we can have a delegator/dispatcher/security for a certain user if desired
        GenericDelegator delegator = null;
        String delegatorName = (String) session.getAttribute("delegatorName");
        if (UtilValidate.isNotEmpty(delegatorName)) {
            delegator = GenericDelegator.getGenericDelegator(delegatorName);
        }
        if (delegator == null) {
            delegator = (GenericDelegator) getServletContext().getAttribute("delegator");
        }
        if (delegator == null) {
            Debug.logError("[ControlServlet] ERROR: delegator not found in ServletContext", module);
        } else {
            request.setAttribute("delegator", delegator);
            // always put this in the session too so that session events can use the delegator
            session.setAttribute("delegatorName", delegator.getDelegatorName());
        }

        // display details on the servlet objects
        if (Debug.verboseOn()) {
            logRequestInfo(request);
        }

    int fyStartMonth = CalendarUtil.getFiscalYearStartMonth( delegator, userInfo );
        if (Debug.timingOn()) timer.timerString("[" + rname + "] Setup done, doing Event(s) and View(s)", module);

    try {
    String monthLabel[] = {"", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
    BarChartProperties properties = new BarChartProperties();
    AxisProperties axisProperties = new AxisProperties();
    axisProperties.setScaleFont( new Font( "Arial", Font.BOLD, 12 ) );
    axisProperties.setAxisTitleFont( new Font( "Arial", Font.BOLD, 12 ) );
    axisProperties.setYAxisUseDollarSigns(true);

    LineChartProperties lineChartProperties = new LineChartProperties(new BasicStroke());


    Paint[] paints= { new Color(100,150,100) };
    int width = 330;
    int height = 216;
    String xAxisTitle = " ";
    String yAxisTitle = " ";

    ArrayList xAxisLabels = new ArrayList();
    ArrayList legendLabels = new ArrayList();

    if(request.getParameter("report").equals("salesForQuarter")){
    double data[] = new double[3];
    Calendar cal = Calendar.getInstance();

    int month = cal.get(Calendar.MONTH) + 1;
    int year = cal.get(Calendar.YEAR);
    int quarterNumbers[] = CalendarUtil.getQuarterMonthNumbers(month, fyStartMonth);

    ArrayList list = new ArrayList();
    list.add(new EntityExpr("ownerId", EntityOperator.EQUALS, userInfo.getPartyId()));
    list.add(new EntityExpr("dealStatusId", EntityOperator.EQUALS, "10"));
    list.add(new EntityExpr("actualCloseDate", EntityOperator.LESS_THAN_EQUAL_TO, new java.sql.Date( CalendarUtil.getMaximumQuarterDate(cal.get(Calendar.MONTH) + 1, cal.get(Calendar.YEAR), fyStartMonth).getTime())));
    list.add(new EntityExpr("actualCloseDate", EntityOperator.GREATER_THAN_EQUAL_TO, new java.sql.Date( CalendarUtil.getMinimumQuarterDate(cal.get(Calendar.MONTH) + 1, cal.get(Calendar.YEAR), fyStartMonth).getTime())));

    ArrayList order = new ArrayList();
    order.add("actualCloseDate");

    java.util.List dealList = delegator.findByAnd("Deal", list, order);
    GenericValue dealValues[] = (GenericValue[])dealList.toArray(new GenericValue[0]);
    GenericValue dealValue = null;

    String months[] = CalendarUtil.getQuarterMonthNames(cal.get(Calendar.MONTH) + 1, fyStartMonth);
    for(int iz=0;iz<months.length;iz++){
      xAxisLabels.add((String)months[iz]);
    }

    xAxisTitle = "Month";
    yAxisTitle = "Sales";

    legendLabels.add("Pipeline for Quarter");

    for(int iz=0;iz<dealValues.length;iz++) {
      dealValue = dealValues[iz];
      Calendar calendar = Calendar.getInstance();
      calendar.setTime(dealValue.getDate("actualCloseDate"));

      if((calendar.get(Calendar.MONTH)+1)==quarterNumbers[0] && calendar.get(Calendar.YEAR)==year){
        data[0] = data[0] + dealValue.getDouble("amount").doubleValue();
      }
      if((calendar.get(Calendar.MONTH)+1)==quarterNumbers[1] && calendar.get(Calendar.YEAR)==year){
        data[1] = data[1] + dealValue.getDouble("amount").doubleValue();
      }
      if((calendar.get(Calendar.MONTH)+1)==quarterNumbers[2] && calendar.get(Calendar.YEAR)==year){
        data[2] = data[2] + dealValue.getDouble("amount").doubleValue();
      }
    }

      try {
      BarChart barChart = new BarChart(
        new SingleDataSet(
        data,
        (String[])legendLabels.toArray(new String[0]),
        (String[])xAxisLabels.toArray(new String[0]),
        paints,
        xAxisTitle,
        yAxisTitle ),
      false, properties, axisProperties, width, height );

      response.reset();
      response.setContentType("image/jpeg");
           
      barChart.exportJPG( response.getOutputStream(), 1.0f);
      response.getOutputStream().flush();
      } catch( Throwable throwable ) { throwable.printStackTrace();
      }
    }

    if(request.getParameter("report").equals("leadsForQuarter")){
    double data[] = new double[3];
    Calendar cal = Calendar.getInstance();

    int month = cal.get(Calendar.MONTH) + 1;
    int year = cal.get(Calendar.YEAR);
    int quarterNumbers[] = CalendarUtil.getQuarterMonthNumbers(month, fyStartMonth);

    ArrayList list = new ArrayList();
    list.add(new EntityExpr("leadOwnerId", EntityOperator.EQUALS, userInfo.getPartyId()));
    list.add(new EntityExpr("statusId", EntityOperator.EQUALS, "50"));
    list.add(new EntityExpr("convertedDate", EntityOperator.LESS_THAN_EQUAL_TO, new java.sql.Date( CalendarUtil.getMaximumQuarterDate(cal.get(Calendar.MONTH) + 1, cal.get(Calendar.YEAR), fyStartMonth).getTime())));
    list.add(new EntityExpr("convertedDate", EntityOperator.GREATER_THAN_EQUAL_TO, new java.sql.Date( CalendarUtil.getMinimumQuarterDate(cal.get(Calendar.MONTH) + 1, cal.get(Calendar.YEAR), fyStartMonth).getTime())));

    ArrayList order = new ArrayList();
    order.add("convertedDate");

    java.util.List dealList = delegator.findByAnd("Lead", list, order);
    GenericValue leadValues[] = (GenericValue[])dealList.toArray(new GenericValue[0]);
    GenericValue leadValue = null;

    String months[] = CalendarUtil.getQuarterMonthNames(cal.get(Calendar.MONTH) + 1, fyStartMonth);
    for(int iz=0;iz<months.length;iz++){
      xAxisLabels.add((String)months[iz]);
    }
    xAxisTitle = "Month";
    yAxisTitle = "Leads";

    legendLabels.add("Leads for Quarter");

    for(int iz=0;iz<leadValues.length;iz++) {
      leadValue = leadValues[iz];
      Calendar calendar = Calendar.getInstance();
      calendar.setTime(leadValue.getTimestamp("convertedDate"));

      if((calendar.get(Calendar.MONTH)+1)==quarterNumbers[0] && calendar.get(Calendar.YEAR)==year){
        data[0] = data[0] + 1;
      }
      if((calendar.get(Calendar.MONTH)+1)==quarterNumbers[1] && calendar.get(Calendar.YEAR)==year){
        data[1] = data[1] + 1;
      }
      if((calendar.get(Calendar.MONTH)+1)==quarterNumbers[2] && calendar.get(Calendar.YEAR)==year){
        data[2] = data[2] + 1;
      }
    }

    axisProperties.setYAxisUseDollarSigns(false);
    axisProperties.setYAxisRoundValuesToNearest(0);
//      axisProperties.setXAxisVerticalScaleFlag(true);

    try {
      BarChart barChart = new BarChart(
        new SingleDataSet(
        data,
        (String[])legendLabels.toArray(new String[0]),
        (String[])xAxisLabels.toArray(new String[0]),
        paints,
        xAxisTitle,
        yAxisTitle ),
      false, properties, axisProperties, width, height );

      response.reset();
      response.setContentType("image/jpeg");
      barChart.exportJPG( response.getOutputStream(), 1.0f);
      response.getOutputStream().flush();
      } catch( Throwable throwable ) { throwable.printStackTrace();
      }
    }

    if(request.getParameter("report").equals("forecastedForQuarter")){
    double data[] = new double[3];
    Calendar cal = Calendar.getInstance();

    int month = cal.get(Calendar.MONTH) + 1;
    int year = cal.get(Calendar.YEAR);
    int quarterNumbers[] = CalendarUtil.getQuarterMonthNumbers(month, fyStartMonth);

    ArrayList list = new ArrayList();
    list.add(new EntityExpr("ownerId", EntityOperator.EQUALS, userInfo.getPartyId()));
    list.add(new EntityExpr("projectedCloseDate", EntityOperator.LESS_THAN_EQUAL_TO, new java.sql.Date( CalendarUtil.getMaximumQuarterDate(cal.get(Calendar.MONTH) + 1, cal.get(Calendar.YEAR), fyStartMonth).getTime())));
    list.add(new EntityExpr("projectedCloseDate", EntityOperator.GREATER_THAN_EQUAL_TO, new java.sql.Date( CalendarUtil.getMinimumQuarterDate(cal.get(Calendar.MONTH) + 1, cal.get(Calendar.YEAR), fyStartMonth).getTime())));

    ArrayList order = new ArrayList();
    order.add("projectedCloseDate");

    java.util.List dealList = delegator.findByAnd("Deal", list, order);
    GenericValue dealValues[] = (GenericValue[])dealList.toArray(new GenericValue[0]);
    GenericValue dealValue = null;

    String months[] = CalendarUtil.getQuarterMonthNames(cal.get(Calendar.MONTH) + 1, fyStartMonth);
    for(int iz=0;iz<months.length;iz++){
      xAxisLabels.add((String)months[iz]);
    }

    xAxisTitle = "month";
    yAxisTitle = "sales";

    legendLabels.add("Forecasted Sales for Quarter");

    for(int iz=0;iz<dealValues.length;iz++) {
      dealValue = dealValues[iz];
      Calendar calendar = Calendar.getInstance();
      calendar.setTime(dealValue.getDate("projectedCloseDate"));

      if((calendar.get(Calendar.MONTH)+1)==quarterNumbers[0] && calendar.get(Calendar.YEAR)==year){
        data[0] = data[0] + dealValue.getDouble("amount").doubleValue();
      }
      if((calendar.get(Calendar.MONTH)+1)==quarterNumbers[1] && calendar.get(Calendar.YEAR)==year){
        data[1] = data[1] + dealValue.getDouble("amount").doubleValue();
      }
      if((calendar.get(Calendar.MONTH)+1)==quarterNumbers[2] && calendar.get(Calendar.YEAR)==year){
        data[2] = data[2] + dealValue.getDouble("amount").doubleValue();
      }
    }

      try {
      BarChart barChart = new BarChart(
        new SingleDataSet(
        data,
        (String[])legendLabels.toArray(new String[0]),
        (String[])xAxisLabels.toArray(new String[0]),
        paints,
        xAxisTitle,
        yAxisTitle ),
      false, properties, axisProperties, width, height );

      response.reset();
      response.setContentType("image/jpeg");
      barChart.exportJPG( response.getOutputStream(), 1.0f);
      response.getOutputStream().flush();
      } catch( Throwable throwable ) { Debug.logError("error creating bar chart", module);throwable.printStackTrace();
      }
    }

  } catch ( Exception e2 ) { Debug.logError("error creating chart", module); }

    if (Debug.timingOn()) timer.timerString("[" + rname + "] Done rendering page, Servlet Finished", module);               
    }
   
    /**
     * @see javax.servlet.Servlet#destroy()
     */
    public void destroy() {
        super.destroy();               
    }   
   
    protected RequestHandler getRequestHandler() {
        RequestHandler rh = (RequestHandler) getServletContext().getAttribute("_REQUEST_HANDLER_");
        if (rh == null) {
            rh = new RequestHandler();
            rh.init(getServletContext());
            getServletContext().setAttribute("_REQUEST_HANDLER_", rh);
        }
        return rh;
    }

  public void generateChart( HttpServletRequest req, HttpServletResponse res, BarChartProperties properties, AxisProperties axisProperties, int width, int height, SingleDataSet singleDataSet) throws ServletException, IOException {
    try {
    BarChart barChart = new BarChart( singleDataSet, false, properties, axisProperties, width, height );
    BufferedImage bi = barChart.getBufferedImage();
    Graphics2D graphics = barChart.getGraphics2D();
     // graphics.scale(0.75, 0.75d);
    //graphics.
    barChart.exportJPG( res.getOutputStream(), 1.0f);
    res.getOutputStream().flush();
    } catch( Throwable throwable ) { throwable.printStackTrace(); Debug.logError("error in generateChart", module);
    }
  }   

    protected void logRequestInfo(HttpServletRequest request) {
        ServletContext servletContext = this.getServletContext();
        HttpSession session = request.getSession();
             
        Debug.logVerbose("--- Start Request Headers: ---", module);
        Enumeration headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String headerName = (String) headerNames.nextElement();
            Debug.logVerbose(headerName + ":" + request.getHeader(headerName), module);
        }
        Debug.logVerbose("--- End Request Headers: ---", module);       
      
        Debug.logVerbose("--- Start Request Parameters: ---", module);
        Enumeration paramNames = request.getParameterNames();
        while (paramNames.hasMoreElements()) {
            String paramName = (String) paramNames.nextElement();
            Debug.logVerbose(paramName + ":" + request.getParameter(paramName), module);
        }
        Debug.logVerbose("--- End Request Parameters: ---", module);
               
        Debug.logVerbose("--- Start Request Attributes: ---", module);
        Enumeration reqNames = request.getAttributeNames();
        while (reqNames != null && reqNames.hasMoreElements()) {
            String attName = (String) reqNames.nextElement();
            Debug.logVerbose(attName + ":" + request.getAttribute(attName), module);
        }
        Debug.logVerbose("--- End Request Attributes ---", module);

        Debug.logVerbose("--- Start Session Attributes: ---", module);
        Enumeration sesNames = null;
        try {
            sesNames = session.getAttributeNames();               
        } catch (IllegalStateException e) {
            Debug.logVerbose("Cannot get session attributes : " + e.getMessage(), module);
        }       
        while (sesNames != null && sesNames.hasMoreElements()) {
            String attName = (String) sesNames.nextElement();
            Debug.logVerbose(attName + ":" + session.getAttribute(attName), module);
        }
        Debug.logVerbose("--- End Session Attributes ---", module);
       
        Enumeration appNames = servletContext.getAttributeNames();
        Debug.logVerbose("--- Start ServletContext Attributes: ---", module);
        while (appNames != null && appNames.hasMoreElements()) {
            String attName = (String) appNames.nextElement();
            Debug.logVerbose(attName + ":" + servletContext.getAttribute(attName), module);
        }
        Debug.logVerbose("--- End ServletContext Attributes ---", module);            
    }   
}
TOP

Related Classes of com.sourcetap.sfa.chart.ChartServlet

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.