You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@harmony.apache.org by py...@apache.org on 2006/08/18 13:13:40 UTC

svn commit: r432552 - in /incubator/harmony/enhanced/classlib/trunk/modules/logging/src: main/java/java/util/logging/ test/java/org/apache/harmony/logging/tests/java/util/logging/

Author: pyang
Date: Fri Aug 18 04:13:36 2006
New Revision: 432552

URL: http://svn.apache.org/viewvc?rev=432552&view=rev
Log:
Lazy load handlers to improve performance when the logger is opened but not used, original Harmony codes failed to pass the system test like this: open a logger with FileHandler, and then abandon it, Harmony code will leave a empty file in the disk, while RI leaves nothing.

Also fixed some invalid tests which fail on RI, as well as related implementations.

Modified:
    incubator/harmony/enhanced/classlib/trunk/modules/logging/src/main/java/java/util/logging/FileHandler.java
    incubator/harmony/enhanced/classlib/trunk/modules/logging/src/main/java/java/util/logging/LogManager.java
    incubator/harmony/enhanced/classlib/trunk/modules/logging/src/main/java/java/util/logging/Logger.java
    incubator/harmony/enhanced/classlib/trunk/modules/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/FileHandlerTest.java
    incubator/harmony/enhanced/classlib/trunk/modules/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/LogManagerTest.java
    incubator/harmony/enhanced/classlib/trunk/modules/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/LoggerTest.java

Modified: incubator/harmony/enhanced/classlib/trunk/modules/logging/src/main/java/java/util/logging/FileHandler.java
URL: http://svn.apache.org/viewvc/incubator/harmony/enhanced/classlib/trunk/modules/logging/src/main/java/java/util/logging/FileHandler.java?rev=432552&r1=432551&r2=432552&view=diff
==============================================================================
--- incubator/harmony/enhanced/classlib/trunk/modules/logging/src/main/java/java/util/logging/FileHandler.java (original)
+++ incubator/harmony/enhanced/classlib/trunk/modules/logging/src/main/java/java/util/logging/FileHandler.java Fri Aug 18 04:13:36 2006
@@ -153,9 +153,9 @@
 
     //current output file name
     String fileName = null;
-
-    //current generation
-    int generation = 0;
+    
+    //current unique ID
+    int uniqueID = -1;
 
     /*
      * ---------------------------------------------
@@ -181,8 +181,7 @@
     }
 
     //init properties
-    private void init(String p, Boolean a, Integer l, Integer c)
-            throws IOException {
+    private void init(String p, Boolean a, Integer l, Integer c) throws IOException{
         //check access
         manager = LogManager.getLogManager();
         manager.checkAccess();
@@ -191,20 +190,33 @@
     }
 
     private void initOutputFiles() throws FileNotFoundException, IOException {
-        int uniqueID = -1;
         FileOutputStream fileStream = null;
         FileChannel channel = null;
         while (true) {
             //try to find a unique file which is not locked by other process
-            fileName = parseFileName(generation, ++uniqueID);
+            uniqueID++;
+            //FIXME: improve performance here
+            for (int generation = 0; generation < count; generation++) {
+                //cache all file names for rotation use
+                files[generation] = new File(parseFileName(generation, uniqueID));
+            }
+            fileName = files[0].getAbsolutePath();
             synchronized (allLocks) {
                 //if current process has held lock for this fileName
                 //continue to find next file
                 if (null != allLocks.get(fileName)) {
                     continue;
                 }
+                if(files[0].exists() && (!append || files[0].length() >= limit)){
+                    for (int i = count - 1; i > 0; i--) {
+                        if (files[i].exists()) {
+                            files[i].delete();
+                        }
+                        files[i - 1].renameTo(files[i]);
+                    }
+                }
                 try {
-                    fileStream = new FileOutputStream(fileName, true);
+                    fileStream = new FileOutputStream(fileName, append);
                     channel = fileStream.getChannel();
                 } catch(FileNotFoundException e){
                     //invalid path name, throw exception
@@ -219,23 +231,13 @@
                 if (null == lock) {
                     continue;
                 }
-				files[0] = new File(fileName);
 				allLocks.put(fileName, lock);
 				break;
             }
         }
-        for (generation = 1; generation < count; generation++) {
-            //cache all file names for rotation use
-            files[generation] = new File(parseFileName(generation, uniqueID));
-        }
         output = new MeasureOutputStream(new BufferedOutputStream(fileStream),
                 files[0].length());
-        if (append && output.getLength() < limit) {
-            setOutputStream(output);
-        } else {
-            setOutputStream(output);
-            findNextGeneration();
-        }
+        setOutputStream(output);
     }
 
     private void initProperties(String p, Boolean a, Integer l, Integer c) {
@@ -550,8 +552,6 @@
     public void close() {
         //release locks
         super.close();
-        //        //FIXME: delete this
-        //        System.out.println("close:"+fileName);
         allLocks.remove(fileName);
         try {
             lock.release();

Modified: incubator/harmony/enhanced/classlib/trunk/modules/logging/src/main/java/java/util/logging/LogManager.java
URL: http://svn.apache.org/viewvc/incubator/harmony/enhanced/classlib/trunk/modules/logging/src/main/java/java/util/logging/LogManager.java?rev=432552&r1=432551&r2=432552&view=diff
==============================================================================
--- incubator/harmony/enhanced/classlib/trunk/modules/logging/src/main/java/java/util/logging/LogManager.java (original)
+++ incubator/harmony/enhanced/classlib/trunk/modules/logging/src/main/java/java/util/logging/LogManager.java Fri Aug 18 04:13:36 2006
@@ -138,9 +138,6 @@
     // Use privileged code to read the line.separator system property
     private static final String lineSeparator = getPrivilegedSystemProperty("line.separator"); //$NON-NLS-1$
 
-    // The file separator of the underlying OS
-    private static final String fileSeparator = File.separator;
-
     // The shared logging permission
     private static final LoggingPermission perm = new LoggingPermission(
             "control", null); //$NON-NLS-1$
@@ -186,15 +183,14 @@
         if (null == manager) {
             manager = new LogManager();
         }
-        // init root logger
-        manager.root = new Logger("", null); //$NON-NLS-1$
-        manager.loggers.put("", manager.root); //$NON-NLS-1$
+
         // read configuration
         try {
             manager.readConfiguration();
         } catch (Exception e) {
             e.printStackTrace();
         }
+        
         // if global logger has been initialized, set root as its parent
         if (null != Logger.global) {
             Logger.global.setParent(manager.root);
@@ -291,6 +287,7 @@
         }
 
         setLoggerLevel(logger, name, false);
+        logger.manager = this;
         return true;
     }
 
@@ -447,8 +444,8 @@
             if (null == configFile) {
                 // if cannot find configFile, use default logging.properties
                 configFile = new StringBuilder().append(
-                        System.getProperty("java.home")).append(fileSeparator) //$NON-NLS-1$
-                        .append("lib").append(fileSeparator).append( //$NON-NLS-1$
+                        System.getProperty("java.home")).append(File.separator) //$NON-NLS-1$
+                        .append("lib").append(File.separator).append( //$NON-NLS-1$
                                 "logging.properties").toString(); //$NON-NLS-1$
             }
             InputStream input = null;
@@ -468,14 +465,17 @@
     private synchronized void readConfigurationImpl(InputStream ins)
             throws IOException {
         reset();
+        if(manager.root == null){
+            // init root logger
+            manager.root = new Logger("", null); //$NON-NLS-1$
+            manager.loggers.put("", manager.root); //$NON-NLS-1$
+            root.manager = this;
+        }
         props.load(ins);
 
         // configs
         parseConfigProp();
 
-        // handlers
-        parseHandlerProp();
-
         // set levels for logger
         initLevelForLoggers();
         listeners.firePropertyChange(null, null, null);
@@ -501,25 +501,6 @@
         }
     }
 
-    // parse "handlers" property and apply setting
-    private void parseHandlerProp() {
-        // Logger rootLogger = root.getLogger();
-        String handlers = props.getProperty("handlers"); //$NON-NLS-1$
-        if (null == root || null == handlers) {
-            return;
-        }
-        StringTokenizer st = new StringTokenizer(handlers, " "); //$NON-NLS-1$
-        while (st.hasMoreTokens()) {
-            String handlerName = st.nextToken();
-            Handler handler = (Handler) getInstanceByClass(handlerName);
-            root.addHandler(handler);
-            String level = props.getProperty(handlerName + ".level"); //$NON-NLS-1$
-            if (null != level) {
-                handler.setLevel(Level.parse(level));
-            }
-        }
-    }
-
     // parse property "config" and apply setting
     private void parseConfigProp() {
         String configs = props.getProperty("config"); //$NON-NLS-1$
@@ -571,16 +552,17 @@
         while (it.hasNext()) {
             Logger l = (Logger) it.next();
             l.setLevel(null);
-            Handler[] handlers = l.getHandlers();
-            for (Handler element : handlers) {
-                l.removeHandler(element);
-                // close all handlers, when unknown exceptions happen,
-                // ignore them and go on
-                try {
-                    element.close();
-                } catch (Exception e) {
-                    // Ignored.
+            if(l.handlers != null){
+                for (Handler element : l.handlers) {
+                    // close all handlers, when unknown exceptions happen,
+                    // ignore them and go on
+                    try {
+                        element.close();
+                    } catch (Exception e) {
+                        // Ignored.
+                    }
                 }
+                l.handlers = null;
             }
         }
         if (null != root) {
@@ -599,6 +581,9 @@
      *             not have the required permissions to perform this action
      */
     public void addPropertyChangeListener(PropertyChangeListener l) {
+        if(l == null){
+            throw new NullPointerException();
+        }
         checkAccess();
         listeners.addPropertyChangeListener(l);
     }

Modified: incubator/harmony/enhanced/classlib/trunk/modules/logging/src/main/java/java/util/logging/Logger.java
URL: http://svn.apache.org/viewvc/incubator/harmony/enhanced/classlib/trunk/modules/logging/src/main/java/java/util/logging/Logger.java?rev=432552&r1=432551&r2=432552&view=diff
==============================================================================
--- incubator/harmony/enhanced/classlib/trunk/modules/logging/src/main/java/java/util/logging/Logger.java (original)
+++ incubator/harmony/enhanced/classlib/trunk/modules/logging/src/main/java/java/util/logging/Logger.java Fri Aug 18 04:13:36 2006
@@ -18,11 +18,12 @@
 
 import java.security.AccessController;
 import java.security.PrivilegedAction;
+import java.util.ArrayList;
+import java.util.List;
 import java.util.Locale;
-import java.util.ResourceBundle;
 import java.util.MissingResourceException;
-import java.util.List;
-import java.util.ArrayList;
+import java.util.ResourceBundle;
+import java.util.StringTokenizer;
 
 /**
  * Loggers are used to log records to certain outputs, including file, console,
@@ -126,7 +127,7 @@
     private ResourceBundle resBundle;
 
     // the handlers attached to this logger
-    private List<Handler> handlers;
+    List<Handler> handlers = null;
 
     /*
      * flag indicating whether to notify parent's handlers on receiving a log
@@ -138,6 +139,8 @@
     private boolean isNamed;
 
     private List<Logger> childs;
+    
+    LogManager manager = null;
 
     /*
      * -------------------------------------------------------------------
@@ -169,7 +172,6 @@
         this.name = name;
         this.parent = null;
         this.filter = null;
-        this.handlers = new ArrayList<Handler>();
         this.childs = new ArrayList<Logger>();
         this.notifyParentHandlers = true;
         // any logger is not anonymous by default
@@ -421,8 +423,33 @@
         if (this.isNamed) {
             LogManager.getLogManager().checkAccess();
         }
+        initHandler();
         this.handlers.add(handler);
     }
+    
+    private void initHandler() {
+      if(handlers == null){
+          if(manager == null){
+              handlers = new ArrayList<Handler>();
+              return;
+          }
+          handlers = new ArrayList<Handler>();
+          String handlerStr = manager.getProperty(name==""?"handlers":name+".handlers"); //$NON-NLS-1$
+          if (null == handlerStr) {
+              return;
+          }
+          StringTokenizer st = new StringTokenizer(handlerStr, " "); //$NON-NLS-1$
+          while (st.hasMoreTokens()) {
+              String handlerName = st.nextToken();
+              Handler handler = (Handler)LogManager.getInstanceByClass(handlerName);
+              handlers.add(handler);
+              String level = manager.getProperty(handlerName + ".level"); //$NON-NLS-1$
+              if (null != level) {
+                  handler.setLevel(Level.parse(level));
+              }
+          }
+      }
+    }
 
     /**
      * Gets all the handlers associated with this logger.
@@ -430,6 +457,7 @@
      * @return an array of all the handlers associated with this logger
      */
     public synchronized Handler[] getHandlers() {
+        initHandler();
         return handlers.toArray(new Handler[handlers.size()]);
     }
 
@@ -449,8 +477,9 @@
             LogManager.getLogManager().checkAccess();
         }
         if (null == handler) {
-            throw new NullPointerException("The 'handler' parameter is null."); //$NON-NLS-1$
+            return;
         }
+        initHandler();
         this.handlers.remove(handler);
     }
 
@@ -1061,24 +1090,19 @@
              * call the handlers of this logger, throw any exception that
              * occurs
              */
-            Handler[] ha = this.getHandlers();
-            for (Handler element : ha) {
+            initHandler();
+            for (Handler element : handlers) {
                 element.publish(record);
             }
             // call the parent's handlers if set useParentHandlers
-            if (getUseParentHandlers()) {
-                Logger anyParent = this.parent;
-                while (null != anyParent) {
-                    ha = anyParent.getHandlers();
-                    for (Handler element : ha) {
-                        element.publish(record);
-                    }
-                    if (anyParent.getUseParentHandlers()) {
-                        anyParent = anyParent.parent;
-                    } else {
-                        break;
-                    }
+            Logger temp = this;
+            while (temp.parent != null && temp.getUseParentHandlers()) {
+                Logger anyParent = temp.parent;
+                Handler[] ha = anyParent.getHandlers();
+                for (Handler element : ha) {
+                    element.publish(record);
                 }
+                temp = anyParent;   
             }
         }
     }

Modified: incubator/harmony/enhanced/classlib/trunk/modules/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/FileHandlerTest.java
URL: http://svn.apache.org/viewvc/incubator/harmony/enhanced/classlib/trunk/modules/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/FileHandlerTest.java?rev=432552&r1=432551&r2=432552&view=diff
==============================================================================
--- incubator/harmony/enhanced/classlib/trunk/modules/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/FileHandlerTest.java (original)
+++ incubator/harmony/enhanced/classlib/trunk/modules/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/FileHandlerTest.java Fri Aug 18 04:13:36 2006
@@ -227,7 +227,7 @@
 			// System.out.println(new String(chars));
 			assertEquals(msg, new String(chars));
 			// assert has reached the end of the file
-			assertEquals(reader.read(), -1);
+			assertEquals(-1, reader.read());
 		} finally {
 			try {
                 if (reader != null) {

Modified: incubator/harmony/enhanced/classlib/trunk/modules/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/LogManagerTest.java
URL: http://svn.apache.org/viewvc/incubator/harmony/enhanced/classlib/trunk/modules/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/LogManagerTest.java?rev=432552&r1=432551&r2=432552&view=diff
==============================================================================
--- incubator/harmony/enhanced/classlib/trunk/modules/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/LogManagerTest.java (original)
+++ incubator/harmony/enhanced/classlib/trunk/modules/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/LogManagerTest.java Fri Aug 18 04:13:36 2006
@@ -423,8 +423,8 @@
 		}
 		try {
 			mockManager.addPropertyChangeListener(null);
-			fail("should throw SecurityException");
-		} catch (SecurityException e) {
+			fail("should throw NPE");
+		} catch (NullPointerException e) {
 		}
 		try {
 			mockManager.removePropertyChangeListener(null);
@@ -540,9 +540,6 @@
 			// for non specifed logger, level is reset to null
 			assertEquals(null, fo.getLevel());
 
-			// handlers has no effect
-			assertEquals(0, foo.getHandlers().length);
-
 			// read properties don't affect handler
 			assertNotSame(Level.OFF, h.getLevel());
 			assertSame(l, h.getLevel());
@@ -578,8 +575,7 @@
 
 		// level DO has effect
 		assertEquals(Level.WARNING, foo.getLevel());
-		// handlers has no effect
-		assertEquals(0, foo.getHandlers().length);
+
 		// for non specifed logger, level is reset to null
 		assertEquals(null, fo.getLevel());
 
@@ -678,7 +674,11 @@
 
 	public void testAddRemovePropertyChangeListener_null() {
 		// seems nothing happened
-		mockManager.addPropertyChangeListener(null);
+        try{
+            mockManager.addPropertyChangeListener(null);
+            fail("Should throw NPE");
+        }catch(NullPointerException e){
+        }
 		mockManager.removePropertyChangeListener(null);
 	}
 

Modified: incubator/harmony/enhanced/classlib/trunk/modules/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/LoggerTest.java
URL: http://svn.apache.org/viewvc/incubator/harmony/enhanced/classlib/trunk/modules/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/LoggerTest.java?rev=432552&r1=432551&r2=432552&view=diff
==============================================================================
--- incubator/harmony/enhanced/classlib/trunk/modules/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/LoggerTest.java (original)
+++ incubator/harmony/enhanced/classlib/trunk/modules/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/LoggerTest.java Fri Aug 18 04:13:36 2006
@@ -57,7 +57,7 @@
 	private Logger sharedLogger = null;
 
 	private Locale oldLocale = null;
-
+    
 	/*
 	 * @see TestCase#setUp()
 	 */
@@ -733,11 +733,7 @@
 	 */
 	public void testRemoveHandler_Null() {
 		Logger log = Logger.getLogger("testRemoveHandler_Null");
-		try {
-			log.removeHandler(null);
-			fail("Should throw NullPointerException!");
-		} catch (NullPointerException e) {
-		}
+		log.removeHandler(null);
 		assertEquals(log.getHandlers().length, 0);
 	}