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

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

  ViewVC Help
Powered by ViewVC 1.1.20