KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > server > uihandler > LogsManager


1 /*
2  * The contents of this file are subject to the terms of the Common Development
3  * and Distribution License (the License). You may not use this file except in
4  * compliance with the License.
5  *
6  * You can obtain a copy of the License at http://www.netbeans.org/cddl.html
7  * or http://www.netbeans.org/cddl.txt.
8  *
9  * When distributing Covered Code, include this CDDL Header Notice in each file
10  * and include the License file at http://www.netbeans.org/cddl.txt.
11  * If applicable, add the following below the CDDL Header, with the fields
12  * enclosed by brackets [] replaced by your own identifying information:
13  * "Portions Copyrighted [year] [name of copyright owner]"
14  *
15  * The Original Software is NetBeans. The Initial Developer of the Original
16  * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
17  * Microsystems, Inc. All Rights Reserved.
18  */

19
20 package org.netbeans.server.uihandler;
21
22 import java.util.concurrent.ExecutionException JavaDoc;
23 import java.io.*;
24 import java.util.ArrayList JavaDoc;
25 import java.util.Collection JavaDoc;
26 import java.util.LinkedList JavaDoc;
27 import java.util.List JavaDoc;
28 import java.util.Map JavaDoc;
29 import java.util.concurrent.ConcurrentHashMap JavaDoc;
30 import java.util.concurrent.ExecutorService JavaDoc;
31 import java.util.concurrent.Executors JavaDoc;
32 import java.util.concurrent.Future JavaDoc;
33 import java.util.logging.Handler JavaDoc;
34 import java.util.logging.Level JavaDoc;
35 import java.util.logging.LogRecord JavaDoc;
36 import java.util.logging.Logger JavaDoc;
37 import javax.naming.Context JavaDoc;
38 import javax.naming.InitialContext JavaDoc;
39 import javax.naming.NamingException JavaDoc;
40 import javax.servlet.jsp.PageContext JavaDoc;
41 import org.netbeans.lib.uihandler.LogRecords;
42 import org.netbeans.server.uihandler.LogsManager.SessionInfo;
43 import org.openide.util.Exceptions;
44 import org.openide.util.Lookup;
45
46 /**
47  *
48  * @author Jaroslav Tulach
49  */

50 public class LogsManager extends Object JavaDoc implements Runnable JavaDoc {
51     static final Logger JavaDoc LOG = Logger.getLogger(LogsManager.class.getName());
52     
53     private File dir;
54     private transient Future JavaDoc<?> initTask;
55     private transient boolean closed;
56     /** maps IDs to list of Session infos */
57     private Map JavaDoc<String JavaDoc,UserInfo> sessions;
58     
59     /** statistics to work on and their global values */
60     private List JavaDoc<Value> statistics;
61     
62     /** executor to use for changing data */
63     private static final ExecutorService JavaDoc EXEC = Executors.newSingleThreadScheduledExecutor();
64     
65     private LogsManager(File userDir) {
66         this.dir = userDir;
67         this.statistics = new ArrayList JavaDoc<LogsManager.Value>();
68         for (Statistics<?> s : Lookup.getDefault().lookupAll(Statistics.class)) {
69             addStatisticsData(this.statistics, s);
70         }
71         this.initTask = EXEC.submit(this);
72     }
73     
74     static LogsManager createManager(File userDir) {
75         return new LogsManager(userDir);
76     }
77     
78     private static LogsManager DEFAULT;
79
80     /** Getter for the default LogsManager. Location of directories it shall operate
81      * on is looked up as "java:comp/env/uilogger/dir" from initial naming context.
82      *
83      * @return an instance of default manager
84      * @throws IllegalStateException if the directory cannot be obtained
85      */

86     public static synchronized LogsManager getDefault() {
87         if (DEFAULT == null) {
88             String JavaDoc dir = Utils.getVariable("dir", String JavaDoc.class); // NOI18N
89
if (dir == null) {
90                 return new LogsManager(null);
91             }
92             DEFAULT = createManager(new java.io.File JavaDoc(dir));
93         }
94         return DEFAULT;
95     }
96     
97     /** does initialization */
98     public void run() {
99         if (dir == null) {
100             LOG.warning("Specify dir attribute, otherwise the server cannot work");
101             return;
102         }
103         
104         
105         LOG.log(Level.INFO, "Initializing for {0}", dir);
106         
107         Map JavaDoc<String JavaDoc,UserInfo> s = new ConcurrentHashMap JavaDoc<String JavaDoc,UserInfo>();
108         File[] files = dir.listFiles();
109         int cnt = 0;
110         for (File f : files) {
111             handleAddNewLog(f, s, statistics, false);
112             LOG.log(Level.INFO, "Processed {0} from {1} files", new Object JavaDoc[] { cnt++, files.length });
113         }
114         
115         sessions = s;
116         
117         LOG.log(Level.INFO, "Sessions created for {0}", dir);
118     }
119     
120     private static void handleAddNewLog(
121         File f,
122         Map JavaDoc<String JavaDoc, UserInfo> s,
123         List JavaDoc<Value> statistics,
124         boolean initialParse
125     ) {
126         try {
127             String JavaDoc[] idSes = f.getName().split("\\.");
128             int ses = idSes.length == 1 ? 0 : Integer.parseInt(idSes[1]);
129
130             UserInfo list = s.get(idSes[0]);
131             if (list == null) {
132                 list = new UserInfo(statistics);
133                 s.put(idSes[0], list);
134             }
135             SessionInfo info = new SessionInfo(idSes[0], ses, f, statistics);
136             list.add(info);
137
138             for (Value<?> v : info.values) {
139                 finishUploadOpen(info, v, initialParse);
140             }
141
142             info.addValues(statistics);
143
144             LOG.log(Level.INFO, "Finished processing {0}", f);
145         } catch (Exception JavaDoc ex) {
146             LogRecord JavaDoc rec = new LogRecord JavaDoc(Level.WARNING, "Cannot process {0}");
147             rec.setThrown(ex);
148             rec.setParameters(new Object JavaDoc[] { f.getPath() });
149             LOG.log(rec);
150         }
151     }
152     
153     private static <Data> void finishUploadOpen(SessionInfo info, Value<Data> v, boolean initialParse) {
154         v.value = v.statistics.finishSessionUpload(info.id, info.session, initialParse, v.value);
155     }
156     
157     /** Close the LogsManager, stop parsing, etc. get ready for shutdown.
158      */

159     public void close() {
160         this.closed = true;
161         this.initTask.cancel(true);
162     }
163     
164     public void addLog(final File f) {
165         if (dir == null) {
166             LOG.warning("Specify dir attribute, otherwise the server cannot work");
167             return;
168         }
169         
170         class R implements Runnable JavaDoc {
171             public void run() {
172                 if (closed) {
173                     LOG.info("Processing cancelled");
174                     return;
175                 }
176                 
177                 LOG.info("processing parsing " + f);
178                 handleAddNewLog(f, sessions, statistics, true);
179                 LOG.info("done processing parsing " + f);
180             }
181         }
182         LOG.info("request for parsing " + f);
183         R run = new R();
184         initTask = EXEC.submit(run);
185     }
186     
187     /**
188      * Getter for number of all submitted logs.
189      * @return number of log files in the logs directory.
190      */

191     public int getNumberOfLogs() {
192         return dir == null ? -1 : dir.list().length;
193     }
194
195     /**
196      * Takes a page context and fills it with informations about all statistics
197      * known to the system.
198      *
199      * @param context the context to fill
200      * @param id session ID identifying the user (and its userdir)
201      * @throws java.lang.InterruptedException
202      * @throws java.util.concurrent.ExecutionException
203      */

204     public void preparePageContext(PageContext JavaDoc context, String JavaDoc id) throws InterruptedException JavaDoc, ExecutionException JavaDoc {
205         context.setAttribute("manager", this);
206         if (dir == null) {
207             LOG.warning("Specify dir attribute, otherwise the server cannot work");
208             return;
209         }
210         initTask.get();
211         
212         for (Value<?> value : statistics) {
213             registerValue(context, value, id, "global");
214         }
215
216         if (id == null) {
217             return;
218         }
219         
220         UserInfo infos = sessions.get(id);
221         if (infos == null || infos.isEmpty()) {
222             return;
223         }
224         
225         for (Value<?> value : infos.get(infos.size() - 1).getValues()) {
226             registerValue(context, value, id, "last");
227         }
228         
229         
230         for (Value<?> value : infos.values) {
231             registerValue(context, value, id, "user");
232         }
233     }
234     
235     private <Data> void registerValue(PageContext JavaDoc context, Value<Data> data, String JavaDoc id, String JavaDoc prefix) {
236         data.statistics.registerPageContext(context, prefix + data.statistics.name, data.value);
237     }
238     
239     static <Data> void addStatisticsData(List JavaDoc<Value> toAdd, Statistics<Data> s) {
240         toAdd.add(new Value<Data>(s));
241     }
242     static <Data> void addStatisticsData(List JavaDoc<Value> toAdd, Value<Data> s) {
243         toAdd.add(new Value<Data>(s.statistics));
244     }
245     
246     static final class Value<Data> {
247         final Statistics<Data> statistics;
248         Data value;
249         
250         public Value(Statistics<Data> statistics) {
251             this.statistics = statistics;
252             this.value = statistics.newData();
253         }
254     }
255     
256     static final class UserInfo extends LinkedList JavaDoc<SessionInfo> {
257         private volatile List JavaDoc<Value> values;
258         
259         public UserInfo(List JavaDoc<Value> orig) {
260             values = new ArrayList JavaDoc<Value>();
261             for (Value<?> v : orig) {
262                 addStatisticsData(values, v);
263             }
264         }
265         
266         @Override JavaDoc
267         public boolean add(SessionInfo info) {
268             if (!super.add(info)) {
269                 return false;
270             }
271
272             info.addValues(values);
273             return true;
274         }
275
276         
277     }
278     
279     static final class SessionInfo {
280         private final String JavaDoc id;
281         private final int session;
282         private final File log;
283         private volatile List JavaDoc<Value> values;
284         private volatile boolean computed;
285         
286         SessionInfo(String JavaDoc id, int session, File log, Collection JavaDoc<Value> stats) {
287             this.log = log;
288             this.id = id;
289             this.session = session;
290             this.values = new ArrayList JavaDoc<Value>();
291             for (Value<?> v : stats) {
292                 addStatisticsData(this.values, v);
293             }
294         }
295         
296         public List JavaDoc<Value> getValues() {
297             if (computed) {
298                 return values;
299             }
300             
301             class H extends Handler JavaDoc {
302                 public void publish(LogRecord JavaDoc rec) {
303                     for (LogsManager.Value<?> value : values) {
304                         addRecord(value, rec);
305                     }
306                 }
307                 
308                 private <Data> void addRecord(Value<Data> value, LogRecord JavaDoc rec) {
309                     Data d = value.statistics.process(rec);
310                     value.value = value.statistics.join(value.value, d);
311                 }
312                 
313                 public void flush() {
314                 }
315                 
316                 public void close() throws SecurityException JavaDoc {
317                 }
318             }
319             H h = new H();
320             
321             InputStream is = null;
322             try {
323                 is = new BufferedInputStream(new FileInputStream(log));
324                 LogRecords.scan(is, h);
325             } catch (IOException ex) {
326                 LOG.log(Level.SEVERE, "Cannot read records: " + log, ex);
327             } finally {
328                 if (is != null) {
329                     try {
330                         is.close();
331                     } catch (IOException ex) {
332                         LOG.log(Level.INFO, "Cannot close stream: " + log, ex);
333                     }
334                 }
335             }
336             
337             computed = true;
338
339             return values;
340         }
341         
342         @SuppressWarnings JavaDoc("unchecked")
343         final void addValues(List JavaDoc<Value> sum) {
344             assert sum.size() == getValues().size();
345             
346             for (int i = 0; i < sum.size(); i++) {
347                 Value session = getValues().get(i);
348                 Value user = sum.get(i);
349                 assert session.statistics == user.statistics;
350                 
351                 user.value = user.statistics.join(user.value, session.value);
352             }
353             
354         }
355     }
356 }
357
Popular Tags