Subversion Repositories bacoAlunos

Rev

Rev 1306 | Go to most recent revision | Details | Compare with Previous | 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.Globals;
23
import jomm.utils.DatesUtils;
438 jmachado 24
import jomm.utils.BytesUtils;
18 jmachado 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
 
144 jmachado 49
    public static final long LINK_CHART_EXPIRE_INTERVAL = Globals.URL_STAT_CHART_EXPIRE_INTERVAL;
50
    public static final 1.5.0/docs/api/java/lang/String.html">String LINK_CHART_TMP_DIR = Globals.URL_STAT_CHART_TMP_DIR;
18 jmachado 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
    {
55 jmachado 108
        1.5.0/docs/api/java/lang/String.html">String location = linkToFileNameEncode(relativePaths,startDate,endDate,type.getScale(),true);
18 jmachado 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
        {
359 jmachado 119
            try
120
            {
438 jmachado 121
                relativePath = BytesUtils.getMD5(URIUtil.encodeWithinQuery(relativePath,"ISO-8859-1"));
359 jmachado 122
            }
123
            catch (1.5.0/docs/api/javax/print/URIException.html">URIException e)
124
            {
125
                logger.error(e,e);
126
                return null;
127
            }
18 jmachado 128
            UrlStat urlStat = DaoFactory.getUrlStatDaoImpl().loadOrNull(relativePath);
129
            if(urlStat != null)
130
            {
131
                TimeSeries s = new TimeSeries(urlStat.getName(), type.getScale().getRegularTimePeriodClass());
132
                if(type.getScale() == TimeSeriesScaleEnum.days)
133
                {
134
                    List<UrlStatDay> urlStatDays = DaoFactory.getUrlStatDayDaoImpl().loadDays(relativePath,startDate,endDate);
135
                    for(UrlStatDay urlStatDay: urlStatDays)
136
                    {
137
                        s.add(new Day(
138
                                urlStatDay.getDate()),
139
                                urlStatDay.getTotalClicks());
140
                    }
141
                }
142
                else if(type.getScale() == TimeSeriesScaleEnum.months)
143
                {
144
                    List<UrlStatMonth> urlStatMonths = DaoFactory.getUrlStatMonthDaoImpl().loadByMonth(relativePath,startDate,endDate);
145
                    for(UrlStatMonth urlStatMonth: urlStatMonths)
146
                    {
147
                        s.add(new Month(
148
                                urlStatMonth.getDate()),
149
                                urlStatMonth.getTotalClicks());
150
                    }
151
                }
152
                dataset.addSeries(s);
153
            }
154
        }
155
//        dataset.setDomainIsPointsInTime(true);
156
 
157
 
158
        JFreeChart chart = ChartFactory.createTimeSeriesChart(
159
                MessageResources.getMessage(request,messageTitle),
160
                MessageResources.getMessage(request,"url.stat.days"),
161
                MessageResources.getMessage(request,"url.stat.access.clicks"),
162
                dataset,
163
                true,
164
                true,
165
                false
166
        );
167
        chart.setBackgroundImage(null);
168
        XYPlot plot = (XYPlot) chart.getPlot();
169
        DateAxis axis = (DateAxis) plot.getDomainAxis();
170
        axis.setDateFormatOverride(type.getSimpleDateFormat());
171
        plot.setBackgroundPaint(1.5.0/docs/api/java/awt/Color.html">Color.lightGray);
172
        plot.setDomainGridlinePaint(1.5.0/docs/api/java/awt/Color.html">Color.white);
173
        plot.setDomainGridlinesVisible(true);
174
        plot.setRangeGridlinePaint(1.5.0/docs/api/java/awt/Color.html">Color.white);
175
        try
176
        {
177
            ChartUtilities.saveChartAsPNG(img, chart, 800, 300);
178
            return location;
179
        }
180
        catch (1.5.0/docs/api/java/io/IOException.html">IOException e)
181
        {
182
            logger.error(e,e);
183
        }
184
        return null;
185
    }
186
 
187
 
188
 
189
    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)
190
    {
191
        return linkToFileNameEncode(relativePaths,startDate,endDate,seriesScaleEnum,false);
192
    }
193
 
194
    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)
195
    {
196
        try
197
        {
198
            1.5.0/docs/api/java/lang/String.html">String relativePathName = "";
199
            for(1.5.0/docs/api/java/lang/String.html">String relativePath: relativePaths)
200
            {
201
                relativePathName += relativePath + "_";
202
            }
203
            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");
204
            1.5.0/docs/api/java/lang/String.html">String dates = sp.format(startDate) + "_UNTIL_" + sp.format(endDate) + "_" + seriesScaleEnum.getType();
205
            1.5.0/docs/api/java/lang/String.html">String path;
206
            if(encode)
359 jmachado 207
                path = URIUtil.encodeWithinQuery(relativePathName.replaceAll("/","_"),"ISO-8859-1");
18 jmachado 208
            else
209
                path = relativePathName.replaceAll("/","_");
210
            return LINK_CHART_TMP_DIR + "/" + path + "_" + dates + ".png";
211
        }
212
        catch (1.5.0/docs/api/javax/print/URIException.html">URIException e)
213
        {
214
            logger.fatal(e,e);
215
            return null;
216
        }
217
    }
218
 
219
 
220
    /**
221
     * Simple test to create link clicks from 2003 until now (PS: call first: UrlStatService.main) and generate charts of all types
222
     * @param args
223
     * @throws ServiceException
224
     */
225
 
359 jmachado 226
    public static void main(1.5.0/docs/api/java/lang/String.html">String[] args) throws ServiceException, 1.5.0/docs/api/javax/print/URIException.html">URIException
18 jmachado 227
    {
228
//        UrlStatService.main(null);
359 jmachado 229
//        AbstractDao.getCurrentSession().beginTransaction();
230
//        List<String> relativePaths = new ArrayList<String>();
231
//        relativePaths.add("/public/announcements/getFlashNews.jsp?sid=0.9998549583612295");
232
        1.5.0/docs/api/java/lang/System.html">System.out.println(URIUtil.decode(URIUtil.encodeWithinQuery("/public/announcements/getFlashNews.jsp?sid=0.9998549583612295&jorge=j","ISO-8859-1")));
18 jmachado 233
//        relativePaths.add("/teste2");
359 jmachado 234
//        System.out.println(new ChartBuilderService().run(new TestHttpServletRequest(),relativePaths, ChartTypeEnum.weekDays));
235
//        System.out.println(new ChartBuilderService().run(new TestHttpServletRequest(),relativePaths, ChartTypeEnum.monthDays));
236
//        System.out.println(new ChartBuilderService().run(new TestHttpServletRequest(),relativePaths, ChartTypeEnum.trimestreDays));
237
//        System.out.println(new ChartBuilderService().run(new TestHttpServletRequest(),relativePaths, ChartTypeEnum.semestreDays));
238
//        System.out.println(new ChartBuilderService().run(new TestHttpServletRequest(),relativePaths, ChartTypeEnum.yearDays));
239
//        System.out.println(new ChartBuilderService().run(new TestHttpServletRequest(),relativePaths, ChartTypeEnum.trimestreMonths));
240
//        System.out.println(new ChartBuilderService().run(new TestHttpServletRequest(),relativePaths, ChartTypeEnum.semestreMonths));
241
//        System.out.println(new ChartBuilderService().run(new TestHttpServletRequest(),relativePaths, ChartTypeEnum.yearMonths));
242
//        System.out.println(new ChartBuilderService().run(new TestHttpServletRequest(),relativePaths, ChartTypeEnum.twoYearsMonths));
243
//        AbstractDao.getCurrentSession().getTransaction().commit();
18 jmachado 244
    }
245
 
246
}