Subversion Repositories bacoAlunos

Rev

Rev 55 | Go to most recent revision | Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
18 jmachado 1
package pt.estgp.estgweb.services.urlstat;
2
 
3
import jomm.utils.MessageResources;
4
import jomm.utils.MyCalendar;
5
import org.apache.log4j.Logger;
6
import org.apache.commons.httpclient.util.URIUtil;
7
import org.apache.commons.httpclient.URIException;
8
import org.jfree.chart.ChartFactory;
9
import org.jfree.chart.ChartUtilities;
10
import org.jfree.chart.JFreeChart;
11
import org.jfree.chart.axis.DateAxis;
12
import org.jfree.chart.plot.XYPlot;
13
import org.jfree.data.time.Day;
14
import org.jfree.data.time.TimeSeries;
15
import org.jfree.data.time.TimeSeriesCollection;
16
import org.jfree.data.time.Month;
17
import pt.estgp.estgweb.domain.UrlStat;
18
import pt.estgp.estgweb.domain.UrlStatDay;
19
import pt.estgp.estgweb.domain.UrlStatMonth;
20
import pt.estgp.estgweb.domain.dao.DaoFactory;
21
import pt.estgp.estgweb.services.expceptions.ServiceException;
22
import pt.estgp.estgweb.utils.ConfigProperties;
23
import pt.estgp.estgweb.Globals;
24
import jomm.utils.DatesUtils;
25
import jomm.dao.impl.AbstractDao;
26
import jomm.web.utils.TestHttpServletRequest;
27
import pt.utl.ist.berserk.logic.serviceManager.IService;
28
 
29
import javax.servlet.http.HttpServletRequest;
30
import java.awt.*;
31
import java.io.File;
32
import java.io.IOException;
33
import java.util.Date;
34
import java.util.List;
35
import java.util.ArrayList;
36
import java.text.SimpleDateFormat;
37
 
38
 
39
/**
40
 * @author Jorge Machado
41
 * @date 15/Mar/2008
42
 * @time 6:55:38
43
 * @see pt.estgp.estgweb.services.urlstat
44
 */
45
public class ChartBuilderService implements IService
46
{
47
    private static final 1.5.0/docs/api/java/util/logging/Logger.html">Logger logger = 1.5.0/docs/api/java/util/logging/Logger.html">Logger.getLogger(ChartBuilderService.class);
48
 
49
    public static final long LINK_CHART_EXPIRE_INTERVAL = ConfigProperties.getIntProperty("url.stat.image.expire.interval.time.minutes") * 60 * 1000;
50
    public static final 1.5.0/docs/api/java/lang/String.html">String LINK_CHART_TMP_DIR = ConfigProperties.getProperty("url.stat.tmp.dir");
51
 
52
    /**
53
     * Return file image location
54
     *
55
     * @param relativePaths to analysis
56
     * @param request to get user language
57
     * @param type of chart
58
     * @return image location
59
     * @throws ServiceException error executing
60
 
61
     */
62
    public 1.5.0/docs/api/java/lang/String.html">String run(HttpServletRequest request, List<String> relativePaths, ChartTypeEnum type) throws ServiceException
63
    {
64
        MyCalendar c = new MyCalendar();
65
        int day = c.getDay();
66
        int month = c.getMonth();
67
        int year = c.getYear();
68
        if(type == ChartTypeEnum.weekDays)
69
            return build(request,type.getMessageKey(), relativePaths, year,month,day,7,type);
70
        else if(type == ChartTypeEnum.monthDays)
71
            return build(request,type.getMessageKey(), relativePaths, year,month,day,31,type);
72
        else if(type == ChartTypeEnum.trimestreDays)
73
            return build(request,type.getMessageKey(), relativePaths, year,month,day,90,type);
74
        else if(type == ChartTypeEnum.semestreDays)
75
            return build(request,type.getMessageKey(), relativePaths, year,month,day,180,type);
76
        else if(type == ChartTypeEnum.yearDays)
77
            return build(request,type.getMessageKey(), relativePaths, year,month,day,365,type);
78
        else if(type == ChartTypeEnum.trimestreMonths)
79
            return build(request,type.getMessageKey(), relativePaths, year,month,3,type);
80
        else if(type == ChartTypeEnum.semestreMonths)
81
            return build(request,type.getMessageKey(), relativePaths, year,month,6,type);
82
        else if(type == ChartTypeEnum.yearMonths)
83
            return build(request,type.getMessageKey(), relativePaths, year,month,12,type);
84
        else if(type == ChartTypeEnum.twoYearsMonths)
85
            return build(request,type.getMessageKey(), relativePaths, year,month,24,type);
86
        return null;
87
    }
88
 
89
 
90
    private 1.5.0/docs/api/java/lang/String.html">String build(HttpServletRequest request, 1.5.0/docs/api/java/lang/String.html">String messageTitle, List<String> relativePaths, int untilYear, int untilMonth, int untilDay, int days, ChartTypeEnum type)
91
    {
92
        5+0%2Fdocs%2Fapi+Date">Date startDate = DatesUtils.getStartDate(untilYear,untilMonth,untilDay,days);
93
        MyCalendar c = new MyCalendar(untilYear,untilMonth, untilDay);
94
        5+0%2Fdocs%2Fapi+Date">Date endDate = c.getTime();
95
        return build(request,messageTitle,relativePaths,startDate,endDate,type);
96
    }
97
 
98
    private 1.5.0/docs/api/java/lang/String.html">String build(HttpServletRequest request, 1.5.0/docs/api/java/lang/String.html">String messageTitle, List<String> relativePaths, int untilYear, int untilMonth, int months,ChartTypeEnum type)
99
    {
100
        5+0%2Fdocs%2Fapi+Date">Date startDate = DatesUtils.getStartDate(untilYear,untilMonth,months);
101
        MyCalendar c = new MyCalendar(untilYear,untilMonth, 1);
102
        5+0%2Fdocs%2Fapi+Date">Date endDate = c.getTime();
103
        return build(request,messageTitle,relativePaths,startDate,endDate,type);
104
    }
105
 
106
    private 1.5.0/docs/api/java/lang/String.html">String build(HttpServletRequest request, 1.5.0/docs/api/java/lang/String.html">String messageTitle, List<String> relativePaths, 5+0%2Fdocs%2Fapi+Date">Date startDate, 5+0%2Fdocs%2Fapi+Date">Date endDate,ChartTypeEnum type)
107
    {
108
        1.5.0/docs/api/java/lang/String.html">String location = linkToFileName(relativePaths,startDate,endDate,type.getScale());
109
        1.5.0/docs/api/java/io/File.html">File img = new 1.5.0/docs/api/java/io/File.html">File(Globals.TMP_DIR + location);
110
        if(img.exists() && ((1.5.0/docs/api/java/lang/System.html">System.currentTimeMillis() - img.lastModified()) < LINK_CHART_EXPIRE_INTERVAL))
111
        {
112
            return location;
113
        }
114
        img.getParentFile().mkdirs();
115
 
116
        TimeSeriesCollection dataset = new TimeSeriesCollection();
117
        for(1.5.0/docs/api/java/lang/String.html">String relativePath: relativePaths)
118
        {
119
            UrlStat urlStat = DaoFactory.getUrlStatDaoImpl().loadOrNull(relativePath);
120
            if(urlStat != null)
121
            {
122
                TimeSeries s = new TimeSeries(urlStat.getName(), type.getScale().getRegularTimePeriodClass());
123
                if(type.getScale() == TimeSeriesScaleEnum.days)
124
                {
125
                    List<UrlStatDay> urlStatDays = DaoFactory.getUrlStatDayDaoImpl().loadDays(relativePath,startDate,endDate);
126
                    for(UrlStatDay urlStatDay: urlStatDays)
127
                    {
128
                        s.add(new Day(
129
                                urlStatDay.getDate()),
130
                                urlStatDay.getTotalClicks());
131
                    }
132
                }
133
                else if(type.getScale() == TimeSeriesScaleEnum.months)
134
                {
135
                    List<UrlStatMonth> urlStatMonths = DaoFactory.getUrlStatMonthDaoImpl().loadByMonth(relativePath,startDate,endDate);
136
                    for(UrlStatMonth urlStatMonth: urlStatMonths)
137
                    {
138
                        s.add(new Month(
139
                                urlStatMonth.getDate()),
140
                                urlStatMonth.getTotalClicks());
141
                    }
142
                }
143
                dataset.addSeries(s);
144
            }
145
        }
146
//        dataset.setDomainIsPointsInTime(true);
147
 
148
 
149
        JFreeChart chart = ChartFactory.createTimeSeriesChart(
150
                MessageResources.getMessage(request,messageTitle),
151
                MessageResources.getMessage(request,"url.stat.days"),
152
                MessageResources.getMessage(request,"url.stat.access.clicks"),
153
                dataset,
154
                true,
155
                true,
156
                false
157
        );
158
        chart.setBackgroundImage(null);
159
        XYPlot plot = (XYPlot) chart.getPlot();
160
        DateAxis axis = (DateAxis) plot.getDomainAxis();
161
        axis.setDateFormatOverride(type.getSimpleDateFormat());
162
        plot.setBackgroundPaint(1.5.0/docs/api/java/awt/Color.html">Color.lightGray);
163
        plot.setDomainGridlinePaint(1.5.0/docs/api/java/awt/Color.html">Color.white);
164
        plot.setDomainGridlinesVisible(true);
165
        plot.setRangeGridlinePaint(1.5.0/docs/api/java/awt/Color.html">Color.white);
166
        try
167
        {
168
            ChartUtilities.saveChartAsPNG(img, chart, 800, 300);
169
            return location;
170
        }
171
        catch (1.5.0/docs/api/java/io/IOException.html">IOException e)
172
        {
173
            logger.error(e,e);
174
        }
175
        return null;
176
    }
177
 
178
 
179
 
180
    private static 1.5.0/docs/api/java/lang/String.html">String linkToFileName(List<String> relativePaths, 5+0%2Fdocs%2Fapi+Date">Date startDate, 5+0%2Fdocs%2Fapi+Date">Date endDate, TimeSeriesScaleEnum seriesScaleEnum)
181
    {
182
        return linkToFileNameEncode(relativePaths,startDate,endDate,seriesScaleEnum,false);
183
    }
184
 
185
    private static 1.5.0/docs/api/java/lang/String.html">String linkToFileNameEncode(List<String> relativePaths, 5+0%2Fdocs%2Fapi+Date">Date startDate, 5+0%2Fdocs%2Fapi+Date">Date endDate, TimeSeriesScaleEnum seriesScaleEnum,boolean encode)
186
    {
187
        try
188
        {
189
            1.5.0/docs/api/java/lang/String.html">String relativePathName = "";
190
            for(1.5.0/docs/api/java/lang/String.html">String relativePath: relativePaths)
191
            {
192
                relativePathName += relativePath + "_";
193
            }
194
            1.5.0/docs/api/java/text/SimpleDateFormat.html">SimpleDateFormat sp = new 1.5.0/docs/api/java/text/SimpleDateFormat.html">SimpleDateFormat("yyyy_MM_dd");
195
            1.5.0/docs/api/java/lang/String.html">String dates = sp.format(startDate) + "_UNTIL_" + sp.format(endDate) + "_" + seriesScaleEnum.getType();
196
            1.5.0/docs/api/java/lang/String.html">String path;
197
            if(encode)
198
                path = URIUtil.encodeAll(relativePathName.replaceAll("/","_"),"ISO-8859-1");
199
            else
200
                path = relativePathName.replaceAll("/","_");
201
            return LINK_CHART_TMP_DIR + "/" + path + "_" + dates + ".png";
202
        }
203
        catch (1.5.0/docs/api/javax/print/URIException.html">URIException e)
204
        {
205
            logger.fatal(e,e);
206
            return null;
207
        }
208
    }
209
 
210
 
211
    /**
212
     * Simple test to create link clicks from 2003 until now (PS: call first: UrlStatService.main) and generate charts of all types
213
     * @param args
214
     * @throws ServiceException
215
     */
216
 
217
    public static void main(1.5.0/docs/api/java/lang/String.html">String[] args) throws ServiceException
218
    {
219
//        UrlStatService.main(null);
220
        AbstractDao.getCurrentSession().beginTransaction();
221
        List<String> relativePaths = new ArrayList<String>();
222
        relativePaths.add("/Welcome.do");
223
//        relativePaths.add("/teste2");
224
        1.5.0/docs/api/java/lang/System.html">System.out.println(new ChartBuilderService().run(new TestHttpServletRequest(),relativePaths, ChartTypeEnum.weekDays));
225
        1.5.0/docs/api/java/lang/System.html">System.out.println(new ChartBuilderService().run(new TestHttpServletRequest(),relativePaths, ChartTypeEnum.monthDays));
226
        1.5.0/docs/api/java/lang/System.html">System.out.println(new ChartBuilderService().run(new TestHttpServletRequest(),relativePaths, ChartTypeEnum.trimestreDays));
227
        1.5.0/docs/api/java/lang/System.html">System.out.println(new ChartBuilderService().run(new TestHttpServletRequest(),relativePaths, ChartTypeEnum.semestreDays));
228
        1.5.0/docs/api/java/lang/System.html">System.out.println(new ChartBuilderService().run(new TestHttpServletRequest(),relativePaths, ChartTypeEnum.yearDays));
229
        1.5.0/docs/api/java/lang/System.html">System.out.println(new ChartBuilderService().run(new TestHttpServletRequest(),relativePaths, ChartTypeEnum.trimestreMonths));
230
        1.5.0/docs/api/java/lang/System.html">System.out.println(new ChartBuilderService().run(new TestHttpServletRequest(),relativePaths, ChartTypeEnum.semestreMonths));
231
        1.5.0/docs/api/java/lang/System.html">System.out.println(new ChartBuilderService().run(new TestHttpServletRequest(),relativePaths, ChartTypeEnum.yearMonths));
232
        1.5.0/docs/api/java/lang/System.html">System.out.println(new ChartBuilderService().run(new TestHttpServletRequest(),relativePaths, ChartTypeEnum.twoYearsMonths));
233
        AbstractDao.getCurrentSession().getTransaction().commit();
234
    }
235
 
236
}