/[projects]/android/TrainInfoService/src/dk/thoerup/traininfoservice/RequestPlotter.java
ViewVC logotype

Diff of /android/TrainInfoService/src/dk/thoerup/traininfoservice/RequestPlotter.java

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 801 by torben, Mon Jun 7 11:29:55 2010 UTC revision 1560 by torben, Fri Jul 8 14:56:01 2011 UTC
# Line 2  package dk.thoerup.traininfoservice; Line 2  package dk.thoerup.traininfoservice;
2    
3  import java.io.BufferedReader;  import java.io.BufferedReader;
4  import java.io.ByteArrayOutputStream;  import java.io.ByteArrayOutputStream;
5    import java.io.File;
6  import java.io.FileInputStream;  import java.io.FileInputStream;
7    import java.io.FilenameFilter;
8  import java.io.IOException;  import java.io.IOException;
9    import java.io.InputStream;
10  import java.io.InputStreamReader;  import java.io.InputStreamReader;
11  import java.text.ParseException;  import java.text.ParseException;
12  import java.text.SimpleDateFormat;  import java.text.SimpleDateFormat;
13  import java.util.ArrayList;  import java.util.ArrayList;
14    import java.util.Arrays;
15  import java.util.Date;  import java.util.Date;
16  import java.util.List;  import java.util.List;
17    import java.util.Map;
18  import java.util.logging.Level;  import java.util.logging.Level;
19  import java.util.logging.Logger;  import java.util.logging.Logger;
20  import java.util.zip.ZipEntry;  import java.util.zip.ZipEntry;
21  import java.util.zip.ZipOutputStream;  import java.util.zip.ZipOutputStream;
22    
23  import javax.servlet.ServletException;  import javax.servlet.ServletException;
24    import javax.servlet.annotation.WebServlet;
25  import javax.servlet.http.HttpServlet;  import javax.servlet.http.HttpServlet;
26  import javax.servlet.http.HttpServletRequest;  import javax.servlet.http.HttpServletRequest;
27  import javax.servlet.http.HttpServletResponse;  import javax.servlet.http.HttpServletResponse;
28    
29    import dk.thoerup.genericjavautils.HttpUtil;
30    import dk.thoerup.genericjavautils.TimeoutMap;
31    
32    @WebServlet(urlPatterns={"/RequestPlotter"})
33  public class RequestPlotter extends HttpServlet {  public class RequestPlotter extends HttpServlet {
34          private static final long serialVersionUID = 1L;          private static final long serialVersionUID = 1L;
35    
# Line 27  public class RequestPlotter extends Http Line 37  public class RequestPlotter extends Http
37    
38          static final String KML = "application/vnd.google-earth.kml";          static final String KML = "application/vnd.google-earth.kml";
39          static final String KMZ = "application/vnd.google-earth.kmz";          static final String KMZ = "application/vnd.google-earth.kmz";
40            
41            Map<String,String> cache = new TimeoutMap<String,String>(30*60*1000);
42    
43          class RequestPosition {          class RequestPosition {
44                  public String ip;                  public String ip;
# Line 34  public class RequestPlotter extends Http Line 46  public class RequestPlotter extends Http
46                  public String lat;                  public String lat;
47                  public String lng;                  public String lng;
48          }          }
49            
50            class PositionContainer {
51                    List<RequestPosition> blue = new ArrayList<RequestPosition>();
52                    List<RequestPosition> green = new ArrayList<RequestPosition>();
53                    List<RequestPosition> yellow = new ArrayList<RequestPosition>();
54                    List<RequestPosition> red = new ArrayList<RequestPosition>();
55            }
56    
57    
58            boolean isGz(String fileStr) {
59                    return fileStr.substring(fileStr.length() - 3).equals(".gz");
60            }
61            
62            public static File[] getFiles(int count) {
63                    File accessLogDir = new File("/home/app/domain1/logs/access/");
64                    //File accessLogDir = new File("/home/torben/inst/glassfishv3/glassfish/domains/domain1/logs/access/");
65                    
66                    File logFiles[] = accessLogDir.listFiles( new FilenameFilter() {
67                            @Override
68                            public boolean accept(File dir, String name) {
69                                    //log.info("name:" + name);
70                                    return name.startsWith("server_access_log");
71                            }                      
72                    });
73                    
74                    Arrays.sort(logFiles);
75                    
76                    if (logFiles == null) {                
77                            File[] empty = {};
78                            log.info("file array was empty");
79                            return empty;
80                    }
81                    
82                    int from = (count>logFiles.length) ? 0 : logFiles.length - (count);
83                    int to = logFiles.length;
84                                    
85                    return Arrays.copyOfRange(logFiles, from, to);  
86            }
87            
88            protected PositionContainer getRequestsFromFileWorker(int  count) throws IOException{
89                    PositionContainer positions = new PositionContainer();
90    
91          protected List<RequestPosition> getRequestsFromFile() throws IOException{                  try {                  
92                  List<RequestPosition> positions = new ArrayList<RequestPosition>();                          
93                            File files[] = getFiles(count);
                 try {  
                         FileInputStream fis = new FileInputStream("/var/log/apache2/app_access.log");  
                         BufferedReader in = new BufferedReader( new InputStreamReader(fis) );  
94    
95                          SimpleDateFormat df = new SimpleDateFormat("dd/MMM/yyyy:HH:mm:ss");                          SimpleDateFormat df = new SimpleDateFormat("dd/MMM/yyyy:HH:mm:ss");
96                    
97                          String line;                          Date now = new Date();
98                          while ( (line=in.readLine()) != null) {                          for (File f : files ) {
99                                  if (line.indexOf("LocateStation") == -1 ){                                  log.info("Parsing file: "  + f.getName() );
100                                    
101                                    if ( !f.exists() ) {
102                                          continue;                                          continue;
103                                  }                                  }
104                                    
105                                  if (line.indexOf("latitude") == -1 ) {                                  
106                                          continue;                                  InputStream input  = new FileInputStream(f);
107    
108                                    
109                                    BufferedReader in = new BufferedReader( new InputStreamReader(input) );
110    
111            
112                                    String line;
113                                    while ( (line=in.readLine()) != null) {
114                                            if (line.indexOf("LocateStation") == -1 ){
115                                                    continue;
116                                            }
117            
118                                            if (line.indexOf("latitude=") == -1 ) {
119                                                    continue;
120                                            }
121                                            
122                                            if (line.indexOf("longitude=") == -1) {
123                                                    continue;
124                                            }
125                                            
126                                            
127                                            
128                                            RequestPosition pos = new RequestPosition();
129            
130                                            String toks[] = line.split(" ");
131                                            pos.ip = toks[0].replaceAll("\"", "");
132            
133                                            pos.time = df.parse( toks[2].replace("\"", "") );
134            
135                                            Map<String,String> params = HttpUtil.decodeUri( toks[5] );                                      
136            
137                                            pos.lat = params.get("latitude");
138                                            pos.lng = params.get("longitude");
139                                            
140                                            
141                                            long timediff = now.getTime() - pos.time.getTime();                                    
142                                            if ( timediff < (3*60*60*1000) ) {
143                                                    positions.red.add(pos); //RED
144                                            } else if ( timediff < (24*60*60*1000)) {
145                                                    positions.yellow.add(pos); //YELLOW
146                                            } else if ( timediff < (7*24*60*60*1000)) {
147                                                    positions.green.add(pos); //GREEN
148                                            } else {
149                                                    positions.blue.add(pos); //BLUE
150                                            }
151            
152                                  }                                  }
153                                  RequestPosition pos = new RequestPosition();                                  in.close();
154                                    input.close();
155                                  String toks[] = line.split(" ");                                  
156                                  pos.ip = toks[0];                          }
157                    } catch (ParseException pe) {
158                            log.log(Level.SEVERE, "parseException", pe);
159                            throw new IOException(pe);
160                    } catch (IOException e) {
161                            log.log(Level.SEVERE, "getKml()", e);
162                            throw e;
163                    }
164    
165                                  pos.time = df.parse( toks[3].replace("[", "") );                  return positions;
166            }
167    
168                                  String argpart = toks[6].split("\\?")[1];          
169            /* old apache code
170            protected PositionContainer getRequestsFromFileWorker(boolean multiple) throws IOException{
171                    PositionContainer positions = new PositionContainer();
172    
173                                  String args[] = argpart.split("&");                  try {
174                            String files_single[] = {"/var/log/apache2/app_access.log"};
175                            String files_multi[] = {"/var/log/apache2/app_access.log.3.gz", "/var/log/apache2/app_access.log.2.gz", "/var/log/apache2/app_access.log.1", "/var/log/apache2/app_access.log"};
176                            
177                            String files[];
178                            
179                            if (multiple == false) {
180                                    files = files_single;
181                            } else {
182                                    files = files_multi;
183                            }
184    
185                                  pos.lat = args[0].split("=")[1];                          SimpleDateFormat df = new SimpleDateFormat("dd/MMM/yyyy:HH:mm:ss");
186                                  pos.lng = args[1].split("=")[1];                  
187                            Date now = new Date();
188                            for (String fileStr : files ) {
189                                    File f = new File(fileStr);
190                                    if ( !f.exists() ) {
191                                            continue;
192                                    }
193                                    
194                                    FileInputStream fis = new FileInputStream(fileStr);
195                                    
196                                    InputStream input;
197                                    if ( isGz(fileStr)) {
198                                            input = new GZIPInputStream(fis);
199                                    } else {
200                                            input = fis;
201                                    }
202                                    
203                                    BufferedReader in = new BufferedReader( new InputStreamReader(input) );
204    
205                                  positions.add(pos);          
206                                    String line;
207                                    while ( (line=in.readLine()) != null) {
208                                            if (line.indexOf("LocateStation") == -1 ){
209                                                    continue;
210                                            }
211            
212                                            if (line.indexOf("latitude=") == -1 ) {
213                                                    continue;
214                                            }
215                                            
216                                            if (line.indexOf("longitude=") == -1) {
217                                                    continue;
218                                            }
219                                            
220                                            RequestPosition pos = new RequestPosition();
221            
222                                            String toks[] = line.split(" ");
223                                            pos.ip = toks[0];
224            
225                                            pos.time = df.parse( toks[3].replace("[", "") );
226            
227                                            String argpart = toks[6].split("\\?")[1];
228            
229                                            String args[] = argpart.split("&");
230            
231                                            pos.lat = args[0].split("=")[1];
232                                            pos.lng = args[1].split("=")[1];
233                                            
234                                            
235                                            long timediff = now.getTime() - pos.time.getTime();                                    
236                                            if ( timediff < (3*60*60*1000) ) {
237                                                    positions.red.add(pos); //RED
238                                            } else if ( timediff < (24*60*60*1000)) {
239                                                    positions.yellow.add(pos); //YELLOW
240                                            } else if ( timediff < (7*24*60*60*1000)) {
241                                                    positions.green.add(pos); //GREEN
242                                            } else {
243                                                    positions.blue.add(pos); //BLUE
244                                            }
245            
246                                    }
247                                    in.close();
248                                    input.close();
249                                    fis.close();
250                          }                          }
251                  } catch (ParseException pe) {                  } catch (ParseException pe) {
252                          log.log(Level.SEVERE, "parseException", pe);                          log.log(Level.SEVERE, "parseException", pe);
# Line 80  public class RequestPlotter extends Http Line 257  public class RequestPlotter extends Http
257                  }                  }
258    
259                  return positions;                  return positions;
260            }*/
261            
262            protected void formatPositions(StringBuilder sb, String color, List<RequestPosition> list) {
263                    sb.append( "<Folder>\n");
264                    sb.append( " <name>" ).append(color).append("</name>\n");
265                    sb.append( " <open>0</open>\n" );
266                    
267                    int count=0;
268                    for(RequestPosition current : list) {
269                            String id = color + count++;
270                            sb.append( " <Placemark id=\"" + id + "\">\n" );
271                            sb.append( "  <name>").append(current.time).append("</name>\n" );
272                            sb.append( "  <styleUrl>#").append(color).append("</styleUrl>\n" );
273                            sb.append( "  <description><![CDATA[IP=").append(current.ip).append("<br/> ]]></description>\n" );
274                            sb.append( "  <Point><coordinates>").append(current.lng).append(",").append(current.lat).append(",0</coordinates></Point>\n" );
275                            sb.append( " </Placemark>\n" );                
276                    }              
277                    
278                    sb.append("</Folder>\n");
279          }          }
280    
281          protected String formatXml(List<RequestPosition> list) {          protected String formatXml(PositionContainer positions) {
282                  StringBuilder sb = new StringBuilder();                  StringBuilder sb = new StringBuilder(1024*1024);
283    
284                  sb.append( "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" );                  sb.append( "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" );
285                  sb.append( "<kml xmlns=\"http://www.opengis.net/kml/2.2\">\n" );                  sb.append( "<kml xmlns=\"http://www.opengis.net/kml/2.2\">\n" );
286                  sb.append( "<Document>\n" );                              sb.append( "<Document>\n" );            
287                    sb.append( " <description><![CDATA[");
288                    sb.append( "  Red:").append(positions.red.size()).append(" (whithin 3 hours)<br/>\n");
289                    sb.append( "  Yellow:").append(positions.yellow.size()).append(" (within 24 hours)<br/>\n");
290                    sb.append( "  Green:").append(positions.green.size()).append(" (within one week)<br/>\n");
291                    sb.append( "  Blue:").append(positions.blue.size()).append(" (older)<br/>\n");          
292                    sb.append( " ]]></description>");
293                                    
294                                    
295                  sb.append( " <Style id=\"red\">\n" );                  sb.append( " <Style id=\"red\">\n" );
# Line 102  public class RequestPlotter extends Http Line 304  public class RequestPlotter extends Http
304                  sb.append( "  <IconStyle><Icon><href>http://maps.google.com/mapfiles/kml/paddle/grn-circle.png</href></Icon></IconStyle>\n" );                  sb.append( "  <IconStyle><Icon><href>http://maps.google.com/mapfiles/kml/paddle/grn-circle.png</href></Icon></IconStyle>\n" );
305                  sb.append( " </Style>\n\n" );                  sb.append( " </Style>\n\n" );
306                                    
307                    sb.append( " <Style id=\"blue\">\n" );
308                    sb.append( "  <IconStyle><Icon><href>http://maps.google.com/mapfiles/kml/paddle/blu-circle.png</href></Icon></IconStyle>\n" );
309                    sb.append( " </Style>\n\n" );          
310  /*  /*
311                  String overlay =                  String overlay =
312                " <ScreenOverlay>" +                " <ScreenOverlay>" +
# Line 121  public class RequestPlotter extends Http Line 326  public class RequestPlotter extends Http
326          */                */      
327                                    
328    
329                    formatPositions(sb, "red", positions.red);
330                    formatPositions(sb, "yellow", positions.yellow);
331                    formatPositions(sb, "green", positions.green);
332                    formatPositions(sb, "blue", positions.blue);
333                    
334    
335                    sb.append( "</Document>\n" );
336                    sb.append( "</kml>\n" );
337    
338                    return sb.toString();
339            }
340                  Date now = new Date();          
341                  for(RequestPosition current : list) {          protected String getRequestsFromFile(int count) throws IOException {            
342                                            String kmlData = null;
343                          String style;                  String key;
344                          long timediff = now.getTime() - current.time.getTime();                  
345                                            key = "kmldata-" + count;
346                          if ( timediff < (3*60*60*1000) ) {                                          
347                                  style = "#red";                  kmlData = cache.get(key);
                         } else if ( timediff < (24*60*60*1000)) {  
                                 style = "#yellow";  
                         } else {  
                                 style = "#green";  
                         }  
348                                                    
349                          sb.append( " <Placemark>\n" );                  if (kmlData == null) {
350                          sb.append( "  <styleUrl>" + style + "</styleUrl>\n" );                          kmlData = formatXml( getRequestsFromFileWorker(count) );
351                          sb.append( "  <description>IP=" + current.ip + "  Time=" + current.time + "</description>\n" );                          cache.put(key, kmlData);
352                          sb.append( "  <Point><coordinates>" + current.lng + "," + current.lat + ",0</coordinates></Point>\n" );                          kmlData += "<!-- from source -->";                      
353                          sb.append( " </Placemark>\n" );                                  } else {
354                            kmlData += "<!-- cached -->";
355                  }                  }
356                                            
357                    return kmlData;
358            }
359            
360            boolean enabled(String param) {
361                    if (param == null || param.equals("")) {
362                            return false;
363                    }
364                    
365                    int p = 0;
366                    try {
367                            p = Integer.parseInt(param);
368                    } catch (Exception e) {}
369                    
370                    return (p != 0);
371            }
372    
373                  sb.append(  "</Document>\n" );          int getCount(String param) {
374                  sb.append( "</kml>\n" );                  if (param == null || param.equals("")) {
375                            return 1;
376                  return sb.toString();                  }
377                                    
378                    return Integer.parseInt(param);
379          }          }
380    
381            
382          @Override          @Override
383          protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {          protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
384                    
385                  String data = formatXml( getRequestsFromFile() );                  
386                    int count = getCount( req.getParameter("count") );
387                  if (req.getParameter("zip") != null) {                  
388                    if (count > 30) //limit to 30 days
389                            count = 30;
390                    if (count < 0) //negative count is not allowed
391                            count = 0;
392                    
393                    String kmlData = getRequestsFromFile(count);
394                    
395                    if ( enabled(req.getParameter("zip")) ) {
396    
397                          ByteArrayOutputStream baos = new ByteArrayOutputStream();                          ByteArrayOutputStream baos = new ByteArrayOutputStream();
398    
399                          ZipOutputStream zip = new ZipOutputStream(baos);                          ZipOutputStream zip = new ZipOutputStream(baos);
400                          zip.putNextEntry( new ZipEntry("trains.kml") );                          zip.putNextEntry( new ZipEntry("trains.kml") );
401                          zip.write( data.getBytes() );                          zip.write( kmlData.getBytes() );
402                          zip.closeEntry();                          zip.closeEntry();
403                          zip.close();                          zip.close();
404    
405                          byte bytes[] = baos.toByteArray();                          byte bytes[] = baos.toByteArray();
406    
407                          resp.setContentType(KMZ);                          resp.setContentType(KMZ);
408                          resp.setContentLength( bytes.length );                          resp.setHeader("Content-Disposition", "attachment; filename=Traininfo-requestplotter.kmz");
409                            resp.setContentLength( bytes.length );                  
410                          resp.getOutputStream().write(bytes);                          resp.getOutputStream().write(bytes);
411    
412                  } else {                  } else {
413                          resp.setContentType(KML);                          byte bytes[] = kmlData.getBytes();
414                          resp.getWriter().print( data );                          
415                            resp.setContentType(KML);                      
416                            resp.setContentLength( bytes.length );
417                            resp.getOutputStream().write(bytes);
418                  }                  }
419          }          }
420  }  }

Legend:
Removed from v.801  
changed lines
  Added in v.1560

  ViewVC Help
Powered by ViewVC 1.1.20