KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > cofax > cds > AdminServlet


1 /*
2  * AdminServlet is part of the Cofax content management system library.
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2.1 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with this library; if not, write to the Free Software
16  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17  *
18  * Please see http://www.cofax.org for contact information and other related informaion.
19  *
20  * $Header: /cvsroot/cofax/cofax/src/org/cofax/cds/AdminServlet.java,v 1.9.2.1 2006/12/11 16:19:29 fxrobin Exp $
21  */

22
23 package org.cofax.cds;
24
25 import java.util.*;
26 import java.io.*;
27
28 import javax.servlet.*;
29 import javax.servlet.http.*;
30
31 import org.cofax.*;
32
33 /**
34  *
35  * Provides web based administration of CofaxServlet.
36  *
37  * @author Rajiv Pant
38  * @author Karl Martino
39  * @author Sam Cohen
40  * @author Lee Bolding
41  * @author Cedric Aveline
42  *
43  */

44
45 public class AdminServlet extends HttpServlet {
46
47     /**
48      * UID for serialization needs
49      */

50     private static final long serialVersionUID = 3855922074031452000L;
51
52     static XMLConfig configFile;
53
54     static CofaxCache cacheOfPages;
55
56     static CofaxCache cacheOfTemplates;
57
58     static CofaxCache cacheOfPackageTags;
59
60     static String JavaDoc contextPath;
61
62     static String JavaDoc configLocation;
63
64     static DataStore dataStore;
65
66     static TemplateLoader templateLoader;
67
68     static String JavaDoc templatePath, defaultListFile, defaultArticleFile;
69
70     static String JavaDoc dataStoreClass;
71
72     static String JavaDoc templateLoaderClass;
73
74     static String JavaDoc templateProcessorClass;
75
76     static String JavaDoc version;
77
78     static String JavaDoc errorMsg;
79
80     static int maxPagesToTrack, maxPagesToStore, pagesRefreshInterval;
81
82     static int maxTemplatesToTrack, maxTemplatesToStore, templatesRefreshInterval;
83
84     static int maxPackageTagsToTrack, maxPackageTagsToStore, packageTagsRefreshInterval;
85
86     /**
87      * Initializes variables
88      */

89     public final void init(ServletConfig config) throws ServletException {
90
91         super.init(config);
92
93         // Get the servlet's context information.
94
ServletContext context = getServletContext();
95         contextPath = context.getRealPath("/");
96
97     }
98
99     /**
100      * Main routine of the servlet.
101      */

102     public final void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
103
104                 Object JavaDoc tmp = req.getHeader("host");
105         String JavaDoc hostName;
106         if (tmp != null) {
107             hostName = (String JavaDoc) tmp;
108         } else {
109             hostName = req.getServerName();
110         }
111
112         // String servletPath = req.getServletPath(); - FX : not used
113
String JavaDoc pathInfo = req.getPathInfo();
114         // String queryString = req.getQueryString(); - FX : not used
115
String JavaDoc requestedUrl = req.getScheme() + "://" + hostName + req.getRequestURI();
116         String JavaDoc requestedUrlWithoutQueryString = requestedUrl;
117
118         // Set up response
119
res.setContentType("text/html");
120         PrintWriter out = res.getWriter();
121
122         // Get the requested command
123
String JavaDoc command;
124         if (pathInfo == null) {
125             pathInfo = "";
126         }
127         if (pathInfo.equals("") || pathInfo.equals("/")) {
128             command = "mainMenu";
129
130         } else if (pathInfo.startsWith("/")) {
131             command = pathInfo.substring(1);
132
133         } else {
134             command = pathInfo;
135         }
136
137         // Get shared objects from main servlet
138
try {
139             cacheOfPages = (CofaxCache) getServletContext().getAttribute("cacheOfPages");
140             cacheOfTemplates = (CofaxCache) getServletContext().getAttribute("cacheOfTemplates");
141             cacheOfPackageTags = (CofaxCache) getServletContext().getAttribute("cacheOfPackageTags");
142             dataStore = (DataStore) getServletContext().getAttribute("dataStore");
143             version = (String JavaDoc) getServletContext().getAttribute("COFAX_VERSION");
144         } catch (ClassCastException JavaDoc e) {
145             out.println("<pre>");
146             e.printStackTrace(out);
147             out.println("</pre>");
148         }
149
150         maxPagesToTrack = cacheOfPages.getMaxTrack();
151         maxPagesToStore = cacheOfPages.getMaxStore();
152         pagesRefreshInterval = (int) cacheOfPages.getRefreshInterval();
153
154         maxTemplatesToTrack = cacheOfTemplates.getMaxTrack();
155         maxTemplatesToStore = cacheOfTemplates.getMaxStore();
156         templatesRefreshInterval = (int) cacheOfTemplates.getRefreshInterval();
157
158         maxPackageTagsToTrack = cacheOfPackageTags.getMaxTrack();
159         maxPackageTagsToStore = cacheOfPackageTags.getMaxTrack();
160         packageTagsRefreshInterval = cacheOfPackageTags.getMaxTrack();
161
162         // Get requested cache
163
String JavaDoc cacheName = req.getParameter("cache");
164         CofaxCache cache = null;
165
166         if (cacheName == null || cacheName.equals("pages")) {
167             cacheName = "pages";
168             cache = cacheOfPages;
169         } else if (cacheName.equals("templates"))
170             cache = cacheOfTemplates;
171         else if (cacheName.equals("packageTags"))
172             cache = cacheOfPackageTags;
173
174         if (cache == null) {
175             showHeader(out, command, req);
176             out.println("The Cofax content server her not been started yet." + CofaxUtil.XHTML_NEW_LINE);
177         } else {
178             if (!command.equals("remove") && !command.equals("expire")) {
179                 showHeader(out, command, req);
180                 mainMenu(out, requestedUrlWithoutQueryString);
181             }
182
183             if (command.equals("showCache")) {
184                 displayMemUsage(out);
185                 out.println(displayCachedObjects(cache, cacheName) + CofaxUtil.XHTML_NEW_LINE + CofaxUtil.XHTML_NEW_LINE);
186             } else if (command.equals("showConnectionPool")) {
187                 displayMemUsage(out);
188                 out.println(displayConnectionPool() + CofaxUtil.XHTML_NEW_LINE + CofaxUtil.XHTML_NEW_LINE);
189             } else if (command.equals("clearCache")) {
190                 cache.clear();
191                 out.println("Cache cleared." + CofaxUtil.XHTML_NEW_LINE);
192                 displayMemUsage(out);
193             } else if (command.equals("remove")) {
194                 String JavaDoc id = req.getParameter("id");
195                 String JavaDoc relative = req.getParameter("relative");
196                 remove(cache, id, relative, out);
197             } else if (command.equals("expire")) {
198                 String JavaDoc id = req.getParameter("id");
199                 String JavaDoc relative = req.getParameter("relative");
200                 expire(cache, id, relative, out);
201             } else if (command.equals("refresh")) {
202                 String JavaDoc id = req.getParameter("id");
203                 cache.removeFromCache(id);
204                 res.sendRedirect(req.getContextPath() + id);
205             } else {
206                 unknownCommand(out, command);
207                 displayMemUsage(out);
208             }
209         }
210
211         if (!command.equals("remove") && !command.equals("expire"))
212             showFooter(out);
213
214     }
215
216     /**
217      * Removes an item from a cache.
218      */

219     void remove(CofaxCache cache, String JavaDoc id, String JavaDoc relative, PrintWriter out) {
220
221         if (relative == null) {
222             cache.removeFromCache(id);
223             out.println("The URL: " + "<a HREF=\"" + id + "\">" + id + "</a>" + " will be removed from the cache right now." + CofaxUtil.XHTML_NEW_LINE);
224         } else {
225             out.println("The following URLs (if any) matching the relative URL path: " + id + " will be removed from the cache now.<br>"
226                     + CofaxUtil.XHTML_NEW_LINE);
227             List list = cache.removeByPartialUrl(id);
228             for (Iterator i = list.iterator(); i.hasNext();) {
229                 String JavaDoc aId = (String JavaDoc) i.next();
230                 out.println("<a HREF=\"" + aId + "\">" + aId + "</a><br>" + CofaxUtil.XHTML_NEW_LINE);
231             }
232         }
233
234     } // end remove()
235

236     /**
237      * Expires an item from a cache.
238      */

239     void expire(CofaxCache cache, String JavaDoc id, String JavaDoc relative, PrintWriter out) {
240
241         if (relative == null || relative.equals("")) {
242             cache.expireInCache(id);
243             out.println("The URL: " + "<a HREF=\"" + id + "\">" + id + "</a>" + " will expire from the cache in 60 seconds." + CofaxUtil.XHTML_NEW_LINE);
244         } else {
245             out.println("The following URLs (if any) matching the relative URL path: " + id + " will be expired from the cache in 60 seconds.<br>"
246                     + CofaxUtil.XHTML_NEW_LINE);
247             List list = cache.expireByPartialUrl(id);
248             for (Iterator i = list.iterator(); i.hasNext();) {
249                 String JavaDoc aId = (String JavaDoc) i.next();
250                 out.println("<a HREF=\"" + aId + "\">" + aId + "</a><br>" + CofaxUtil.XHTML_NEW_LINE);
251             }
252         }
253
254     } // end remove()
255

256     /**
257      * Displays statistics.
258      */

259     public void displayMemUsage(PrintWriter out) {
260
261         Runtime JavaDoc r = Runtime.getRuntime();
262
263         long totalMemory = r.totalMemory();
264         long freeMemory = r.freeMemory();
265         long usedMemory = totalMemory - freeMemory;
266         long percentMemoryUsed = 100 * usedMemory / totalMemory;
267         long pageRequests = cacheOfPages.getCacheRequests();
268         long pageHits = cacheOfPages.getCacheHits();
269         long dirtyHits = cacheOfPages.getDirtyCacheHits();
270         long hitRate = 0;
271         long misses = 0;
272         long tCHits = pageHits + dirtyHits;
273
274         if (pageRequests > 0 && pageHits > 0) {
275             hitRate = 100 * tCHits / pageRequests;
276             misses = pageRequests - pageHits;
277         } else
278             misses = pageRequests;
279
280         out.println("<h4>Memory Statistics</h4>\n" + "Total = " + totalMemory + " Used = " + usedMemory + " Free = " + freeMemory + CofaxUtil.XHTML_NEW_LINE
281                 + "Percent Memory Used = " + percentMemoryUsed + "%" + "<h4>Page Cache Statistics</h4>\n" + "Cached = " + cacheOfPages.getCachedCount()
282                 + " Tracked = " + cacheOfPages.getTrackedCount() + CofaxUtil.XHTML_NEW_LINE + "Requested = " + pageRequests + " Hit = " + pageHits
283                 + " Missed = " + misses + " Dirty Hit = " + dirtyHits + CofaxUtil.XHTML_NEW_LINE + "Cache Hit Rate = " + hitRate + "%"
284                 + CofaxUtil.XHTML_NEW_LINE + "Cleared Time = " + CofaxUtil.getDateFormat("yyyy.MM.dd 'at' hh:mm:ss z", cacheOfPages.getClearedTimeTotal())
285                 + CofaxUtil.XHTML_NEW_LINE);
286
287         if (cacheOfPages.getIsMaxStoreReached()) {
288             out.println("MaxStore Reached Time = " + CofaxUtil.getDateFormat("yyyy.MM.dd 'at' hh:mm:ss z", cacheOfPages.getMaxStoreReached())
289                     + CofaxUtil.XHTML_NEW_LINE + "Now swapping least hit from store " + "with others from tracked." + CofaxUtil.XHTML_NEW_LINE);
290         }
291         if (cacheOfPages.getMaxTrackTurnOver() > 0) {
292             out.println("MaxTrack Last Turned Over = " + CofaxUtil.getDateFormat("yyyy.MM.dd 'at' hh:mm:ss z", cacheOfPages.getMaxTrackReached())
293                     + CofaxUtil.XHTML_NEW_LINE);
294         }
295
296         out.println("<h4>Other Cache Statistics</h4>" + "Templates cached = " + cacheOfTemplates.getCachedCount() + CofaxUtil.XHTML_NEW_LINE
297                 + "packageTags cached = " + cacheOfPackageTags.getCachedCount() + CofaxUtil.XHTML_NEW_LINE);
298         out.println("</td></tr></table>");
299     }
300
301     /**
302      * Shows the main menu.
303      */

304     void mainMenu(PrintWriter out, String JavaDoc requestedUrlWithoutQueryString) {
305         String JavaDoc addSeparator = "";
306         if ((requestedUrlWithoutQueryString.endsWith("admin")))
307             addSeparator = contextPath+"/admin/";
308         out.println("Separator : "+addSeparator+"<br />");
309         out.println("<table cellspacing \"8\" cellpadding=\"4\">");
310         out.println("<tr><td valign=\"top\" nowrap>" + "<font size=5>Commands:</font><br>" + "<a HREF=\"" + addSeparator
311                 + "showCache\">Show Pages Cache With Tracked</a>" + CofaxUtil.XHTML_NEW_LINE + "<a HREF=\"" + addSeparator
312                 + "showCache?cache=templates\">Show Templates Cache With Tracked</a>" + CofaxUtil.XHTML_NEW_LINE + "<a HREF=\"" + addSeparator
313                 + "showCache?cache=packageTags\">Show Package Tags Cache With Tracked</a>" + CofaxUtil.XHTML_NEW_LINE + "<a HREF=\"" + addSeparator
314                 + "showConnectionPool\">Show Connection Pool Info</a>" + CofaxUtil.XHTML_NEW_LINE + CofaxUtil.XHTML_NEW_LINE + "<a HREF=\"" + addSeparator
315                 + "clearCache\">" + "Clear Pages Cache</a>" + CofaxUtil.XHTML_NEW_LINE + "<a HREF=\"" + addSeparator + "clearCache?cache=templates\">"
316                 + "Clear Templates Cache</a>" + CofaxUtil.XHTML_NEW_LINE + "<a HREF=\"" + addSeparator + "clearCache?cache=packageTags\">"
317                 + "Clear Package Tags Cache</a>" + CofaxUtil.XHTML_NEW_LINE + CofaxUtil.XHTML_NEW_LINE + "<h4>Configuration Settings</h4>\n"
318                 + "maximum pages to track = " + maxPagesToTrack + CofaxUtil.XHTML_NEW_LINE + "maximum pages to store = " + maxPagesToStore
319                 + CofaxUtil.XHTML_NEW_LINE + "page refresh interval = " + pagesRefreshInterval + CofaxUtil.XHTML_NEW_LINE + "maximum templates to track = "
320                 + maxTemplatesToTrack + CofaxUtil.XHTML_NEW_LINE + "maximum templates to store = " + maxTemplatesToStore + CofaxUtil.XHTML_NEW_LINE
321                 + "templates refresh interval = " + templatesRefreshInterval + CofaxUtil.XHTML_NEW_LINE + "maximum packageTags to track = "
322                 + maxPackageTagsToTrack + CofaxUtil.XHTML_NEW_LINE + "maximum packageTags to store = " + maxPackageTagsToStore + CofaxUtil.XHTML_NEW_LINE
323                 + "templates packageTags interval = " + packageTagsRefreshInterval + CofaxUtil.XHTML_NEW_LINE + "</td>");
324         out.println("<td valign=\"top\">");
325
326     }
327
328     /**
329      * Prints the header of the user interface.
330      */

331     void showHeader(PrintWriter out, String JavaDoc command, HttpServletRequest req) {
332
333         out.println("<html>" + CofaxUtil.NEW_LINE + "<head>" + CofaxUtil.NEW_LINE + "<title>Cofax Admin Servlet</title>" + CofaxUtil.NEW_LINE
334                 + "<meta name='robots' content='noindex,nofollow'>" + CofaxUtil.NEW_LINE
335                 + "<link HREF='"+contextPath+"/static/admin/style.css' rel='stylesheet' type='text/css' />" + "</head>" + CofaxUtil.NEW_LINE + "<body>"
336                 + CofaxUtil.NEW_LINE + "<font size=5>Cofax Admin</font><br>" + CofaxUtil.NEW_LINE + "<font size=3>Cofax Version: " + version + "</font><br>"
337                 + CofaxUtil.NEW_LINE + "<font size=2><dd> Welcome: " + req.getRemoteHost() + "(" + req.getRemoteAddr() + ")</font><br>" + CofaxUtil.NEW_LINE
338                 + "<font size=2><dd> This Server Name: " + req.getServerName() + "</font><br>" + CofaxUtil.NEW_LINE + "<font size=2><dd> Your Request URI: "
339                 + req.getRequestURI() + "</font><br>" + CofaxUtil.NEW_LINE + "<font size=3>Executing: " + command + "</font><br>" + CofaxUtil.NEW_LINE);
340
341     }
342
343     /**
344      * Prints the footer of the user interface.
345      */

346     void showFooter(PrintWriter out) {
347
348         out.println("<hr>" + CofaxUtil.NEW_LINE + "This application should be used by authorized staff people only." + CofaxUtil.NEW_LINE + "</body>"
349                 + CofaxUtil.NEW_LINE + "</html>" + CofaxUtil.NEW_LINE);
350
351     }
352
353     /**
354      * Prints an error message when passed an invalid command.
355      */

356     void unknownCommand(PrintWriter out, String JavaDoc command) {
357
358         out.println("Unknown command: " + command + CofaxUtil.XHTML_NEW_LINE);
359         if (command.endsWith("/"))
360             out.println("Try removing the last \"/\" from the command." + "That was required in an earlier version of this "
361                     + "program, but isn't used anymore.");
362
363     }
364
365     /**
366      * Calls destroy.
367      */

368     public void destroy() {
369
370         super.destroy();
371
372     }
373
374     /**
375      * Displays a table of items that have been cached.
376      */

377     public String JavaDoc displayCachedObjects(CofaxCache cache, String JavaDoc name) {
378
379         StringBuffer JavaDoc display = new StringBuffer JavaDoc(CofaxUtil.COMMON_DATA_SIZE);
380
381         display.append("<table border=\"1\">" + CofaxUtil.NEW_LINE + "<th colspan=\"4\">Dumping Cached Objects in " + name + "</th>"
382                 + "<tr><td colspan=\"2\">Max objects to Cache: " + CofaxUtil.NEW_LINE + cache.getMaxStore() + "</td>" + CofaxUtil.NEW_LINE
383                 + "<td>Time to Refresh: " + (cache.getRefreshInterval() / CofaxUtil.MILLISECONDS_PER_MINUTE) + "</td></tr>" + CofaxUtil.NEW_LINE
384                 + "<tr><td align=\"center\">ID</td>" + CofaxUtil.NEW_LINE + "<td align=\"center\">Hit Count</td>" + CofaxUtil.NEW_LINE
385                 + "<td align=\"center\">Time Since Cached(Mins)</td>" + "<td align=center>Size</td></tr>" + CofaxUtil.NEW_LINE);
386
387         HashMap pages = cache.getCacheHash();
388         Iterator objects = pages.keySet().iterator();
389         Date currDate = new Date();
390         long currSecs = currDate.getTime();
391         long cacheAge;
392         long cachedTime;
393
394         String JavaDoc id;
395         String JavaDoc urlEncoded;
396         Integer JavaDoc x;
397
398         // display all the cached pages
399
while (objects.hasNext()) {
400             id = (String JavaDoc) objects.next();
401             urlEncoded = CofaxUtil.encodeUrl(id);
402             if (pages.get(id) instanceof CofaxPage) { // if we are dealing
403
// with a cached page
404
CofaxPage page = (CofaxPage) pages.get(id);
405                 x = new Integer JavaDoc(page.getHitCount());
406                 // x = (Integer) urlCounts.get(id) ;
407
cachedTime = page.getLastModified();
408                 cacheAge = currSecs - cachedTime;
409                 display.append("<tr><td>" + "[<a HREF=\"remove?cache=" + name + "&id=" + urlEncoded + "\""
410                         + " target=\"_new\"><font size=\"-1\">Remove</font>]</a>" + "[<a HREF=\"refresh?id=" + urlEncoded + "\""
411                         + " target=\"_new\"><font size=\"-1\">Refresh</font></a>]" + "[<a HREF=\"removeAll?cache=" + name + "&id=" + urlEncoded + "\""
412                         + " target=\"_new\"><font size=\"-1\">RemoveAll</font></a>]" + " <a HREF=\"" + id + "\" target=\"_new\">" + id + "</a>" + "</td><td>"
413                         + x.toString() + "</td><td>");
414
415                 if (cacheAge > cache.getRefreshInterval()) {
416                     display.append("<font color=\"red\">" + (cacheAge / CofaxUtil.MILLISECONDS_PER_MINUTE) + "</font>");
417                 } else {
418                     display.append("<font color=\"green\">" + (cacheAge / CofaxUtil.MILLISECONDS_PER_MINUTE) + "</font>");
419                 }
420                 display.append("</td><td>" + page.getContentsLength() / 1024 + " KB</td></tr>"); // FX :
421
// adding
422
// page
423
// size
424
// in
425
// memory
426
display.append(CofaxUtil.NEW_LINE);
427             }
428         }
429         display.append("</table>");
430
431         // display all the tracked pages
432
display.append("<table border=\"1\">" + CofaxUtil.NEW_LINE + "<th colspan=\"3\">Dumping Tracked Objects in " + name + "</th>"
433                 + "<tr><td colspan=\"3\">Max objects to Track: " + CofaxUtil.NEW_LINE + cache.getMaxTrack() + "</td>" + CofaxUtil.NEW_LINE + "</tr>"
434                 + CofaxUtil.NEW_LINE + "<tr><td align=\"center\">ID</td>" + CofaxUtil.NEW_LINE + "<td align=\"center\">Hit Count</td>" + CofaxUtil.NEW_LINE
435                 + "<td align=center>Status</td></tr>" + CofaxUtil.NEW_LINE);
436         objects = pages.keySet().iterator();
437         while (objects.hasNext()) {
438             id = (String JavaDoc) objects.next();
439             urlEncoded = CofaxUtil.encodeUrl(id);
440             if (pages.get(id) instanceof Integer JavaDoc) {
441                 x = (Integer JavaDoc) pages.get(id);
442                 display.append("<tr><td>" + urlEncoded + "</td><td>" + x.toString() + "</td><td>Tracked</td></tr>");
443                 display.append(CofaxUtil.NEW_LINE);
444             }
445         }
446         display.append("</table>");
447         display.append(CofaxUtil.NEW_LINE);
448         return display.toString();
449
450     }
451
452     /**
453      * Function: displayConnectionPool Purpose: To call the current connection
454      * pool to display its connection info Args: Returns: The string which the
455      * connection pool generates containing it detailed info Author: Sam Cohen
456      * Created: 7/23/2001 Revision History:
457      */

458     public String JavaDoc displayConnectionPool() {
459
460         StringBuffer JavaDoc display = new StringBuffer JavaDoc(CofaxUtil.COMMON_DATA_SIZE);
461
462         display.append(dataStore.getPoolConnectionStats("cofax"));
463         display.append(CofaxUtil.NEW_LINE);
464         return display.toString();
465
466     }
467
468 } // end class AdminServlet
469
Popular Tags