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

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

  ViewVC Help
Powered by ViewVC 1.1.20