KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > mmbase > module > INFO


1 /*
2
3 This software is OSI Certified Open Source Software.
4 OSI Certified is a certification mark of the Open Source Initiative.
5
6 The license (Mozilla version 1.0) can be read at the MMBase site.
7 See http://www.MMBase.org/license
8
9 */

10 package org.mmbase.module;
11
12 import java.util.*;
13 import java.io.File JavaDoc;
14 import java.text.DateFormat JavaDoc;
15 import java.text.SimpleDateFormat JavaDoc;
16
17 import org.mmbase.util.*;
18 import org.mmbase.module.core.*;
19
20 import org.mmbase.util.logging.Logging;
21 import org.mmbase.util.logging.Logger;
22
23 /**
24  * The INFO module provides access to the environment on which the mmbase system resides.
25  * It can retrieve information on the file system, system memory, time, current user or browser,
26  * and miscellaneous information that is not directly related to the object cloud.
27  * Most functions in this module are specific for SCAN - other scripting languages generally have
28  * their own ways of obtaining this data.
29  *
30  * @application SCAN
31  * @rename Info
32  * @author Daniel Ockeloen
33  * @author Eduard Witteveen
34  * @author Pierre van Rooden
35  * @version $Id: INFO.java,v 1.51 2005/08/31 11:46:55 nklasens Exp $
36 .*/

37 public class INFO extends ProcessorModule {
38
39     /**
40      * @rename NOT
41      */

42     public final static int Not=0;
43     public final static int Dutch=1;
44     public final static int English=2;
45
46     private static Logger log = Logging.getLoggerInstance(INFO.class.getName());
47
48     /**
49      * @scope private
50      */

51     Random rnd;
52     /**
53      * @scope private
54      */

55     String JavaDoc documentroot;
56     /**
57      * @scope private
58      */

59     Hashtable DirCache=new Hashtable();
60
61     /**
62      * Constructor for
63      */

64     public INFO() {
65     }
66
67     /**
68      * Initializes the module.
69      * Determines the document root by reading system properties.
70      */

71     public void init() {
72         documentroot=MMBaseContext.getHtmlRoot();
73         // org.mmbase super.init();
74
rnd=new RandomPlus();
75     }
76
77
78     /**
79      * Generate a list of values from a command to the processor.
80      * The commands processed are : <br />
81      * COLOR-BASIC : returns a list of (system) color names and their RGB values<br />
82      * RANGE-X-Y-Z : returns a list of values in the numeric range X to Y, using Z as the increment factor (step) i.e
83      * RANGE-0-12-3 returns the values 0, 3 ,6 ,9, 12<br />
84      * The default values of X, Y and Z are 1, 10 and 1.<br />
85      * RANGE-ALPHA : returns the values 'A' thru 'Z'<br />
86      * SCANDATE :returns a list of dates (date, month, day, day-of-week) of all directories in a given path with a file length of 10 characters.
87      * No, I don't get it either.<br />
88      *
89      * @param sp the current page context
90      * @param tagger the parameters (name-value pairs) belonging to the command to process
91      * @param value the command to process
92      * @return a <code>Vector</code> containing the requested values.
93      * @throws ParseException
94      */

95      public Vector getList(scanpage sp,StringTagger tagger, String JavaDoc value) throws ParseException {
96         String JavaDoc line = Strip.DoubleQuote(value,Strip.BOTH);
97         StringTokenizer tok = new StringTokenizer(line,"-\n\r");
98         if (tok.hasMoreTokens()) {
99             String JavaDoc cmd=tok.nextToken();
100             if (cmd.equals("COLOR")) { tagger.setValue("ITEMS","2"); return doColor(tok); }
101             if (cmd.equals("RANGE")) { tagger.setValue("ITEMS","1"); return doRange(tok); }
102             if (cmd.equals("SCANDATE")) { tagger.setValue("ITEMS","4"); return doScanDate(sp,tagger); }
103         }
104         return null;
105     }
106
107     /**
108      * Execute the commands provided in the form values.
109      * Does not do anything except output debug code.
110      * @param sp the current page context
111      * @param cmds the command to process
112      * @param vars the variables to process
113      * @return alwyas <code>false</code>
114      */

115     public boolean process(scanpage sp, Hashtable cmds,Hashtable vars) {
116         if (log.isDebugEnabled()) {
117             log.debug("CMDS="+cmds);
118             log.debug("VARS="+vars);
119         }
120         return false;
121     }
122
123     /**
124      * Handle a $MOD command.
125      * This generally replaces the command in the SCAN page with the value returned by the command.
126      * Commands include:<br />
127      * BROWSER : returns browser or host name<br />
128      * DECODE : decodes a URL-encodes stringvalue<br />
129      * ENCODE : URL-encodes a strignvalue <br />
130      * ESCAPE : escapes the single quotes in a stringvalue <br />
131      * EXISTS : test if a file exists
132      * MEMORY : returns free meory <br />
133      * MOVE : Move a file on the system
134      * OS : retrieve the name of the user's Operating System
135      * RANDOM : returns a random number
136      * RELTIME : convert (relative) time values
137      * TIME : return a specific time value
138      * TIMEFORMAT/TIMEFORMATSEC : format a timevalue
139      * PARSETIME : parse time to seconds
140      * STRING :
141      * USER :
142      * @param sp the current page context
143      * @param cmds the command to process
144      * @return a <code>String</code> with the command's result value
145        */

146     public String JavaDoc replace(scanpage sp, String JavaDoc cmds) {
147         StringTokenizer tok = new StringTokenizer(cmds,"-\n\r");
148         if (tok.hasMoreTokens()) {
149             String JavaDoc cmd=tok.nextToken();
150             if (cmd.equals("CLASS")) return "CLASS="+this;
151             if (cmd.equals("BROWSER")) return doBrowser(sp,tok);
152             if (cmd.equals("DECODE")) return doParamDecode(sp,tok);
153             if (cmd.equals("ENCODE")) return doParamEncode(sp,tok);
154             if (cmd.equals("ESCAPE")) return doEscape(sp,tok);
155             if (cmd.equals("EXISTS")) return doExists(sp,tok);
156             if (cmd.equals("MEMORY")) return doMemory(tok);
157             if (cmd.equals("MOVE")) return doMove(sp,tok);
158             if (cmd.equals("OS")) return doOs(sp,tok);
159             if (cmd.equals("RANDOM")) return doRandom(sp,tok);
160             if (cmd.equals("RELTIME")) return doRelTime(tok);
161             if (cmd.equals("STRING")) return doString(tok);
162             if (cmd.equals("STRINGCMP")) return toYesNo(doString(tok).equals(""+true));
163                     if (cmd.equals("TIME")) return doTime(tok);
164             if (cmd.equals("TIMEFORMAT")) return doTimeFormat(tok, false);
165             if (cmd.equals("TIMEFORMATSEC")) return doTimeFormat(tok, true);
166             if (cmd.equals("PARSETIME")) return doParseTime(tok);
167
168             if (cmd.equals("USER")) return doUser(sp,tok);
169             if (cmd.equals("SERVERCONTEXT")) return sp.req.getContextPath();
170         }
171         return "No command defined";
172     }
173
174
175     /**
176      * takes a time in several formats and creates a time from it
177      * @param tok the processing command's arguments
178      */

179     String JavaDoc doParseTime(StringTokenizer tok) {
180         String JavaDoc rawstr=tok.nextToken();
181         String JavaDoc formatstr="";
182         if (tok.hasMoreTokens()) {
183             formatstr=tok.nextToken();
184             formatstr.replace('_',' ');
185         } else {
186             int len=rawstr.length();
187             if (len==8) formatstr="ddMMyyyy";
188             if (len==6) formatstr="HHmmss";
189             if (len==14) formatstr="HHmmssddMMyyyy";
190         }
191
192         SimpleDateFormat JavaDoc df = (SimpleDateFormat JavaDoc)DateFormat.getDateTimeInstance();
193         TimeZone tz;
194         //df.applyLocalizedPattern("yyyyMMdd");
195
df.applyLocalizedPattern(formatstr);
196
197         tz=TimeZone.getDefault() ;
198         df.setTimeZone(tz);
199
200         Date date = null;
201         try {
202             date = df.parse(rawstr);
203         } catch( java.text.ParseException JavaDoc e ) {
204             log.error(e.toString());
205         }
206
207         if( date != null) {
208             return ""+(int)((date.getTime()-DateSupport.getMilliOffset())/1000);
209         } else {
210             return "";
211         }
212     }
213
214     /**
215      * Formats either the current or a given timevalue according to a specified format.
216      * Cmd arguments are an optional timevalue and a format (default HH:MM:ss).
217      * @param tok the processing command's arguments
218      * @param inSec if <code>true</code>, the timevalue is in seconds instead of milliseconds
219      * @return a <code>String</code> containing the time in the specified format
220      */

221     String JavaDoc doTimeFormat(StringTokenizer tok, boolean inSec) {
222         String JavaDoc format = "HH:mm:ss";
223         long timeInMs = System.currentTimeMillis();
224         while (tok.hasMoreTokens())
225         { String JavaDoc tmp = tok.nextToken();
226             if ((tmp.charAt(0) >= '0') && (tmp.charAt(0) <= '9'))
227             { if (inSec)
228                     timeInMs = (Long.decode(tmp + "000")).longValue();
229                 else
230                     timeInMs = (Long.decode(tmp)).longValue();
231                 if (tok.hasMoreTokens()) format = tok.nextToken();
232             }
233             else
234             { // Time parameter is skipped, use current time.
235
format = tmp;
236             }
237             // If there are more tokens add them to the format because in that case the format contains '-'.
238
while (tok.hasMoreTokens()) format += "-" + tok.nextToken();
239             format=format.replace('_', ' ');
240         }
241         SimpleDateFormat JavaDoc simpleDateFormat = new SimpleDateFormat JavaDoc(format);
242         String JavaDoc result = simpleDateFormat.format(new Date(timeInMs));
243         return result;
244     }
245
246
247     /**
248      * Performs tests on strings. Cmd arguments are:
249      * EQUALS-val-compareVal : checks whether two strings are the same
250      * STARTSWITH-val-compareVal(-toffset) or LEFTSTRING : checks whether one strings starts with another
251      * ENDSWITH-val-compareVal or RIGHTSTRING : checks whether one strings ends with another
252      * INDEXOF-val-compareVal or CONTAINS : checks whether one string contains another
253      * @param tok StringTokenizer with the rest of the cmd.
254      * @return A string conmtaining the value <code>true</code> if the test succeeds
255      */

256     String JavaDoc doString(StringTokenizer tok) {
257         if (tok.hasMoreTokens()) {
258             String JavaDoc cmd=tok.nextToken();
259             if (tok.hasMoreTokens()) {
260                 String JavaDoc val = tok.nextToken();
261                 if ((tok.hasMoreTokens())||(!val.equals(""))) {
262                     String JavaDoc compareVal = tok.nextToken();
263                     if (cmd.equals("STARTSWITH")||cmd.equals("LEFTSTRING")) {
264                         if (tok.hasMoreTokens()) {
265                             int toffset = 0;
266                             try { toffset = Integer.parseInt(tok.nextToken());
267                             } catch (NumberFormatException JavaDoc nfe) {
268                                 log.error(""+nfe);
269                                 return "Error in "+cmd+" offset arg";
270                             }
271                             return ""+val.startsWith(compareVal,toffset);
272                         }
273                         return ""+val.startsWith(compareVal);
274                     } else if (cmd.equals("ENDSWITH")||cmd.equals("RIGHTSTRING")) {
275                         return ""+val.endsWith(compareVal);
276                     } else if (cmd.equals("EQUALS")) {
277                         return ""+val.equals(compareVal);
278                     } else if (cmd.equals("INDEXOF")||cmd.equals("CONTAINS")) {
279                         return ""+(val.indexOf(compareVal)!=-1);
280                     } else { return ("Unknown String cmd "+cmd);
281                     }
282                 } else { return ("Syntax error, $MOD-INFO-"+cmd+"-"+val);
283                 }
284             } else { return "Syntax error, $MOD-INFO-"+cmd+"-";
285             }
286         } else { return "Syntax error, $MOD-INFO-";
287         }
288     }
289
290     /**
291      * Converts a string into a string with 'escaped' quotes.<br />
292      * The argument for this command is the string to 'escape'.
293      * @param sp the current page context
294      * @param tok the StringTokenizer containing the subsequent cmd argument tokens.
295      * @return a <code>String</code> which is the converted value
296      */

297     String JavaDoc doEscape(scanpage sp, StringTokenizer tok) {
298         String JavaDoc result=null;
299         while (tok.hasMoreTokens()) {
300             String JavaDoc tmp=tok.nextToken();
301             if (result==null) {
302                 result=tmp;
303             } else {
304                 result+="-"+tmp;
305             }
306         }
307         return Encode.encode("ESCAPE_SINGLE_QUOTE", result);
308     }
309
310
311     /**
312      * Converts an ASCII string into a URL-encoded string.<br />
313      * The argument for this command is the string to encode.
314      * @param sp the current page context
315      * @param tok the StringTokenizer containing the subsequent cmd argument tokens.
316      * @return a <code>String</code> which is the converted value
317      */

318     String JavaDoc doParamEncode(scanpage sp, StringTokenizer tok) {
319         String JavaDoc result=null;
320         while (tok.hasMoreTokens()) {
321             String JavaDoc tmp=tok.nextToken();
322             if (result==null) {
323                 result=tmp;
324             } else {
325                 result+="-"+tmp;
326             }
327         }
328         return URLParamEscape.escapeurl(result);
329     }
330
331
332     /**
333      * Converts an URL-encoded string into a ASCII string.<br />
334      * The argument for this command is the string to decode.
335      * @param sp the current page context
336      * @param tok the StringTokenizer containing the subsequent cmd argument tokens.
337      * @return a <code>String</code> which is the converted value
338      */

339     String JavaDoc doParamDecode(scanpage sp, StringTokenizer tok) {
340         String JavaDoc result=null;
341         while (tok.hasMoreTokens()) {
342             String JavaDoc tmp=tok.nextToken();
343             if (result==null) {
344                 result=tmp;
345             } else {
346                 result+="-"+tmp;
347             }
348         }
349         return URLParamEscape.unescapeurl(result);
350     }
351
352
353     /**
354      * Retrieve the name of the user's operating system.
355      * This command takes no arguments
356      * @param sp the current page context
357      * @param tok the StringTokenizer containing the subsequent cmd argument tokens.
358      * @return a <code>String</code> which is the converted value
359      */

360     String JavaDoc doOs(scanpage sp, StringTokenizer tok) {
361         if (tok.hasMoreTokens()) {
362             String JavaDoc cmd=tok.nextToken();
363             return "Illegal OS command";
364         } else {
365             String JavaDoc tmp=sp.req.getHeader("User-Agent");
366             tmp = tmp.toLowerCase();
367             if (tmp.indexOf("windows 95")!=-1 || tmp.indexOf("win95")!=-1) {
368                 return "WIN95";
369             } else if (tmp.indexOf("win98")!=-1) {
370                 return "Windows 98";
371             } else if (tmp.indexOf("windows nt 5.0")!=-1) {
372                 return "Windows 2000";
373             } else if (tmp.indexOf("winnt")!=-1 || tmp.indexOf("windows nt")!=-1) {
374                 return "Windows NT";
375             } else if (tmp.indexOf("win")!=-1) {
376                 return "Windows";
377             } else if (tmp.indexOf("mac")!=-1) {
378                 return "MAC";
379             } else if (tmp.indexOf("sun")!=-1) {
380                 return "Unix";
381             } else if (tmp.indexOf("irix")!=-1) {
382                 return "Irix";
383             } else if (tmp.indexOf("freebsd")!=-1) {
384                 return "FreeBSD";
385             } else if (tmp.indexOf("hp-ux")!=-1) {
386                 return "HP Unix";
387             } else if (tmp.indexOf("aix")!=-1) {
388                 return "AIX";
389             } else if (tmp.indexOf("linux")!=-1) {
390                 return "Linux";
391             }
392             return "Unknown OS";
393         }
394     }
395
396
397     /**
398      * Returns a random number in a specified range.
399      * The command arguments are the start and end of the numerical range in which the random number should fall.
400      * @param sp the current page context
401      * param tok the StringTokenizer containing the subsequent cmd argument tokens.
402      * @return a <code>String</code> containing a random number
403      */

404     String JavaDoc doRandom(scanpage sp, StringTokenizer tok) {
405     int j=0;
406     int s=0;
407     int e=0;
408     if (tok.hasMoreTokens()) {
409         String JavaDoc start=tok.nextToken();
410         if (tok.hasMoreTokens()) {
411             String JavaDoc end=tok.nextToken();
412             try {
413                 s=Integer.parseInt(start);
414                 e=Integer.parseInt(end);
415                 j=Math.abs(rnd.nextInt()%(e-s));
416             } catch (Exception JavaDoc f) {}
417         }
418     }
419     return ""+(s+j);
420     }
421
422
423     /**
424      * Returns data about the user's browser.<br />
425      * Valid options are: <br />
426      * OS : returns the operating system.
427      * HTTP : returns the requested HTTP-header.
428      * WANTEDHOST : returns the host name.
429      * NAME : returns the name of the current browser
430      * NETSCAPE : returns YES is the current browser is netscape navigator, NO otherwise
431      * MSIE : returns YES is the current browser is internet explorer, NO otherwise
432      * @param sp the current page context
433      * @param tok The StringTokenizer containing the subsequent cmd argument tokens.
434      * @return a <code>String</code> containing the result
435      */

436     String JavaDoc doBrowser(scanpage sp, StringTokenizer tok) {
437         if (tok.hasMoreTokens()) {
438             String JavaDoc cmd=tok.nextToken();
439             if (cmd.equals("OS")) {
440                 return doOs(sp,tok);
441             }
442             if (cmd.equals("HTTP")) {
443                 if (tok.hasMoreTokens()) {
444                     cmd=tok.nextToken();
445                     while (tok.hasMoreTokens()) {
446                         cmd+="-"+tok.nextToken();
447                     }
448                     return sp.req.getHeader(cmd);
449                 } else {
450                     return "Illegal browser command";
451                 }
452             }
453             if (cmd.equals("WANTEDHOST")) {
454                 return sp.req.getHeader("Host");
455             }
456             if (cmd.equals("NAME")) {
457                 return sp.req.getHeader("User-Agent");
458             }
459             String JavaDoc br=sp.req.getHeader("User-Agent");
460             if (cmd.equals("NETSCAPE")) {
461                 return toYesNo(br.indexOf("Mozilla")==0 && br.indexOf("MSIE")==-1);
462             }
463             if (cmd.equals("MSIE")) {
464                 return toYesNo(br.indexOf("MSIE")!=-1);
465             }
466             return "Illegal browser command";
467         } else {
468             return sp.req.getHeader("User-Agent");
469         }
470     }
471
472     /** Returns information on the user
473      * Valid options are:<br />
474      * NAME, which returns the username in SCAN<br />
475      * HOSTNAME, which returns the name of the remote host (visiting) in SCAN<br />
476      * IPNUMBER, which returns the ipnumber of the remote host(visiting) in SCAN <br />
477      * SECLEVEL, which returns current security level in SCAN <br />
478      * REQUEST_URI, which returns the path of the file requested in SCAN<br />
479      * BACK, which returns the name of the page visted befote the current page, notice not supported by all browsers<br />
480      * COUNTRY, which returns the country name of the remote host ( mmbase.nl -> nl; mmbase.org-> org )<br />
481      * DOMAIN, which returns the domain name of the remote host<br />
482      * INDOMAIN, which returns YES when remote host has the same domain as us otherwise it returns NO in SCAN <br />
483      * @param tok StringTokenizer with the rest of the cmd.
484      * @param sp the scanpage
485      * @return a String containing cmd result.
486      * @author Eduard Witteveen 08-11-2000
487      */

488      // http://uk.php.net/manual/language.variables.predefined.php <-- a few defines from php
489
String JavaDoc doUser(scanpage sp, StringTokenizer tok) {
490         if (tok.hasMoreTokens()) {
491             String JavaDoc cmd=tok.nextToken();
492             if (cmd.equals("NAME")) return HttpAuth.getRemoteUser(sp.req);
493             if (cmd.equals("SESSIONNAME")) return sp.getSessionName();
494             if (cmd.equals("HOSTNAME")) return sp.req.getRemoteHost();
495             if (cmd.equals("REQUEST_URI")) return sp.req.getRequestURI();
496             if (cmd.equals("SECLEVEL")) return sp.req.getAuthType();
497             if (cmd.equals("IPNUMBER")) return sp.req.getRemoteAddr();
498             if (cmd.equals("BACK")) {
499                 String JavaDoc tmp=sp.req.getHeader("Referer");
500                 if (tmp!=null) {
501                     return tmp;
502                 } else {
503                     return "";
504                 }
505             }
506             if (cmd.equals("COUNTRY")) {
507                 String JavaDoc tmp=sp.req.getRemoteHost();
508                 if (tmp!=null) {
509                     String JavaDoc domain = tmp.substring(tmp.lastIndexOf('.')+1);
510                     if (domain!=null) {
511                         return domain;
512                     } else {
513                         return "";
514                     }
515                 }
516             }
517             if (cmd.equals("DOMAIN")) {
518                 String JavaDoc tmp=sp.req.getRemoteHost();
519                 if (tmp!=null && tmp.indexOf('.')!=-1) {
520                     String JavaDoc domain = tmp.substring(tmp.lastIndexOf('.'));
521                     tmp = tmp.substring(0,tmp.lastIndexOf('.'));
522                     tmp = tmp.substring(tmp.lastIndexOf('.')+1);
523                     domain = tmp+domain;
524                     if (domain!=null) {
525                         return domain;
526                     }
527                 }
528                 return "";
529             }
530             if (cmd.equals("INDOMAIN")) {
531                 String JavaDoc tmp=sp.req.getRemoteHost();
532                 if (tmp!=null && tmp.indexOf('.')!=-1) {
533                     String JavaDoc domain = tmp.substring(tmp.lastIndexOf('.'));
534                     tmp = tmp.substring(0,tmp.lastIndexOf('.'));
535                     tmp = tmp.substring(tmp.lastIndexOf('.')+1);
536                     domain = tmp+domain;
537                     if (domain!=null) {
538                         String JavaDoc serverdomain=getProperty("server","Domain");
539                         return toYesNo(serverdomain.equals(domain));
540                     }
541                     return toYesNo(false);
542                 } else {
543                     String JavaDoc servername=getProperty("server","MachineName");
544                     return toYesNo(servername.equals(tmp));
545                 }
546             }
547             return "Illegal user command";
548         } else {
549             return HttpAuth.getRemoteUser(sp.req);
550         }
551     }
552
553     /**
554      * Returns a continues range of values with two set numerical boundaries and a step-increase, or
555      * the range of characters of the alphabet. <br />
556      * i.e. RANGE-60-100-10 returns 60,70,80,90,100 <br />
557      * RANGE-ALPHA returns A,B,C,....Y.Z
558      * @param tok The StringTokenizer containing the subsequent cmd argument tokens.
559      * @return a <code>String</code> containing the result
560      */

561     Vector doRange(StringTokenizer tok) {
562         Vector results = new Vector();
563         String JavaDoc firstToken="";
564         int start=1;
565         int end=10;
566         int step=1;
567         try {
568             // check for numerical boundaries (defaults are 1 and 10)
569
if (tok.hasMoreTokens()) {
570                 firstToken=tok.nextToken();
571                 start=Integer.parseInt(firstToken);
572                 if (tok.hasMoreTokens()) {
573                     end=Integer.parseInt(tok.nextToken());
574                     if (tok.hasMoreTokens()) {
575                         step=Integer.parseInt(tok.nextToken());
576                     }
577                     for (int i=start;i<=end;i+=step) {
578                         results.addElement(""+i);
579                     }
580                 }
581             }
582         } catch (Exception JavaDoc e) {
583             if (firstToken.equals("ALPHA")) { // return the alphabet
584
for (int i='A';i<='Z';i++) {
585                     results.addElement(""+(char)i);
586                 }
587             }
588         }
589         return results;
590     }
591
592     /**
593      * Returns a list of color names and their RGB values. <br />
594      * COLOR-BASIC returns a list of basic colors. <br />
595      * COLOR-PRIMARY returns a list of primary colors. <br />
596      * No other options are yet implemented
597      * @param tok The commands to be executed
598      * @return a <code>Vector</code> containing color names and RGB values
599      */

600     Vector doColor(StringTokenizer tok) {
601         if (tok.hasMoreTokens()) {
602             String JavaDoc cmd=tok.nextToken();
603             if (cmd.equals("BASIC")) {
604                 return doColorBasic();
605             } else if (cmd.equals("SPECTRUM")) {
606                 return doColorSpectrum();
607             } else if (cmd.equals("WINDOWS") || cmd.equals("16")) {
608                 return doColor16();
609             } else {
610                 return null;
611             }
612         }
613         return doColorSpectrum();
614     }
615
616     /**
617      * Returns a list of basic color names and their RGB values. <br />
618      * These include the basic RGB colors, as well as mint-blue and mint-green.
619      * @return a <code>Vector</code> containing color names and RGB values
620      */

621     Vector doColorBasic() {
622         Vector results = new Vector();
623         results.addElement("black");results.addElement("000000");
624         results.addElement("white");results.addElement("FFFFFF");
625         results.addElement("red");results.addElement("FF0000");
626         results.addElement("green");results.addElement("00FF00");
627         results.addElement("blue");results.addElement("0000FF");
628         results.addElement("mint-blue");results.addElement("31FFCE");
629         results.addElement("mint-green");results.addElement("20FFFFF");
630         return results;
631     }
632
633     /**
634      * Returns a list of primary and secondary color names and their RGB values. <br />
635      * @return a <code>Vector</code> containing color names and RGB values
636      */

637     Vector doColorSpectrum() {
638         Vector results = new Vector();
639         results.addElement("white");results.addElement("FFFFFF");
640         results.addElement("purple");results.addElement("800080");
641         results.addElement("red");results.addElement("FF0000");
642         results.addElement("orange");results.addElement("FFA500");
643         results.addElement("yellow");results.addElement("FFFF00");
644         results.addElement("green");results.addElement("008000");
645         results.addElement("blue");results.addElement("0000FF");
646         results.addElement("black");results.addElement("000000");
647         return results;
648     }
649
650     /**
651      * Returns a list of the 16 windows color names and their RGB values. <br />
652      * @return a <code>Vector</code> containing color names and RGB values
653      */

654     Vector doColor16() {
655         Vector results = new Vector();
656         results.addElement("white");results.addElement("FFFFFF");
657         results.addElement("black");results.addElement("000000");
658         results.addElement("red");results.addElement("FF0000");
659         results.addElement("lime");results.addElement("00FF00");
660         results.addElement("blue");results.addElement("0000FF");
661         results.addElement("magenta");results.addElement("FF00FF");
662         results.addElement("yellow");results.addElement("FFFF00");
663         results.addElement("cyan");results.addElement("00FFFF");
664         results.addElement("silver");results.addElement("C0C0C0");
665         results.addElement("gray");results.addElement("808080");
666         results.addElement("maroon");results.addElement("800000");
667         results.addElement("green");results.addElement("008000");
668         results.addElement("navy");results.addElement("000080");
669         results.addElement("purple");results.addElement("800080");
670         results.addElement("olive");results.addElement("808000");
671         results.addElement("teal");results.addElement("008080");
672         return results;
673     }
674
675     /**
676      * Formats either the current or a given timevalue according to a specified format.
677      * Cmd arguments are an optional timevalue, a format, and the timepart to return.
678      * @deprecation uses Date instead of Calendar
679      * @param tok the processing command's arguments
680      * @param inSec if <code>true</code>, the timevalue is in seconds instead of milliseconds
681      * @return a <code>String</code> containing the time in the specified format
682      */

683     String JavaDoc doTime(StringTokenizer tok) {
684         if (tok.hasMoreTokens()) {
685             String JavaDoc cmd=tok.nextToken(),rtn="";
686
687             Date d=new Date(System.currentTimeMillis());
688             TimeZone tz = TimeZone.getTimeZone("ECT"); //Rob
689
GregorianCalendar calendar = new GregorianCalendar(tz); //Rob
690
// extra hack to check if the first param is a number
691
// so we can have given times instead of epoch
692
try {
693                 int i=Integer.parseInt(cmd);
694                 d=new Date(((long)i)*1000);
695                 calendar.setTime(d);
696                 cmd=tok.nextToken();
697             } catch(Exception JavaDoc e) {
698                 // no problem it was probably not a number
699
}
700             int ctime=(int)(calendar.getTime().getTime()/1000);
701
702             int whichname=INFO.Not;
703
704             if (cmd.equals("NAME") || cmd.equals("ENGLISH")) {
705                 whichname=INFO.English;
706                 if (tok.hasMoreTokens()) cmd=tok.nextToken();
707             } else if (cmd.equals("DUTCHNAME") || cmd.equals("DUTCH")) {
708                 whichname=INFO.Dutch;
709                 if (tok.hasMoreTokens()) cmd=tok.nextToken();
710             } else if (cmd.equals("NUMBER")) {
711                 whichname=INFO.Not;
712                 if (tok.hasMoreTokens()) cmd=tok.nextToken();
713             } else {
714                 whichname=INFO.Not;
715             }
716             if (cmd.equals("TIME")) {
717                 int getminutes = calendar.get(Calendar.MINUTE);
718                 if (getminutes<10) {
719                     return ""+calendar.get(Calendar.HOUR_OF_DAY)+":0"+getminutes;
720                 } else {
721                     return ""+calendar.get(Calendar.HOUR_OF_DAY)+":"+getminutes;
722                 }
723             }
724
725             int days = calendar.get(Calendar.DAY_OF_YEAR);
726
727             if (cmd.equals("CURTIME")) {
728                 if (tok.hasMoreTokens()) {
729                     return nextCurTime(tok);
730                 } else {
731                     return ""+System.currentTimeMillis()/1000;
732                 }
733             }
734             if (cmd.equals("DCURTIME")) return ""+System.currentTimeMillis()/1000;
735             if (cmd.equals("CURTIME10")) return ""+System.currentTimeMillis()/(10*1000);
736             if (cmd.equals("CURTIME20")) return ""+System.currentTimeMillis()/(20*1000);
737
738             // YEAR
739
if (cmd.equals("YEAR")) return ""+calendar.get(Calendar.YEAR);
740             if (cmd.equals("SHORTYEAR")) {
741                 int getyear = calendar.get(Calendar.YEAR)%100;
742                 if(getyear<10) {
743                     return "0"+getyear;
744                 } else {
745                     return ""+getyear;
746                 }
747             }
748
749             //MONTH
750
if (cmd.equals("MONTH") || cmd.equals("SHORTMONTH")) {
751                 int getmonth = calendar.get(Calendar.MONTH);
752                 switch(whichname) {
753                     case INFO.Not:
754                         rtn=""+(++getmonth);
755                         break;
756                     case INFO.English:
757                         if (cmd.equals("MONTH")) {
758                             rtn=DateStrings.ENGLISH_DATESTRINGS.getMonth(getmonth);
759                         } else {
760                             rtn=DateStrings.ENGLISH_DATESTRINGS.getShortMonth(getmonth);
761                         }
762                         break;
763                     case INFO.Dutch:
764                         if (cmd.equals("MONTH")) {
765                             rtn=DateStrings.DUTCH_DATESTRINGS.getMonth(getmonth);
766                         } else {
767                             rtn=DateStrings.DUTCH_DATESTRINGS.getShortMonth(getmonth);
768                         }
769                         break;
770                 }
771                 return rtn;
772             }
773
774             //MONTHS
775
if (cmd.equals("MONTHS") || cmd.equals("SHORTMONTHS")) {
776                 rtn="";
777                 int year,month,months;
778                 Calendar cal=null;
779                 String JavaDoc tk;
780                 int w=0;
781
782                 if (whichname!=INFO.Not) {
783                     int imonth;
784                     if (tok.hasMoreTokens()) {
785                         tk=tok.nextToken();
786                         if (tk.equals("YEAR")) {
787                             tk=tok.nextToken();
788                             w=1;
789                         } else if (tk.equals("MONTH")) {
790                             tk=tok.nextToken();
791                             w=2;
792                         }
793                         try {
794                             imonth=Integer.parseInt(tk);
795                         } catch (NumberFormatException JavaDoc nfe) {
796                             imonth=0;
797                         }
798                     } else {
799                         imonth=0;
800                     }
801                     cal=getCalendarMonths(imonth);
802                 }
803                 switch(whichname) {
804                     case INFO.Not:
805                         year=calendar.get(Calendar.YEAR)-1970;
806                         month=calendar.get(Calendar.MONTH);
807                         months=month+year*12;
808                         rtn=""+months;
809                         break;
810                     case INFO.English:
811                         switch(w) {
812                             case 1:
813                                 month=cal.get(Calendar.YEAR);
814                                 rtn=""+month;
815                                 break;
816                             case 2:
817                                 month=cal.get(Calendar.MONTH);
818                                 if (cmd.equals("MONTHS")) {
819                                     rtn=DateStrings.ENGLISH_DATESTRINGS.getMonth(month);
820                                 } else {
821                                     rtn=DateStrings.ENGLISH_DATESTRINGS.getShortMonth(month);
822                                 }
823                                 break;
824                             default:
825                                 month=cal.get(Calendar.MONTH);
826                                 if (cmd.equals("MONTHS")) {
827                                     rtn=DateStrings.ENGLISH_DATESTRINGS.getMonth(month);
828                                 } else {
829                                     year=cal.get(Calendar.YEAR);
830                                     rtn=DateStrings.ENGLISH_DATESTRINGS.getShortMonth(month)+" "+year;
831                                 }
832                                 break;
833                         }
834                         break;
835                     case INFO.Dutch:
836                         switch(w) {
837                             case 1:
838                                 month=cal.get(Calendar.YEAR);
839                                 rtn=""+month;
840                                 break;
841                             case 2:
842                                 month=cal.get(Calendar.MONTH);
843                                 if (cmd.equals("MONTHS")) {
844                                     rtn=DateStrings.DUTCH_DATESTRINGS.getMonth(month);
845                                 } else {
846                                     rtn=DateStrings.DUTCH_DATESTRINGS.getShortMonth(month);
847                                 }
848                                 break;
849                             default:
850                                 month=cal.get(Calendar.MONTH);
851                                 if (cmd.equals("MONTHS")) {
852                                     rtn=DateStrings.DUTCH_DATESTRINGS.getMonth(month);
853                                 } else {
854                                     year=cal.get(Calendar.YEAR);
855                                     rtn=DateStrings.DUTCH_DATESTRINGS.getShortMonth(month)+" "+year;
856                                 }
857                                 break;
858                         }
859                         break;
860                 }
861
862                 return rtn;
863             }
864
865             //WEEK
866
if (cmd.equals("WEEK")) return ""+((days/7)+1);
867             if (cmd.equals("WEEKOFYEAR")) return ""+calendar.get(Calendar.WEEK_OF_YEAR);
868             if (cmd.equals("WEEKOFMONTH")) return ""+calendar.get(Calendar.WEEK_OF_MONTH);
869
870             // DAY
871
if (cmd.equals("DAY") || cmd.equals("DAYOFMONTH")) return ""+calendar.get(Calendar.DAY_OF_MONTH);
872             if (cmd.equals("WEEKDAY") || cmd.equals("DAYOFWEEK") || cmd.equals("SHORTDAYOFWEEK")) {
873                 int getday = calendar.get(Calendar.DAY_OF_WEEK);
874                 switch(whichname) {
875                     case INFO.Not:
876                         rtn=""+getday;
877                         break;
878                     case INFO.English:
879                         if(cmd.equals("SHORTDAYOFWEEK")) {
880                             rtn=DateStrings.ENGLISH_DATESTRINGS.getShortDay(--getday);
881                         } else {
882                             rtn=DateStrings.ENGLISH_DATESTRINGS.getDay(--getday);
883                         }
884                         break;
885                     case INFO.Dutch:
886                         if (cmd.equals("SHORTDAYOFWEEK")) {
887                             rtn=DateStrings.DUTCH_DATESTRINGS.getShortDay(--getday);
888                         } else {
889                             rtn=DateStrings.DUTCH_DATESTRINGS.getDay(--getday);
890                         }
891                         break;
892                 }
893                 return rtn;
894             }
895             if (cmd.equals("DAYOFWEEKINMONTH")) return ""+calendar.get(Calendar.DAY_OF_WEEK_IN_MONTH);
896             if (cmd.equals("YDAY") || cmd.equals("DAYOFYEAR")) return ""+calendar.get(Calendar.DAY_OF_YEAR);
897
898             //HOUR
899
if (cmd.equals("HOUR")) return ""+calendar.get(Calendar.HOUR);
900             if (cmd.equals("HOUROFDAY")) return ""+calendar.get(Calendar.HOUR_OF_DAY);
901
902             //MINUTES
903
if (cmd.equals("MIN") || cmd.equals("MINUTE")) return ""+calendar.get(Calendar.MINUTE);
904
905             //SECONDS
906
if (cmd.equals("SEC") || cmd.equals("SECOND")) return ""+calendar.get(Calendar.SECOND);
907
908
909             if (cmd.equals("PREVWEEK")) {
910                 long tmp=days/7;
911                 if (tmp<1) tmp=52;
912                 if (tmp>52) tmp=1;
913                 return ""+tmp;
914             }
915             if (cmd.equals("GWEEK")) return ""+(((days+3)/7)); // +3 days
916
if (cmd.equals("PREVGWEEK")) {
917                 long tmp=((days+3)/7)-1; // +3 days
918
if (tmp<1) tmp=52;
919                 if (tmp>52) tmp=1;
920                 return ""+tmp;
921             }
922             if (cmd.equals("NEXTWEEK")) {
923                 long tmp=(days/7)+2;
924                 if (tmp==53) tmp=1;
925                 if (tmp==54) tmp=2;
926                 return ""+tmp;
927             }
928             if (cmd.equals("NEXTGWEEK")) {
929                 long tmp=((days+3)/7)+1; // +3days
930
if (tmp==53) tmp=1;
931                 if (tmp==54) tmp=2;
932                 return ""+tmp;
933             }
934             if (cmd.equals("WEEKDATE")) {
935                 String JavaDoc sday;
936                 int iday,iweek;
937                 Date ad;
938
939                 iweek=(days/7)+1;
940                 if (tok.hasMoreTokens()) {
941                     sday=tok.nextToken();
942                 } else {
943                     sday="1";
944                 }
945                 try {
946                     iday=Integer.parseInt(sday);
947                 } catch (NumberFormatException JavaDoc e) {
948                     iday=1;
949                 }
950                 iday-=2;
951                 if (iday<0) {
952                     iweek--;
953                     iday=6;
954                 }
955                 d=DateSupport.Date(d.getYear(),iweek,iday);
956                 rtn=d.getDate()+" "+DateStrings.DUTCH_DATESTRINGS.getMonth(d.getMonth());
957                 return rtn;
958             }
959             if (cmd.equals("NEXTWEEKDATE")) {
960                 String JavaDoc sday;
961                 int iday,iweek;
962
963                 iweek=(days/7)+2;
964                 if (tok.hasMoreTokens()) {
965                     sday=tok.nextToken();
966                 } else {
967                     sday="1";
968                 }
969                 try {
970                     iday=Integer.parseInt(sday);
971                 } catch (NumberFormatException JavaDoc e) {
972                     iday=1;
973                 }
974                 iday-=2;
975                 if (iday<0) {
976                     iweek--;
977                     iday=6;
978                 }
979                 d=DateSupport.Date(d.getYear(),iweek,iday);
980                 rtn=d.getDate()+" "+DateStrings.DUTCH_DATESTRINGS.getMonth(d.getMonth());
981                 return rtn;
982             }
983             if (cmd.equals("GWEEKDATE")) {
984                 String JavaDoc sday;
985                 int iday,iweek;
986                 Date ad;
987
988                 iweek=((days+3)/7)+1;
989                 if (tok.hasMoreTokens()) {
990                     sday=tok.nextToken();
991                 } else {
992                     sday="1";
993                 }
994                 try {
995                     iday=Integer.parseInt(sday);
996                 } catch (NumberFormatException JavaDoc e) {
997                     iday=1;
998                 }
999                 iday-=2;
1000                if (iday<0) {
1001                    iweek--;
1002                    iday=6;
1003                }
1004                d=DateSupport.Date(d.getYear(),iweek,iday);
1005                rtn=d.getDate()+" "+DateStrings.DUTCH_DATESTRINGS.getMonth(d.getMonth());
1006                return rtn;
1007            }
1008            if (cmd.equals("NEXTGWEEKDATE")) {
1009                String JavaDoc sday;
1010                int iday,iweek;
1011                Date ad;
1012
1013                iweek=((days+3)/7)+2;
1014                if (tok.hasMoreTokens()) {
1015                    sday=tok.nextToken();
1016                } else {
1017                    sday="1";
1018                }
1019                try {
1020                    iday=Integer.parseInt(sday);
1021                } catch (NumberFormatException JavaDoc e) {
1022                    iday=1;
1023                }
1024                iday-=2;
1025                if (iday<0) {
1026                    iweek--;
1027                    iday=6;
1028                }
1029                d=DateSupport.Date(d.getYear(),iweek,iday);
1030                rtn=d.getDate()+" "+DateStrings.DUTCH_DATESTRINGS.getMonth(d.getMonth());
1031                return rtn;
1032            } else if (cmd.equals("WEEKCURTIME")) {
1033                Date d2=new Date((long)ctime*1000);
1034                int day=d2.getDay();
1035                int hours=d2.getHours();
1036                int min=d2.getMinutes();
1037                int sec=d2.getSeconds();
1038                ctime-=((day+1)*86400);
1039                ctime-=(hours*3600);
1040                ctime-=(min*60);
1041                ctime-=(sec);
1042                return ""+ctime;
1043            } else if (cmd.equals("DAYCURTIME")) {
1044                Date d2=calendar.getTime();
1045                int hours=d2.getHours();
1046                int min=d2.getMinutes();
1047                int sec=d2.getSeconds();
1048                ctime-=(hours*3600);
1049                ctime-=(min*60);
1050                ctime-=(sec);
1051                return ""+ctime;
1052            }
1053
1054
1055            return "Illegal date command";
1056        } else {
1057            return new Date(System.currentTimeMillis()).toString();
1058        }
1059    }
1060
1061    /**
1062     * Returns a description of the module.
1063     * @return a <code>String</code> describing the module's function.
1064     */

1065    public String JavaDoc getModuleInfo() {
1066        return "Support routines for servscan, Daniel Ockeloen";
1067    }
1068
1069    /**
1070     * This method is used to retrieve time related info from a relative time value.
1071     * Valid commands are :
1072     * GET/GETTIME-timeValueInMillis : time passed since the indicated time
1073     * GETHOURS-timeValueInMillis : hours passed since the indicated time
1074     * GETMINUTES-timeValueInMillis : minutes passed since the indicated time
1075     * GETSECONDS-timeValueInMillis : seconds passed since the indicated time
1076     * GETMILLIS-timeValueInMillis : milliseconds passed since the indicated time
1077     * COUNTMILLIS-hourValue-minuteValue-secondValue-milliValue : milisecodms past siunce the indicated time
1078     * @param tok The StringTokenizer containing the subsequent cmd argument tokens.
1079     * @return A String containing cmd result.
1080     */

1081    String JavaDoc doRelTime(StringTokenizer tok) {
1082        int timeValue = 0;
1083        if (tok.hasMoreTokens()) {
1084            String JavaDoc cmd=tok.nextToken();
1085
1086            // Check commandname.
1087
if (cmd.equals("COUNTMILLIS")) {
1088                if (tok.hasMoreTokens() && (tok.countTokens()==4)) {
1089                    String JavaDoc value = tok.nextToken()+":"+tok.nextToken()+":"+tok.nextToken()+"."+tok.nextToken();
1090                    timeValue = RelativeTime.convertTimeToInt(value);
1091                    if (log.isDebugEnabled()) {
1092                        log.debug("doRelTime -> COUNTMILLIS result= " +timeValue);
1093                    }
1094                    return (""+timeValue);
1095                } else {
1096                    String JavaDoc error = "doRelTime: Error, Amount of timeValues is != 4 (h,m,s,ms)";
1097                    log.error(error);
1098                    return error;
1099                }
1100            } else if (cmd.startsWith("GET")) {
1101
1102                if (tok.hasMoreTokens()) {
1103                    try {
1104                        timeValue = Integer.parseInt(tok.nextToken());
1105                    } catch (NumberFormatException JavaDoc nfe) {
1106                        log.warn("doRelTime: Invalid timeValue specified. "+nfe);
1107                        return "INFO::doRelTime: Invalid timeValue specified timeValue="+timeValue;
1108                    }
1109                } else {
1110                    return "INFO::doRelTime: No timeValue specified";
1111                }
1112                if (log.isDebugEnabled()) {
1113                    log.debug("doRelTime: "+cmd+"-"+timeValue+" result= "+RelativeTime.getHours(timeValue));
1114                }
1115                if (cmd.equals("GETHOURS")) {
1116                    return (""+RelativeTime.getHours(timeValue));
1117                } else if (cmd.equals("GETMINUTES")) {
1118                    return (""+RelativeTime.getMinutes(timeValue));
1119                } else if (cmd.equals("GETSECONDS")) {
1120                return (""+RelativeTime.getSeconds(timeValue));
1121                } else if (cmd.equals("GETMILLIS")) {
1122                    return (""+RelativeTime.getMillis(timeValue));
1123                } else {
1124                    return (""+RelativeTime.convertIntToTime(timeValue));
1125                }
1126            } else {
1127                return "INFO::doRelTime: Undefined command specified, command= "+cmd;
1128            }
1129        } else {
1130            return "INFO::doRelTime: No command specified";
1131        }
1132    }
1133
1134    /**
1135     * This method is used to retrieve the amount of FREE MEMORY in either the JVM or the SYSTEM.<br />
1136     * Valid options are: <br />
1137     * GETJVM (default) : returns free memory of the Java Virtual Machine
1138     * GETSYS : return the free memory on the system
1139     * B(default) :return memory in bytes
1140     * KB: :return memory in kilo bytes
1141     * MB: :return memory in mega bytes
1142     * @param tok The StringTokenizer containing the subsequent cmd argument tokens.
1143     * @return A String containing the available memory.
1144     */

1145    String JavaDoc doMemory(StringTokenizer tok) {
1146        int whichMem = 0;
1147        float memDiv = 0.0f;
1148        if (tok.hasMoreTokens()) {
1149            String JavaDoc cmd=tok.nextToken();
1150            // Check commandname.
1151
if (cmd.equals("GETJVM")) {
1152                whichMem = 0;
1153            } else if (cmd.equals("GETSYS")) {
1154                whichMem = 1;
1155            } else {
1156                log.error("doMemory: Undefined command requested -> "+cmd);
1157                return "INFO::doMemory: Undefined command requested -> "+cmd;
1158            }
1159            if (tok.hasMoreTokens()) {
1160                cmd = tok.nextToken();
1161                if (cmd.equals("MB")) memDiv = 1048576.0f;
1162                else if (cmd.equals("KB")) memDiv = 1024.0f;
1163            }
1164        }
1165        Runtime JavaDoc rt = Runtime.getRuntime();
1166
1167        if (memDiv < 1.0f) {
1168            if (whichMem == 0)
1169                return (""+rt.totalMemory());
1170            else
1171                return (""+rt.freeMemory());
1172        } else {
1173            if (whichMem == 0)
1174                return (""+(rt.totalMemory()/memDiv));
1175            else
1176                return (""+(rt.freeMemory()/memDiv));
1177        }
1178    }
1179
1180    /**
1181     * Returns a list of dates (date, month,day, day-of-week) of all directories in a given path with a file length of 10 characters.
1182     * Requires tags are base (path) and start (date)
1183     * Optional tags are end (date), STARTINCLUDED, ENDINCLUDED and REVERS (booleans)
1184     * @param sp the current page context
1185     * @param tok the commands to be executed
1186     * @return a <code>Vector</code> containing color names and RGB values
1187     * @deprecated hereditary code. Should be dropped or adapted.
1188     */

1189    Vector doScanDate(scanpage sp,StringTagger tagger) {
1190        String JavaDoc temp = sp.req.getHeader("Pragma");
1191        if (temp!=null && temp.indexOf("no-cache")!=-1) {
1192            DirCache=new Hashtable();
1193        }
1194
1195        Vector results=new Vector();
1196
1197        // get base
1198
String JavaDoc base=tagger.Value("BASE");
1199        if (base==null) return results;
1200           base = Strip.DoubleQuote(base,Strip.BOTH);
1201
1202        // find the start
1203
Date start=null;
1204        String JavaDoc val=tagger.Value("START");
1205        if (val!=null) {
1206            val = Strip.DoubleQuote(val,Strip.BOTH);
1207            start=DateSupport.parsedbmdate(val);
1208        }
1209
1210        // find the end
1211
Date end=null;
1212        val=tagger.Value("END");
1213        if (val!=null) {
1214            val = Strip.DoubleQuote(val,Strip.BOTH);
1215            end=DateSupport.parsedbmdate(val);
1216        }
1217
1218        // start included
1219
boolean startincluded=true;
1220        val=tagger.Value("STARTINCLUDED");
1221        if (val!=null) {
1222            val = Strip.DoubleQuote(val,Strip.BOTH);
1223            startincluded=isNotNo(val);
1224        }
1225
1226        // end included
1227
boolean endincluded=true;
1228        val=tagger.Value("ENDINCLUDED");
1229        if (val!=null) {
1230            val = Strip.DoubleQuote(val,Strip.BOTH);
1231            endincluded=isNotNo(val);
1232        }
1233
1234        // revers list
1235
boolean revert=false;
1236        val=tagger.Value("REVERS");
1237        if (val!=null) {
1238            val = Strip.DoubleQuote(val,Strip.BOTH);
1239            revert = isYes(val);
1240        }
1241
1242        // scan the disk
1243
File JavaDoc scanfile = new File JavaDoc(documentroot+base);
1244        //debug(documentroot+base);
1245
SortedVector fullres=(SortedVector)DirCache.get(documentroot+base);
1246        if (fullres==null) {
1247            fullres=getDirTimes(scanfile);
1248            DirCache.put(documentroot+base,fullres);
1249            //debug(DirCache.toString());
1250
}
1251
1252        if (start!=null) {
1253            long val2=start.getTime();
1254            if (!startincluded) val2++; // shift start to exclude start
1255
long val3;
1256            if (revert) fullres=revertVector(fullres);
1257            if (end!=null) {
1258                long val4=end.getTime();
1259                if (!endincluded) val4--; // shift end to exclude start
1260
Date rd;
1261                for (Enumeration e=fullres.elements();e.hasMoreElements();) {
1262                    val3=Long.parseLong((String JavaDoc)e.nextElement());
1263                    if (val3>=val2 && val3<=val4) {
1264                        rd=new Date(val3);
1265                        results.addElement(DateSupport.makedbmdate(rd));
1266                        results.addElement(DateStrings.DUTCH_DATESTRINGS.getMonth(rd.getMonth()));
1267                        results.addElement(""+rd.getDate());
1268                        results.addElement(DateStrings.DUTCH_DATESTRINGS.getMonth(rd.getDay()));
1269                    }
1270                }
1271            } else {
1272                Date rd;
1273                for (Enumeration e=fullres.elements();e.hasMoreElements();) {
1274                    val3=Long.parseLong((String JavaDoc)e.nextElement());
1275                    if (val3>=val2) {
1276                        rd=new Date(val3);
1277                        results.addElement(DateSupport.makedbmdate(rd));
1278                        results.addElement(DateStrings.DUTCH_DATESTRINGS.getMonth(rd.getMonth()));
1279                        results.addElement(""+rd.getDate());
1280                        results.addElement(DateStrings.DUTCH_DATESTRINGS.getMonth(rd.getDay()));
1281                    }
1282                }
1283            }
1284        }
1285        tagger.setValue("ITEMS","4");
1286        return results;
1287    }
1288
1289    /**
1290     * Reverse the order of a list of values
1291     * @param src the source of values to reverse
1292     * @return a <code>Vector</code> containing the reverse ordered list
1293     */

1294    SortedVector revertVector(SortedVector src) {
1295        SortedVector dst=new SortedVector();
1296        for (int i=0;i<src.size();i++) {
1297            dst.insertElementAt(src.elementAt(i),0);
1298        }
1299        return dst;
1300    }
1301
1302    /**
1303     * Retrieves the creation times of all directories under a specific path
1304     * whose names are 10 characters long.
1305     * @param scanfile the path to search
1306     * @return a <code>Vector</code> containing the times
1307     */

1308    SortedVector getDirTimes(File JavaDoc scanfile) {
1309        SortedVector results;
1310        // scan the disk
1311
results=new SortedVector();
1312        File JavaDoc theFile;
1313        Date d;
1314        String JavaDoc theFileName;
1315        String JavaDoc files[] = scanfile.list();
1316        if (files!=null) {
1317            for (int i=0;i<files.length;i++) {
1318                theFileName=files[i];
1319                theFile = new File JavaDoc(scanfile,theFileName);
1320                if (theFile.isDirectory() && theFileName.length()==10) {
1321                    d=DateSupport.parsedbmdate(theFileName);
1322                    results.addSorted(""+d.getTime());
1323                }
1324            }
1325        }
1326        return results;
1327    }
1328
1329    /**
1330     * Tests whether a given filename exists either as a directory, as a file, or as a path (depending on the subcommand given).
1331     * Subcommands are DIR, FILE, and PATH. This subcommand need be followed by a filename.
1332     * @param sp the current page context
1333     * @param tok the commands to be executed
1334     * @return a <code>String</code> withe the value 'YES' if the check succeeded, 'NO' if it failed.
1335     */

1336    public String JavaDoc doExists(scanpage sp,StringTokenizer tok) {
1337        String JavaDoc type=tok.nextToken();
1338        String JavaDoc path=tok.nextToken();
1339        boolean rtn=false;
1340
1341        /* fully quallify path */
1342        if (path.charAt(0)=='/') {
1343            String JavaDoc droot = documentroot;
1344
1345            if(documentroot.endsWith("/"))
1346            {
1347                droot = documentroot.substring(0, documentroot.length()-1);
1348            }
1349            path=droot+path;
1350            // debug("INFO -> doExists full path : "+path);
1351
} else {
1352            String JavaDoc r=sp.req_line;
1353            int i=r.lastIndexOf('/');
1354            path=documentroot+r.substring(0,i+1)+path;
1355            // debug("INFO -> doExists req path : "+path);
1356
}
1357        /* check */
1358        if (type.equals("PATH")) {
1359            rtn=pathExists(path);
1360        } else if (type.equals("FILE")) {
1361            rtn=fileExists(path);
1362        } else if (type.equals("DIR")) {
1363            rtn=dirExists(path);
1364        }
1365        return toYesNo(rtn);
1366    }
1367
1368    // Determines whether a path exists on the server's file system.
1369
private boolean pathExists(String JavaDoc path) {
1370        File JavaDoc f=new File JavaDoc(path);
1371        return f.exists();
1372    }
1373
1374    // Determines whether a path exists as a directory on the server's file system.
1375
private boolean dirExists(String JavaDoc path) {
1376        File JavaDoc f=new File JavaDoc(path);
1377        return (f.exists() && f.isDirectory());
1378    }
1379
1380    // Determines whether a path exists as a file the server's file system.
1381
private boolean fileExists(String JavaDoc path) {
1382        File JavaDoc f=new File JavaDoc(path);
1383        return (f.exists() && f.isFile());
1384    }
1385
1386    // returns a Calendar object set to the first day of the indicated month (counted from 1-1-1970)
1387
private Calendar getCalendarMonths(int months) {
1388        int year,month;
1389        year=months/12;
1390        month=months%12;
1391        GregorianCalendar cal=new GregorianCalendar();
1392        cal.set(year+1970,month,1,0,0,0);
1393        return cal;
1394    }
1395
1396    /**
1397     * Move a file on the system. The command line should include a filepath of the original file, and one for its destination.
1398     * @param sp the current page context
1399     * @param tok the commands to be executed
1400     * @return Always <code>null</code>. This comamnd is executed for its side effects, it does not return a value.
1401     */

1402    private String JavaDoc doMove( scanpage sp, StringTokenizer tok ) {
1403        String JavaDoc result = null;
1404
1405        if( tok.hasMoreTokens() ) {
1406
1407            String JavaDoc from = tok.nextToken();
1408            if( tok.hasMoreTokens() ) {
1409                String JavaDoc toDir = tok.nextToken();
1410                    moveFile( from, toDir );
1411            } else
1412                log.error("doMove(): ERROR: page("+sp.getUrl()+"): no destination specified in $MOD-INFO-MOVE-"+from+" !");
1413        } else
1414            log.error("doMove(): ERROR: page("+sp.getUrl()+"): no source directory given in $MOD-INFO-MOVE-.. !");
1415        return result;
1416    }
1417
1418
1419    // check if this will work with moveFile("/a/b/file.txt", "../c")
1420
//
1421
// moves file from '/../directory/filename' to '/../otherdirectory/'
1422
private boolean moveFile( String JavaDoc pathslashfile , String JavaDoc otherdirectory ) {
1423        boolean result = false;
1424        if( fileExists(pathslashfile) ) {
1425            File JavaDoc f1 = new File JavaDoc( pathslashfile );
1426
1427            String JavaDoc name = f1.getName();
1428            String JavaDoc path = f1.getAbsolutePath(); // filename included
1429
path = path.substring( 0, path.lastIndexOf("/") ); // remove filename
1430
String JavaDoc parent = path.substring( 0, path.lastIndexOf("/") ); // remove last directory
1431

1432            String JavaDoc oparent = parent + f1.separator + otherdirectory;
1433            File JavaDoc f2 = new File JavaDoc( oparent );
1434
1435            if( f2.isDirectory() ) {
1436                if( f2.canWrite() ) {
1437                    f2 = new File JavaDoc( oparent , name );
1438                    if( f1.renameTo( f2 ) ) {
1439                        result = true;
1440                    } else
1441                        log.error("moveFile("+pathslashfile+","+otherdirectory+"): ERROR: move file("+pathslashfile+") -> file("+oparent+","+name+") did not succeed!");
1442                } else
1443                    log.error("moveFile("+pathslashfile+","+otherdirectory+"): ERROR: directory("+oparent+") has no write-permission set!");
1444            } else
1445                log.error("moveFile("+pathslashfile+","+otherdirectory+"): ERROR: directory("+oparent+") is not a valid directory!");
1446        } else
1447            log.error("moveFile("+pathslashfile+","+otherdirectory+"): ERROR: first parameter is not a valid file!");
1448
1449        return result;
1450    }
1451
1452    // determines string value for boolean results
1453
private String JavaDoc toYesNo(boolean value) {
1454        return ( value ? "YES" : "NO" );
1455    }
1456
1457    // returns true is a string value is equal to YES or TRUE
1458
private boolean isYes(String JavaDoc value) {
1459        return (value.equals("YES") || value.equals("TRUE"));
1460    }
1461
1462    // returns true if a string value is not equal to NO or FALSE
1463
private boolean isNotNo(String JavaDoc value) {
1464        return !(value.equals("NO") || value.equals("FALSE"));
1465    }
1466
1467    /**
1468     * @javadoc
1469     */

1470    private String JavaDoc nextCurTime(StringTokenizer tok) {
1471        int curtime=(int)(System.currentTimeMillis()/1000);
1472        //int curtime=(int)(System.currentTimeMillis()/1000);
1473
String JavaDoc cmd=tok.nextToken();
1474        if (cmd.equals("NEXTHOUR")) {
1475            // gives us the next full hour based on realtime
1476
int hours=curtime/3600;
1477            hours++;
1478            return ""+(hours*3600);
1479        } else if (cmd.equals("NEXTDAY")) {
1480            // gives us the next full day based on realtime (00:00)
1481
int days=curtime/(3600*24);
1482            days++;
1483            return ""+((days*(3600*24))-3600);
1484        } else if (cmd.equals("TODAY")) {
1485            // gives us the next full day based on realtime (00:00)
1486
int days=curtime/(3600*24);
1487            return ""+((days*(3600*24))-3600);
1488        } else if (cmd.equals("NEXTTIME")) {
1489            // gives us the next full day at time definedd based on realtime
1490
int days=curtime/(3600*24);
1491            if (tok.hasMoreTokens()) {
1492                String JavaDoc timestring=tok.nextToken();
1493                int pos=timestring.indexOf(":");
1494                if (pos!=-1) {
1495                    String JavaDoc hourstring=timestring.substring(0,pos);
1496                    String JavaDoc minstring=timestring.substring(pos+1);
1497                    try {
1498                        int hours=Integer.parseInt(hourstring)*3600;
1499                        int min=Integer.parseInt(minstring)*60;
1500                        int total=(days*3600*24)+hours+min;
1501                        return ""+(total-7200);
1502                    } catch (Exception JavaDoc e) {
1503                        log.error("Error in NEXTTIME time part make sure its 00:00 format");
1504                    }
1505                }
1506            }
1507            return ""+(days*(3600*24));
1508        }
1509        return "";
1510    }
1511}
1512
Popular Tags