org.androidpn.server.console.controller.OnlineStatusController.java Source code

Java tutorial

Introduction

Here is the source code for org.androidpn.server.console.controller.OnlineStatusController.java

Source

/*
 * Copyright (C) 2010 Moduad Co., Ltd.
 * 
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */
package org.androidpn.server.console.controller;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.androidpn.server.dao.hibernate.Order;
import org.androidpn.server.model.OnlineRecord;
import org.androidpn.server.model.OnlineUserCount;
import org.androidpn.server.model.User;
import org.androidpn.server.service.OnlineRecordService;
import org.androidpn.server.service.OnlineUserCountService;
import org.androidpn.server.service.ServiceLocator;
import org.androidpn.server.service.UserNotFoundException;
import org.androidpn.server.service.UserService;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;

/**
 * A controller class to process the user online status.
 * 
 */
public class OnlineStatusController extends MultiActionController {

    private UserService userService;
    private OnlineRecordService onlineService;
    private OnlineUserCountService onlineUserCountService;

    public OnlineStatusController() {
        userService = ServiceLocator.getUserService();
        onlineService = ServiceLocator.getOnlineRecordService();
        onlineUserCountService = ServiceLocator.getOnlineUserCountService();
    }

    public ModelAndView list(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String username = request.getParameter("username");
        ModelAndView mav = new ModelAndView();
        mav.addObject("username", username);
        mav.setViewName("online/list");
        return mav;
    }

    public ModelAndView query(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String username = request.getParameter("username");
        ModelAndView mav = new ModelAndView();
        mav.addObject("username", username);
        mav.setViewName("online/query");
        return mav;
    }

    public ModelAndView getChart(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String username = request.getParameter("username");
        User user = null;
        try {
            user = userService.getUserByUsername(username);
        } catch (UserNotFoundException e) {
            e.printStackTrace();
            //         return ;
        }

        String startTimeStr = request.getParameter("start");
        String endTimeStr = request.getParameter("end");
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date endTime = endTimeStr == null ? new Date() : format.parse(endTimeStr);
        Date startTime = startTimeStr == null ? new Date() : format.parse(startTimeStr);

        List<OnlineRecord> list = this.getOnlineList(user, startTime, endTime);

        //   System.out.println(format.format(startTime)+"-"+format.format(endTime)+": find" + list.size());

        ModelAndView mav = new ModelAndView();
        mav.addObject("list", list);
        mav.setViewName("online/chart");
        return mav;
    }

    public ModelAndView getCountChart(HttpServletRequest request, HttpServletResponse response) throws Exception {

        String startTimeStr = request.getParameter("start");
        String endTimeStr = request.getParameter("end");
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date endTime = endTimeStr == null ? new Date() : format.parse(endTimeStr);
        Date startTime = startTimeStr == null ? new Date() : format.parse(startTimeStr);

        List<OnlineUserCount> list = onlineUserCountService.getAllRecords(startTime, endTime, "time", Order.asc);

        ModelAndView mav = new ModelAndView();
        mav.addObject("list", list);
        mav.setViewName("online/chart_count");
        return mav;
    }

    // get online list
    public List<OnlineRecord> getOnlineList(User user, Date startTime, Date endTime) {
        List<OnlineRecord> list = onlineService.getOnlineRecords(user, startTime, endTime, "time", Order.desc);

        //0????loginlogout?
        if (list != null && list.size() == 0) {
            List<OnlineRecord> before = onlineService.getOnlineRecords(user, null, startTime, "time", Order.desc);
            List<OnlineRecord> after = onlineService.getOnlineRecords(user, endTime, null, "time", Order.asc);
            //?loginstartTimelogin
            if (before.size() > 0 && before.get(0).getAction().equals(OnlineRecord.Action.login)) {
                OnlineRecord record = new OnlineRecord(user, OnlineRecord.Action.login, startTime);
                list.add(list.size(), record);
            }
            //?logoutendTimelogout
            if (after.size() > 0 && after.get(0).getAction().equals(OnlineRecord.Action.logout)) {
                OnlineRecord record = new OnlineRecord(user, OnlineRecord.Action.logout, endTime);
                list.add(0, record);
            }
        }

        if (list == null || list.size() <= 0) {
            return new ArrayList<OnlineRecord>();
        }

        //loginendTimeendTime
        if (OnlineRecord.Action.login.equals(list.get(0).getAction())) {
            OnlineRecord record = new OnlineRecord(user, OnlineRecord.Action.logout, endTime);
            list.add(0, record);
        }
        //?logoutstartTimestartTime
        if (OnlineRecord.Action.logout.equals(list.get(list.size() - 1).getAction())) {
            OnlineRecord record = new OnlineRecord(user, OnlineRecord.Action.login, startTime);
            list.add(list.size(), record);
        }
        return list;
    }

    //   public JFreeChart createPieChart(List<OnlineRecord> list, Date startTime, Date endTime, String title) {
    //      
    //      Map<String, Long> map = this.getPieChartData(list, startTime, endTime);
    //      
    //      DefaultPieDataset dpd = new DefaultPieDataset();
    //      Set<String> keys = map.keySet();
    //      for(String key : keys) {
    //         dpd.setValue(key, map.get(key));
    //      }
    //      
    //      //?????Legend??????URL
    //      JFreeChart chart = ChartFactory.createPieChart(title, dpd, true, true, false); 
    //      chart.setTitle(new TextTitle(title, titleFont));
    ////      chart.setBackgroundPaint(bgColor); //
    //      
    //      PiePlot pieplot = (PiePlot)chart.getPlot(); //
    ////       pieplot.setLabelFont(labelFont); //
    ////       pieplot.setNoDataMessage("No data available"); //?
    //       pieplot.setCircular(true); //true false
    ////       pieplot.setLabelGap(0.01D);//?
    //       //("{0}: ({1}{2})")??{0}section??{1}section{2}?new DecimalFormat("0.00%")????
    //      NumberFormat nf = NumberFormat.getInstance();
    //      nf.setMaximumFractionDigits(0);
    //       StandardPieSectionLabelGenerator generator = new StandardPieSectionLabelGenerator(("{0}:{1},{2}"), nf, new DecimalFormat("0%"));
    //       pieplot.setLabelGenerator(generator);
    //       // section 
    ////       pieplot.setBaseSectionOutlinePaint(new Color(0xF7, 0x79, 0xED));
    //        // section 
    ////       pieplot.setSectionOutlineStroke(new BasicStroke(0));
    //        // section        
    //       pieplot.setSectionPaint("offline", Color.gray);        
    //       pieplot.setSectionPaint("online", Color.blue); 
    //       
    //      return chart;
    //   }
    //   
    //   public Map<String, Long> getPieChartData(List<OnlineRecord> list, Date startTime, Date endTime) {
    //      Map<String, Long> map = new HashMap<String, Long>();
    //      
    //      Date logout = null;
    //      Date login = null;
    //      Long onlineTime = 0l;
    //      for(int j=0; j<list.size(); j++) {
    //         OnlineRecord r = list.get(j);
    //         if(OnlineRecord.Action.logout.equals(r.getAction())) {
    //            logout = r.getTime();
    //         } else if(OnlineRecord.Action.login.equals(r.getAction()) && logout != null){
    //            login = r.getTime();
    //            onlineTime += logout.getTime()-login.getTime();
    //            logout = null;
    //         }
    //      }
    //      
    //      Long minute = 1000l*60;   
    //      map.put("offline", (endTime.getTime()-startTime.getTime()-onlineTime) /minute);
    //      map.put("online", onlineTime /minute );
    //
    //      return map;
    //   }
    //   
    //   @SuppressWarnings("deprecation")
    //   public JFreeChart createLineChart(List<OnlineRecord> list, Date startTime, Date EndTime, Class periodClz, 
    //         String title, String xLabel, String yLabel) {
    //      
    //      Map<RegularTimePeriod, Double> map = this.getLineChartData(list, periodClz, startTime, EndTime, yLabel);
    //      
    //      //??
    //      TimeSeries timeSeries = new TimeSeries("", periodClz);
    //      TimeSeries averageTS = new TimeSeries("?", periodClz);
    //      Double total = 0d;
    //      Set<RegularTimePeriod> keys = map.keySet();
    //      for(RegularTimePeriod key : keys) {
    //         timeSeries.add(key, map.get(key));
    //         total += map.get(key);
    //      }
    //      Double average = total/map.size();
    //      for(RegularTimePeriod key : keys) {
    //         averageTS.add(key, average);
    //      }
    //      
    //      //?collection?
    //      TimeSeriesCollection lineDataset = new TimeSeriesCollection();
    //      lineDataset.addSeries(timeSeries);
    //      lineDataset.addSeries(averageTS);
    //      
    ////      lineDataset.setDomainIsPointsInTime(true); //x?
    //      
    //      //??: legend:?,true?????     tooltips:??    urls:??URL
    //      JFreeChart chart = ChartFactory.createTimeSeriesChart(title, "", "/"+yLabel, lineDataset, true, false, false); 
    //      chart.setTitle(new TextTitle(title, titleFont));
    //
    ////      //?
    ////      TextTitle subtitle = new TextTitle(title, new Font("", Font.BOLD, 12)); 
    ////      chart.addSubtitle(subtitle);
    //
    //      //
    //      chart.setAntiAlias(true);
    //
    //      //???,??????x?y?
    //      XYPlot plot = (XYPlot) chart.getPlot(); 
    //      plot.setBackgroundPaint(Color.lightGray); //?
    //      plot.setAxisOffset(new RectangleInsets(5D, 5D, 5D, 5D)); //????
    //      plot.setDomainGridlinePaint(Color.white); //?
    //      plot.setRangeGridlinePaint(Color.white); //?
    //      
    //      //?
    //      XYLineAndShapeRenderer xylineandshaperenderer = (XYLineAndShapeRenderer)plot.getRenderer();
    //      xylineandshaperenderer.setBaseShapesVisible(false);  //???
    //      xylineandshaperenderer.setStroke(new BasicStroke(1.5f)); //?
    //      xylineandshaperenderer.setSeriesFillPaint(0, Color.BLUE);  //??
    //      xylineandshaperenderer.setSeriesFillPaint(1, Color.red);  //
    ////      xylineandshaperenderer.setUseFillPaint(false); 
    //
    //      
    //      
    //      //???
    //        xylineandshaperenderer.setBaseItemLabelsVisible(true);  
    //        xylineandshaperenderer.setBasePositiveItemLabelPosition(new ItemLabelPosition(  
    //        ItemLabelAnchor.OUTSIDE12, TextAnchor.BASELINE_CENTER));  
    //        xylineandshaperenderer.setBaseItemLabelGenerator(new MyGenerator());  
    ////        xylineandshaperenderer.setBaseItemLabelPaint(new Color(102, 102, 102));
    //      
    //      //???
    //      NumberAxis numAxis = (NumberAxis)plot.getRangeAxis();
    //      DateAxis  dateaxis =   (DateAxis)plot.getDomainAxis();
    //
    //      //x?
    //      SimpleDateFormat sdf = null;
    //      DateTickUnit dtu = null; 
    //      int interval = 1;
    //      int max = 14;
    //      if(map.size()>max) {
    //         interval = map.size()/max + 1; //????
    //      }
    //      if(periodClz == Day.class){ 
    //         sdf = new SimpleDateFormat("MM-dd");
    //         dtu = new DateTickUnit(DateTickUnit.DAY, interval);
    //      } else if(periodClz == Month.class) {
    //         sdf = new SimpleDateFormat("yyyy-MM");
    //         dtu = new DateTickUnit(DateTickUnit.MONTH, interval);
    //      } else if(periodClz == Hour.class) {
    //         sdf = new SimpleDateFormat("HH:00");
    //         dtu = new DateTickUnit(DateTickUnit.HOUR, interval);
    //      } else if(periodClz == Minute.class) {
    //         sdf = new SimpleDateFormat("HH:mm");
    //         dtu = new DateTickUnit(DateTickUnit.MINUTE, interval);
    //      }
    //      dateaxis.setDateFormatOverride(sdf);
    //      dateaxis.setTickUnit(dtu); 
    //      
    //      //y?
    //      numAxis.setAutoTickUnitSelection(true);//???
    //      NumberFormat nf = NumberFormat.getInstance();
    //      if("?".endsWith(yLabel) || "".endsWith(yLabel)) {
    //         nf.setMaximumFractionDigits(1); // ???1?
    //      } else if("".endsWith(yLabel) || "".endsWith(yLabel)){
    //         nf.setMaximumFractionDigits(0); //????
    //      } else {
    //         nf.setMaximumFractionDigits(1); //???
    //      }
    //      nf.setMaximumFractionDigits(1);
    //      numAxis.setNumberFormatOverride(nf);//y?? 
    //            
    //      return chart;
    //   }
    //   
    //   class MyGenerator extends StandardXYItemLabelGenerator {
    //      private static final long serialVersionUID = 1L;
    //      String last = "";
    //      @Override
    //      public String generateLabelString(XYDataset dataset, int series, int item) {
    //         String result = "";
    //         //??seriesitem???if(....)?"";
    //         if(series == 1 && item != 0) {
    //            result = "";
    //         } else {
    ////            result = super.generateLabelString(dataset,series,item);//??   
    //
    //            TimeSeriesCollection tsc = (TimeSeriesCollection) dataset;
    //            Number n = dataset.getY(series, item);
    //            Class clz = tsc.getSeries(series).getTimePeriodClass();
    //            NumberFormat nf = NumberFormat.getInstance();
    //            if(clz == Month.class || clz == Day.class) {
    //               nf.setMaximumFractionDigits(1); // x??1?
    //            } else if(clz == Hour.class || clz == Minute.class || clz == Second.class){
    //               nf.setMaximumFractionDigits(0); //x?????
    //            } else {
    //               nf.setMaximumFractionDigits(1); //???
    //            }
    //            result = nf.format(n);
    //            
    //            if(!result.equals("") && result.equals(last)) {
    //               result = ""; //???
    //            } else {
    //               last = result;
    //            }
    //         }
    //         return result;
    //      }
    //   }
    //   
    //   @SuppressWarnings("unchecked")
    //   public Map<RegularTimePeriod, Double> getLineChartData(List<OnlineRecord> list, Class periodClz, 
    //         Date startTime, Date endTime, String yAxisLabel) {
    //      Map<RegularTimePeriod, Double> map = new HashMap<RegularTimePeriod, Double>();
    //      RegularTimePeriod rtp = RegularTimePeriod.createInstance(periodClz, startTime, TimeZone.getDefault());
    //      RegularTimePeriod endRtp = RegularTimePeriod.createInstance(periodClz, endTime, TimeZone.getDefault());
    //      while(rtp.compareTo(endRtp)<=0) {
    //         map.put(rtp, 0d);
    //         rtp = rtp.next();
    //      }
    //      //?value=0map
    //      if(list == null || list.size()<=0) {
    //         return map;
    //      }
    //      Date logout = null;
    //      Date login = null;
    //      for(int j=0; j<list.size(); j++) {
    //         OnlineRecord r = list.get(j);
    //         if(OnlineRecord.Action.logout.equals(r.getAction())) {
    //            logout = r.getTime();
    //         } else if(OnlineRecord.Action.login.equals(r.getAction()) && logout != null){
    //            login = r.getTime();
    //            RegularTimePeriod rtpLogin = RegularTimePeriod.createInstance(periodClz, login, TimeZone.getDefault());
    //            RegularTimePeriod rtpLogout = RegularTimePeriod.createInstance(periodClz, logout, TimeZone.getDefault());
    //            
    //            if(rtpLogout.equals(rtpLogin)) {
    //               //??
    //               Long online = logout.getTime() - login.getTime();
    //               map.put(rtpLogout, map.get(rtpLogout) + online);
    //            } else if(rtpLogout.compareTo(rtpLogin)>0){
    //               //???
    //               while(!rtpLogout.equals(rtpLogin)) {
    //                  Long online = logout.getTime() - rtpLogout.getFirstMillisecond() + 1;                  
    //                  map.put(rtpLogout, map.get(rtpLogout) + online);
    //                  rtpLogout = rtpLogout.previous();
    //                  logout = rtpLogout.getEnd();
    //               }
    //               //rtpLogout???
    //               Long online = logout.getTime() - login.getTime();
    //               map.put(rtpLogout, map.get(rtpLogout) + online);
    //            }
    //            logout = null;
    //         }
    //      }
    //      
    //      Long unit = 1000l*60;
    //      if("?".endsWith(yAxisLabel)) {
    //         unit = 1000l*60*60; //1?
    //      } else if("".endsWith(yAxisLabel)) {
    //         unit = 1000l*60*60*24; //1
    //      } else if("".endsWith(yAxisLabel)) {
    //         unit = 1000l; //1
    //      } else {
    //         unit = 1000l*60; //1
    //      }
    //      
    //      Set<RegularTimePeriod> keys = map.keySet();
    //      for(RegularTimePeriod key : keys) {
    //         map.put(key, map.get(key)/unit);
    //      }
    //      
    //      return map;
    //   }
    //
    //
    //   public String saveChartAsPNG(JFreeChart chart, int width, int height, HttpSession session) {
    //      String filename = null;
    //      try {
    //         filename = ServletUtilities.saveChartAsPNG(chart, width, height, null, session);
    //      } catch (IOException e) {
    //         e.printStackTrace();
    //      }
    //      return filename;
    //   }
    //   
}