Advertisement
Guest User

doug daniels

a guest
Aug 12th, 2009
437
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 27.91 KB | None | 0 0
  1. package com.webwars.logging;
  2.  
  3. import java.io.BufferedOutputStream;
  4. import java.io.File;
  5. import java.io.FileOutputStream;
  6. import java.io.IOException;
  7. import java.io.OutputStream;
  8. import java.nio.channels.FileChannel;
  9. import java.nio.channels.FileLock;
  10. import java.security.AccessController;
  11. import java.security.PrivilegedAction;
  12. import java.util.logging.ErrorManager;
  13. import java.util.logging.Filter;
  14. import java.util.logging.Formatter;
  15. import java.util.logging.Level;
  16. import java.util.logging.LogManager;
  17. import java.util.logging.LogRecord;
  18. import java.util.logging.StreamHandler;
  19. import java.util.logging.XMLFormatter;
  20.  
  21. /**
  22.  * Simple file logging <tt>Handler</tt>.
  23.  * <p>
  24.  * The <tt>FileHandler</tt> can either write to a specified file, or it can
  25.  * write to a rotating set of files.
  26.  * <p>
  27.  * For a rotating set of files, as each file reaches a given size limit, it is
  28.  * closed, rotated out, and a new file opened. Successively older files are
  29.  * named by adding "0", "1", "2", etc into the base filename.
  30.  * <p>
  31.  * By default buffering is enabled in the IO libraries but each log record is
  32.  * flushed out when it is complete.
  33.  * <p>
  34.  * By default the <tt>XMLFormatter</tt> class is used for formatting.
  35.  * <p>
  36.  * <b>Configuration:</b> By default each <tt>FileHandler</tt> is initialized
  37.  * using the following <tt>LogManager</tt> configuration properties. If
  38.  * properties are not defined (or have invalid values) then the specified
  39.  * default values are used.
  40.  * <ul>
  41.  * <li>java.util.logging.FileHandler.level specifies the default level for the
  42.  * <tt>Handler</tt> (defaults to <tt>Level.ALL</tt>).
  43.  * <li>java.util.logging.FileHandler.filter specifies the name of a
  44.  * <tt>Filter</tt> class to use (defaults to no <tt>Filter</tt>).
  45.  * <li>java.util.logging.FileHandler.formatter specifies the name of a
  46.  * <tt>Formatter</tt> class to use (defaults to
  47.  * <tt>java.util.logging.XMLFormatter</tt>)
  48.  * <li>java.util.logging.FileHandler.encoding the name of the character set
  49.  * encoding to use (defaults to the default platform encoding).
  50.  * <li>java.util.logging.FileHandler.limit specifies an approximate maximum
  51.  * amount to write (in bytes) to any one file. If this is zero, then there is no
  52.  * limit. (Defaults to no limit).
  53.  * <li>java.util.logging.FileHandler.count specifies how many output files to
  54.  * cycle through (defaults to 1).
  55.  * <li>java.util.logging.FileHandler.pattern specifies a pattern for generating
  56.  * the output file name. See below for details. (Defaults to "%h/java%u.log").
  57.  * <li>java.util.logging.FileHandler.append specifies whether the FileHandler
  58.  * should append onto any existing files (defaults to false).
  59.  * </ul>
  60.  * <p>
  61.  * <p>
  62.  * A pattern consists of a string that includes the following special components
  63.  * that will be replaced at runtime:
  64.  * <ul>
  65.  * <li>"/" the local pathname separator
  66.  * <li>"%t" the system temporary directory
  67.  * <li>"%h" the value of the "user.home" system property
  68.  * <li>"%g" the generation number to distinguish rotated logs
  69.  * <li>"%u" a unique number to resolve conflicts
  70.  * <li>"%%" translates to a single percent sign "%"
  71.  * </ul>
  72.  * If no "%g" field has been specified and the file count is greater than one,
  73.  * then the generation number will be added to the end of the generated
  74.  * filename, after a dot.
  75.  * <p>
  76.  * Thus for example a pattern of "%t/java%g.log" with a count of 2 would
  77.  * typically cause log files to be written on Solaris to /var/tmp/java0.log and
  78.  * /var/tmp/java1.log whereas on Windows 95 they would be typically written to
  79.  * C:\TEMP\java0.log and C:\TEMP\java1.log
  80.  * <p>
  81.  * Generation numbers follow the sequence 0, 1, 2, etc.
  82.  * <p>
  83.  * Normally the "%u" unique field is set to 0. However, if the
  84.  * <tt>FileHandler</tt> tries to open the filename and finds the file is
  85.  * currently in use by another process it will increment the unique number field
  86.  * and try again. This will be repeated until <tt>FileHandler</tt> finds a file
  87.  * name that is not currently in use. If there is a conflict and no "%u" field
  88.  * has been specified, it will be added at the end of the filename after a dot.
  89.  * (This will be after any automatically added generation number.)
  90.  * <p>
  91.  * Thus if three processes were all trying to log to fred%u.%g.txt then they
  92.  * might end up using fred0.0.txt, fred1.0.txt, fred2.0.txt as the first file in
  93.  * their rotating sequences.
  94.  * <p>
  95.  * Note that the use of unique ids to avoid conflicts is only guaranteed to work
  96.  * reliably when using a local disk file system.
  97.  *
  98.  * @version 1.36, 04/07/06
  99.  * @since 1.4
  100.  */
  101.  
  102. public class WebwarsFileHandler extends StreamHandler {
  103.     private LogManager manager = LogManager.getLogManager();
  104.  
  105.     private MeteredStream meter;
  106.  
  107.     private boolean append;
  108.  
  109.     private int limit; // zero => no limit.
  110.  
  111.     private int count;
  112.  
  113.     private String pattern;
  114.  
  115.     private String lockFileName;
  116.  
  117.     private FileOutputStream lockStream;
  118.  
  119.     private File files[];
  120.  
  121.     private static final int MAX_LOCKS = 100;
  122.  
  123.     private static java.util.HashMap locks = new java.util.HashMap();
  124.  
  125.     // A metered stream is a subclass of OutputStream that
  126.     // (a) forwards all its output to a target stream
  127.     // (b) keeps track of how many bytes have been written
  128.     private class MeteredStream extends OutputStream {
  129.         OutputStream out;
  130.  
  131.         int written;
  132.  
  133.         MeteredStream(OutputStream out, int written) {
  134.             this.out = out;
  135.             this.written = written;
  136.         }
  137.  
  138.         public void write(int b) throws IOException {
  139.             out.write(b);
  140.             written++;
  141.         }
  142.  
  143.         public void write(byte buff[]) throws IOException {
  144.             out.write(buff);
  145.             written += buff.length;
  146.         }
  147.  
  148.         public void write(byte buff[], int off, int len) throws IOException {
  149.             out.write(buff, off, len);
  150.             written += len;
  151.         }
  152.  
  153.         public void flush() throws IOException {
  154.             out.flush();
  155.         }
  156.  
  157.         public void close() throws IOException {
  158.             out.close();
  159.         }
  160.     }
  161.  
  162.     private void open(File fname, boolean append) throws IOException {
  163.         int len = 0;
  164.         if (append) {
  165.             len = (int) fname.length();
  166.         }
  167.         FileOutputStream fout = new FileOutputStream(fname.toString(), append);
  168.         BufferedOutputStream bout = new BufferedOutputStream(fout);
  169.         meter = new MeteredStream(bout, len);
  170.         setOutputStream(meter);
  171.     }
  172.  
  173.     // Private method to configure a FileHandler from LogManager
  174.     // properties and/or default values as specified in the class
  175.     // javadoc.
  176.     private void configure() {
  177.         LogManager manager = LogManager.getLogManager();
  178.  
  179.         String cname = getClass().getName();
  180.         pattern = getStringProperty(cname + ".pattern", "%h/java%u.log");
  181.         limit = getIntProperty(cname + ".limit", 0);
  182.         if (limit < 0) {
  183.             limit = 0;
  184.         }
  185.         count = getIntProperty(cname + ".count", 1);
  186.         if (count <= 0) {
  187.             count = 1;
  188.         }
  189.         append = getBooleanProperty(cname + ".append", false);
  190.         setLevel(getLevelProperty(cname + ".level", Level.ALL));
  191.         setFilter(getFilterProperty(cname + ".filter", null));
  192.         setFormatter(getFormatterProperty(cname + ".formatter",
  193.                 new XMLFormatter()));
  194.         try {
  195.             setEncoding(getStringProperty(cname + ".encoding", null));
  196.         } catch (Exception ex) {
  197.             try {
  198.                 setEncoding(null);
  199.             } catch (Exception ex2) {
  200.                 // doing a setEncoding with null should always work.
  201.                 // assert false;
  202.             }
  203.         }
  204.     }
  205.  
  206.     /**
  207.      * Construct a default <tt>FileHandler</tt>. This will be configured
  208.      * entirely from <tt>LogManager</tt> properties (or their default values).
  209.      * <p>
  210.      *
  211.      * @exception IOException
  212.      *                if there are IO problems opening the files.
  213.      * @exception SecurityException
  214.      *                if a security manager exists and if the caller does not
  215.      *                have <tt>LoggingPermission("control"))</tt>.
  216.      * @exception NullPointerException
  217.      *                if pattern property is an empty String.
  218.      */
  219.     public WebwarsFileHandler() throws IOException, SecurityException {
  220.         // checkAccess();
  221.         configure();
  222.         openFiles();
  223.     }
  224.  
  225.     /**
  226.      * Initialize a <tt>FileHandler</tt> to write to the given filename.
  227.      * <p>
  228.      * The <tt>FileHandler</tt> is configured based on <tt>LogManager</tt>
  229.      * properties (or their default values) except that the given pattern
  230.      * argument is used as the filename pattern, the file limit is set to no
  231.      * limit, and the file count is set to one.
  232.      * <p>
  233.      * There is no limit on the amount of data that may be written, so use this
  234.      * with care.
  235.      *
  236.      * @param pattern
  237.      *            the name of the output file
  238.      * @exception IOException
  239.      *                if there are IO problems opening the files.
  240.      * @exception SecurityException
  241.      *                if a security manager exists and if the caller does not
  242.      *                have <tt>LoggingPermission("control")</tt>.
  243.      * @exception IllegalArgumentException
  244.      *                if pattern is an empty string
  245.      */
  246.     public WebwarsFileHandler(String pattern) throws IOException,
  247.             SecurityException {
  248.         if (pattern.length() < 1) {
  249.             throw new IllegalArgumentException();
  250.         }
  251.         // checkAccess();
  252.         configure();
  253.         this.pattern = pattern;
  254.         this.limit = 0;
  255.         this.count = 1;
  256.         openFiles();
  257.     }
  258.  
  259.     /**
  260.      * Initialize a <tt>FileHandler</tt> to write to the given filename, with
  261.      * optional append.
  262.      * <p>
  263.      * The <tt>FileHandler</tt> is configured based on <tt>LogManager</tt>
  264.      * properties (or their default values) except that the given pattern
  265.      * argument is used as the filename pattern, the file limit is set to no
  266.      * limit, the file count is set to one, and the append mode is set to the
  267.      * given <tt>append</tt> argument.
  268.      * <p>
  269.      * There is no limit on the amount of data that may be written, so use this
  270.      * with care.
  271.      *
  272.      * @param pattern
  273.      *            the name of the output file
  274.      * @param append
  275.      *            specifies append mode
  276.      * @exception IOException
  277.      *                if there are IO problems opening the files.
  278.      * @exception SecurityException
  279.      *                if a security manager exists and if the caller does not
  280.      *                have <tt>LoggingPermission("control")</tt>.
  281.      * @exception IllegalArgumentException
  282.      *                if pattern is an empty string
  283.      */
  284.     public WebwarsFileHandler(String pattern, boolean append)
  285.             throws IOException, SecurityException {
  286.         if (pattern.length() < 1) {
  287.             throw new IllegalArgumentException();
  288.         }
  289.         // checkAccess();
  290.         configure();
  291.         this.pattern = pattern;
  292.         this.limit = 0;
  293.         this.count = 1;
  294.         this.append = append;
  295.         openFiles();
  296.     }
  297.  
  298.     /**
  299.      * Initialize a <tt>FileHandler</tt> to write to a set of files. When
  300.      * (approximately) the given limit has been written to one file, another
  301.      * file will be opened. The output will cycle through a set of count files.
  302.      * <p>
  303.      * The <tt>FileHandler</tt> is configured based on <tt>LogManager</tt>
  304.      * properties (or their default values) except that the given pattern
  305.      * argument is used as the filename pattern, the file limit is set to the
  306.      * limit argument, and the file count is set to the given count argument.
  307.      * <p>
  308.      * The count must be at least 1.
  309.      *
  310.      * @param pattern
  311.      *            the pattern for naming the output file
  312.      * @param limit
  313.      *            the maximum number of bytes to write to any one file
  314.      * @param count
  315.      *            the number of files to use
  316.      * @exception IOException
  317.      *                if there are IO problems opening the files.
  318.      * @exception SecurityException
  319.      *                if a security manager exists and if the caller does not
  320.      *                have <tt>LoggingPermission("control")</tt>.
  321.      * @exception IllegalArgumentException
  322.      *                if limit < 0, or count < 1.
  323.      * @exception IllegalArgumentException
  324.      *                if pattern is an empty string
  325.      */
  326.     public WebwarsFileHandler(String pattern, int limit, int count)
  327.             throws IOException, SecurityException {
  328.         if (limit < 0 || count < 1 || pattern.length() < 1) {
  329.             throw new IllegalArgumentException();
  330.         }
  331.         // checkAccess();
  332.         configure();
  333.         this.pattern = pattern;
  334.         this.limit = limit;
  335.         this.count = count;
  336.         openFiles();
  337.     }
  338.  
  339.     /**
  340.      * Initialize a <tt>FileHandler</tt> to write to a set of files with
  341.      * optional append. When (approximately) the given limit has been written to
  342.      * one file, another file will be opened. The output will cycle through a
  343.      * set of count files.
  344.      * <p>
  345.      * The <tt>FileHandler</tt> is configured based on <tt>LogManager</tt>
  346.      * properties (or their default values) except that the given pattern
  347.      * argument is used as the filename pattern, the file limit is set to the
  348.      * limit argument, and the file count is set to the given count argument,
  349.      * and the append mode is set to the given <tt>append</tt> argument.
  350.      * <p>
  351.      * The count must be at least 1.
  352.      *
  353.      * @param pattern
  354.      *            the pattern for naming the output file
  355.      * @param limit
  356.      *            the maximum number of bytes to write to any one file
  357.      * @param count
  358.      *            the number of files to use
  359.      * @param append
  360.      *            specifies append mode
  361.      * @exception IOException
  362.      *                if there are IO problems opening the files.
  363.      * @exception SecurityException
  364.      *                if a security manager exists and if the caller does not
  365.      *                have <tt>LoggingPermission("control")</tt>.
  366.      * @exception IllegalArgumentException
  367.      *                if limit < 0, or count < 1.
  368.      * @exception IllegalArgumentException
  369.      *                if pattern is an empty string
  370.      *
  371.      */
  372.     public WebwarsFileHandler(String pattern, int limit, int count,
  373.             boolean append) throws IOException, SecurityException {
  374.         if (limit < 0 || count < 1 || pattern.length() < 1) {
  375.             throw new IllegalArgumentException();
  376.         }
  377.         // checkAccess();
  378.         configure();
  379.         this.pattern = pattern;
  380.         this.limit = limit;
  381.         this.count = count;
  382.         this.append = append;
  383.         openFiles();
  384.     }
  385.  
  386.     // Private method to open the set of output files, based on the
  387.     // configured instance variables.
  388.     private void openFiles() throws IOException {
  389.         LogManager manager = LogManager.getLogManager();
  390.         manager.checkAccess();
  391.         if (count < 1) {
  392.             throw new IllegalArgumentException("file count = " + count);
  393.         }
  394.         if (limit < 0) {
  395.             limit = 0;
  396.         }
  397.  
  398.         // We register our own ErrorManager during initialization
  399.         // so we can record exceptions.
  400.         InitializationErrorManager em = new InitializationErrorManager();
  401.         setErrorManager(em);
  402.  
  403.         // Create a lock file. This grants us exclusive access
  404.         // to our set of output files, as long as we are alive.
  405.         int unique = -1;
  406.         for (;;) {
  407.             unique++;
  408.             if (unique > MAX_LOCKS) {
  409.                 throw new IOException("Couldn't get lock for " + pattern);
  410.             }
  411.             // Generate a lock file name from the "unique" int.
  412.             lockFileName = generate(pattern, 0, unique).toString() + ".lck";
  413.             // Now try to lock that filename.
  414.             // Because some systems (e.g. Solaris) can only do file locks
  415.             // between processes (and not within a process), we first check
  416.             // if we ourself already have the file locked.
  417.             synchronized (locks) {
  418.                 if (locks.get(lockFileName) != null) {
  419.                     // We already own this lock, for a different FileHandler
  420.                     // object. Try again.
  421.                     continue;
  422.                 }
  423.                 FileChannel fc;
  424.                 try {
  425.                     File lockFile = new File(lockFileName);
  426.                     if (lockFile.getParent() != null) {
  427.                         File lockParentDir = new File(lockFile.getParent());
  428.                         // create the log dir if it does not exist
  429.                         if (!lockParentDir.exists()) {
  430.                             lockParentDir.mkdirs();
  431.                         }
  432.                     }
  433.  
  434.                     lockStream = new FileOutputStream(lockFileName);
  435.                     fc = lockStream.getChannel();
  436.                 } catch (IOException ix) {
  437.                     // We got an IOException while trying to open the file.
  438.                     // Try the next file.
  439.                     continue;
  440.                 }
  441.                 try {
  442.                     FileLock fl = fc.tryLock();
  443.                     if (fl == null) {
  444.                         // We failed to get the lock. Try next file.
  445.                         continue;
  446.                     }
  447.                     // We got the lock OK.
  448.                 } catch (IOException ix) {
  449.                     // We got an IOException while trying to get the lock.
  450.                     // This normally indicates that locking is not supported
  451.                     // on the target directory. We have to proceed without
  452.                     // getting a lock. Drop through.
  453.                 }
  454.                 // We got the lock. Remember it.
  455.                 locks.put(lockFileName, lockFileName);
  456.                 break;
  457.             }
  458.         }
  459.  
  460.         files = new File[count];
  461.         for (int i = 0; i < count; i++) {
  462.             files[i] = generate(pattern, i, unique);
  463.         }
  464.  
  465.         // Create the initial log file.
  466.         if (append) {
  467.             open(files[0], true);
  468.         } else {
  469.             rotate();
  470.         }
  471.  
  472.         // Did we detect any exceptions during initialization?
  473.         Exception ex = em.lastException;
  474.         if (ex != null) {
  475.             if (ex instanceof IOException) {
  476.                 throw (IOException) ex;
  477.             } else if (ex instanceof SecurityException) {
  478.                 throw (SecurityException) ex;
  479.             } else {
  480.                 throw new IOException("Exception: " + ex);
  481.             }
  482.         }
  483.  
  484.         // Install the normal default ErrorManager.
  485.         setErrorManager(new ErrorManager());
  486.     }
  487.  
  488.     // Generate a filename from a pattern.
  489.     private File generate(String pattern, int generation, int unique)
  490.             throws IOException {
  491.         File file = null;
  492.         String word = "";
  493.         int ix = 0;
  494.         boolean sawg = false;
  495.         boolean sawu = false;
  496.         while (ix < pattern.length()) {
  497.             char ch = pattern.charAt(ix);
  498.             ix++;
  499.             char ch2 = 0;
  500.             if (ix < pattern.length()) {
  501.                 ch2 = Character.toLowerCase(pattern.charAt(ix));
  502.             }
  503.             if (ch == '/') {
  504.                 if (file == null) {
  505.                     file = new File(word);
  506.                 } else {
  507.                     file = new File(file, word);
  508.                 }
  509.                 word = "";
  510.                 continue;
  511.             } else if (ch == '%') {
  512.                 if (ch2 == 't') {
  513.                     String tmpDir = System.getProperty("java.io.tmpdir");
  514.                     if (tmpDir == null) {
  515.                         tmpDir = System.getProperty("user.home");
  516.                     }
  517.                     file = new File(tmpDir);
  518.                     ix++;
  519.                     word = "";
  520.                     continue;
  521.                 } else if (ch2 == 'h') {
  522.                     file = new File(System.getProperty("user.home"));
  523.                     /**
  524.                      * if (isSetUID()) { // Ok, we are in a set UID program. For
  525.                      * safety's sake // we disallow attempts to open files
  526.                      * relative to %h. throw new
  527.                      * IOException("can't use %h in set UID program"); }
  528.                      **/
  529.                     ix++;
  530.                     word = "";
  531.                     continue;
  532.                 } else if (ch2 == 'g') {
  533.                     word = word + generation;
  534.                     sawg = true;
  535.                     ix++;
  536.                     continue;
  537.                 } else if (ch2 == 'u') {
  538.                     word = word + unique;
  539.                     sawu = true;
  540.                     ix++;
  541.                     continue;
  542.                 } else if (ch2 == '%') {
  543.                     word = word + "%";
  544.                     ix++;
  545.                     continue;
  546.                 }
  547.             }
  548.             word = word + ch;
  549.         }
  550.         if (count > 1 && !sawg) {
  551.             word = word + "." + generation;
  552.         }
  553.         if (unique > 0 && !sawu) {
  554.             word = word + "." + unique;
  555.         }
  556.         if (word.length() > 0) {
  557.             if (file == null) {
  558.                 file = new File(word);
  559.             } else {
  560.                 file = new File(file, word);
  561.             }
  562.         }
  563.         return file;
  564.     }
  565.  
  566.     // Rotate the set of output files
  567.     private synchronized void rotate() {
  568.         Level oldLevel = getLevel();
  569.         setLevel(Level.OFF);
  570.  
  571.         super.close();
  572.         for (int i = count - 2; i >= 0; i--) {
  573.             File f1 = files[i];
  574.             File f2 = files[i + 1];
  575.             if (f1.exists()) {
  576.                 if (f2.exists()) {
  577.                     f2.delete();
  578.                 }
  579.                 f1.renameTo(f2);
  580.             }
  581.         }
  582.         try {
  583.             open(files[0], false);
  584.         } catch (IOException ix) {
  585.             // We don't want to throw an exception here, but we
  586.             // report the exception to any registered ErrorManager.
  587.             reportError(null, ix, ErrorManager.OPEN_FAILURE);
  588.  
  589.         }
  590.         setLevel(oldLevel);
  591.     }
  592.  
  593.     /**
  594.      * Format and publish a <tt>LogRecord</tt>.
  595.      *
  596.      * @param record
  597.      *            description of the log event. A null record is silently
  598.      *            ignored and is not published
  599.      */
  600.     public synchronized void publish(LogRecord record) {
  601.         if (!isLoggable(record)) {
  602.             return;
  603.         }
  604.         super.publish(record);
  605.         flush();
  606.         if (limit > 0 && meter.written >= limit) {
  607.             // We performed access checks in the "init" method to make sure
  608.             // we are only initialized from trusted code. So we assume
  609.             // it is OK to write the target files, even if we are
  610.             // currently being called from untrusted code.
  611.             // So it is safe to raise privilege here.
  612.             AccessController.doPrivileged(new PrivilegedAction() {
  613.                 public Object run() {
  614.                     rotate();
  615.                     return null;
  616.                 }
  617.             });
  618.         }
  619.     }
  620.  
  621.     /**
  622.      * Close all the files.
  623.      *
  624.      * @exception SecurityException
  625.      *                if a security manager exists and if the caller does not
  626.      *                have <tt>LoggingPermission("control")</tt>.
  627.      */
  628.     public synchronized void close() throws SecurityException {
  629.         super.close();
  630.         // Unlock any lock file.
  631.         if (lockFileName == null) {
  632.             return;
  633.         }
  634.         try {
  635.             // Closing the lock file's FileOutputStream will close
  636.             // the underlying channel and free any locks.
  637.             lockStream.close();
  638.         } catch (Exception ex) {
  639.             // Problems closing the stream. Punt.
  640.         }
  641.         synchronized (locks) {
  642.             locks.remove(lockFileName);
  643.         }
  644.         new File(lockFileName).delete();
  645.         lockFileName = null;
  646.         lockStream = null;
  647.     }
  648.  
  649.     private static class InitializationErrorManager extends ErrorManager {
  650.         Exception lastException;
  651.  
  652.         public void error(String msg, Exception ex, int code) {
  653.             lastException = ex;
  654.         }
  655.     }
  656.  
  657.     // Package private method to get a String property.
  658.     // If the property is not defined we return the given
  659.     // default value.
  660.     protected String getStringProperty(String name, String defaultValue) {
  661.         String val = manager.getProperty(name);
  662.         if (val == null) {
  663.             return defaultValue;
  664.         }
  665.         return val.trim();
  666.     }
  667.  
  668.     // Package private method to get an integer property.
  669.     // If the property is not defined or cannot be parsed
  670.     // we return the given default value.
  671.     protected int getIntProperty(String name, int defaultValue) {
  672.         String val = manager.getProperty(name);
  673.         if (val == null) {
  674.             return defaultValue;
  675.         }
  676.         try {
  677.             return Integer.parseInt(val.trim());
  678.         } catch (Exception ex) {
  679.             return defaultValue;
  680.         }
  681.     }
  682.  
  683.     // Package private method to get a boolean property.
  684.     // If the property is not defined or cannot be parsed
  685.     // we return the given default value.
  686.     protected boolean getBooleanProperty(String name, boolean defaultValue) {
  687.         String val = manager.getProperty(name);
  688.         if (val == null) {
  689.             return defaultValue;
  690.         }
  691.         val = val.toLowerCase();
  692.         if (val.equals("true") || val.equals("1")) {
  693.             return true;
  694.         } else if (val.equals("false") || val.equals("0")) {
  695.             return false;
  696.         }
  697.         return defaultValue;
  698.     }
  699.  
  700.     // Package private method to get a Level property.
  701.     // If the property is not defined or cannot be parsed
  702.     // we return the given default value.
  703.     protected Level getLevelProperty(String name, Level defaultValue) {
  704.         String val = manager.getProperty(name);
  705.         if (val == null) {
  706.             return defaultValue;
  707.         }
  708.         try {
  709.             return Level.parse(val.trim());
  710.         } catch (Exception ex) {
  711.             return defaultValue;
  712.         }
  713.     }
  714.  
  715.     // Package private method to get a filter property.
  716.     // We return an instance of the class named by the "name"
  717.     // property. If the property is not defined or has problems
  718.     // we return the defaultValue.
  719.     protected Filter getFilterProperty(String name, Filter defaultValue) {
  720.         String val = manager.getProperty(name);
  721.         try {
  722.             if (val != null) {
  723.                 Class clz = ClassLoader.getSystemClassLoader().loadClass(val);
  724.                 return (Filter) clz.newInstance();
  725.             }
  726.         } catch (Exception ex) {
  727.             // We got one of a variety of exceptions in creating the
  728.             // class or creating an instance.
  729.             // Drop through.
  730.         }
  731.         // We got an exception. Return the defaultValue.
  732.         return defaultValue;
  733.     }
  734.  
  735.     // Package private method to get a formatter property.
  736.     // We return an instance of the class named by the "name"
  737.     // property. If the property is not defined or has problems
  738.     // we return the defaultValue.
  739.     protected Formatter getFormatterProperty(String name, Formatter defaultValue) {
  740.         String val = manager.getProperty(name);
  741.         try {
  742.             if (val != null) {
  743.                 Class clz = ClassLoader.getSystemClassLoader().loadClass(val);
  744.                 return (Formatter) clz.newInstance();
  745.             }
  746.         } catch (Exception ex) {
  747.             // We got one of a variety of exceptions in creating the
  748.             // class or creating an instance.
  749.             // Drop through.
  750.         }
  751.         // We got an exception. Return the defaultValue.
  752.         return defaultValue;
  753.     }
  754. }
  755.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement