Java Code Examples for java.util.logging.Logger#addHandler()

The following examples show how to use java.util.logging.Logger#addHandler() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: RepositoryUpdaterTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
protected void tearDown() throws Exception {
    final TestHandler handler = new TestHandler();
    final Logger logger = Logger.getLogger(RepositoryUpdater.class.getName()+".tests");
    try {
        logger.setLevel (Level.FINEST);
        logger.addHandler(handler);
        for(String id : registeredClasspaths.keySet()) {
            final Map<ClassPath,Void> classpaths = registeredClasspaths.get(id);
            GlobalPathRegistry.getDefault().unregister(id, classpaths.keySet().toArray(new ClassPath[classpaths.size()]));
        }
        handler.await();
    } finally {
        logger.removeHandler(handler);
    }
    super.tearDown();
}
 
Example 2
Source File: RepositoryUpdaterTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * Test that unknown source roots are registered in the scannedRoots2Dependencies with EMPTY_DEPS
 * and when the unknown root registers it's changed to regular dependencies.
 * When the root is unregistered it's removed from scannedRoots2Dependencies
 *
 * The test was also extended to test Issue 196985. Unknown root which becomes known was lost
 * @throws Exception
 */
public void testIndexManagerRefreshIndexListensOnChanges_And_Issue196985() throws Exception {
    final File _wd = this.getWorkDir();
    final FileObject wd = FileUtil.toFileObject(_wd);
    final FileObject refreshedRoot = wd.createFolder("refreshedRoot");
    final RepositoryUpdater ru = RepositoryUpdater.getDefault();
    assertNotNull(refreshedRoot);
    assertFalse (ru.getScannedRoots2Dependencies().containsKey(refreshedRoot.toURL()));
    IndexingManager.getDefault().refreshIndexAndWait(refreshedRoot.toURL(), Collections.<URL>emptyList());
    assertSame(RepositoryUpdater.UNKNOWN_ROOT, ru.getScannedRoots2Dependencies().get(refreshedRoot.toURL()));
    //Register the root => EMPTY_DEPS changes to regular deps
    final TestHandler handler = new TestHandler();
    final Logger logger = Logger.getLogger(RepositoryUpdater.class.getName()+".tests");
    logger.setLevel (Level.FINEST);
    logger.addHandler(handler);
    final ClassPath cp = ClassPathSupport.createClassPath(refreshedRoot);
    handler.reset(RepositoryUpdaterTest.TestHandler.Type.ROOTS_WORK_FINISHED);
    globalPathRegistry_register(SOURCES, new ClassPath[]{cp});
    handler.await();
    assertNotNull(ru.getScannedRoots2Dependencies().get(refreshedRoot.toURL()));
    assertNotSame(RepositoryUpdater.UNKNOWN_ROOT, ru.getScannedRoots2Dependencies().get(refreshedRoot.toURL()));
    handler.reset(RepositoryUpdaterTest.TestHandler.Type.ROOTS_WORK_FINISHED);
    globalPathRegistry_unregister(SOURCES, new ClassPath[]{cp});
    handler.await();
    assertFalse(ru.getScannedRoots2Dependencies().containsKey(refreshedRoot.toURL()));
}
 
Example 3
Source File: ValueGroupTestCase.java    From vespa with Apache License 2.0 6 votes vote down vote up
@Test
public void testBasic() {
    Logger logger = Logger.getLogger(ValueGroup.class.getName());
    boolean initUseParentHandlers = logger.getUseParentHandlers();
    Handler logChecker = new ValueGroupHandler();
    logger.setUseParentHandlers(false);
    final MockStatistics manager = new MockStatistics();
    ValueGroup v = new ValueGroup("test", manager);
    v.put("a", 50.0);
    v.put("b", 40.0);
    v.put("a", -50.0);
    assertTrue("Last value inserted to a was -50",
               -50.0 == v.getValue("a").get());
    assertTrue("Last value inserted to b was 40.",
               40.0 == v.getValue("b").get());
    assertTrue("c has not been used yet",
               0.0 == v.getValue("c").get());
    logger.addHandler(logChecker);
    v.run();
    assertFalse("The logging handler did not really run.", gotRecord == false);
    assertEquals(1, manager.registerCount);
    // cleanup:
    logger.removeHandler(logChecker);
    logger.setUseParentHandlers(initUseParentHandlers);
}
 
Example 4
Source File: IndexerOrderingTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
protected void tearDown() throws Exception {
    final RepositoryUpdaterTest.TestHandler handler = new RepositoryUpdaterTest.TestHandler();
    final Logger logger = Logger.getLogger(RepositoryUpdater.class.getName()+".tests"); //NOI18N
    try {
        logger.setLevel (Level.FINEST);
        logger.addHandler(handler);
        for(String id : registeredClasspaths.keySet()) {
            final Map<ClassPath,Void> classpaths = registeredClasspaths.get(id);
            GlobalPathRegistry.getDefault().unregister(id, classpaths.keySet().toArray(new ClassPath[classpaths.size()]));
        }
        handler.await();
    } finally {
        logger.removeHandler(handler);
    }
    super.tearDown();
}
 
Example 5
Source File: WatcherLoggingTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testLimitAddWatchLogs() throws IOException {
    FileObject root = FileUtil.toFileObject(getWorkDir());
    int total = 100;

    Logger log = Logger.getLogger(Watcher.class.getName());
    Log.enable(log.getName(), Level.FINEST);
    LogCountHandler h = new LogCountHandler();

    log.addHandler(h);
    try {
        for (int i = 0; i < total; i++) {
            root.addFileChangeListener(listener);
        }
    } finally {
        log.removeHandler(h);
    }

    assertEquals("2 warnings", 2, h.warning);
    assertEquals("10 infos", 10, h.info);
    assertEquals("The rest messages are of fine level", 88, h.fine);
}
 
Example 6
Source File: ProfilerTest.java    From copybara with Apache License 2.0 6 votes vote down vote up
@Test
public void testListenerLogging() {
  // Keep a strong reference to the Logger we use to capture log records for the duration of the
  // test to avoid any potential race conditions with the weak referencing used by the JDK
  //
  // TODO: This could be migrated to use the package level logger name, which would be less
  // fragile against code being moved around.
  Logger loggerUnderTest = Logger.getLogger(LogProfilerListener.class.getCanonicalName());

  TestLogHandler assertingHandler = new TestLogHandler();
  assertingHandler.setLevel(Level.FINE);
  loggerUnderTest.addHandler(assertingHandler);

  profiler = new Profiler(ticker);
  profiler.init(ImmutableList.of(new LogProfilerListener()));
  try (ProfilerTask ignore = profiler.start("testListenerLogging")) {
    // do something
  }
  LogRecord record = assertingHandler.getStoredLogRecords().get(0);
  assertThat(record.getMessage()).contains("testListenerLogging");
  assertThat(record.getSourceClassName()).contains(this.getClass().getName());

  loggerUnderTest.removeHandler(assertingHandler);
}
 
Example 7
Source File: ExceptionsTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testLogLevel() {
    Exception e = new IOException("Help");
    
    Exception result = Exceptions.attachSeverity(e, Level.FINE);
    assertSame(e, result);

    class H extends Handler {
        int cnt;
        
        @Override
        public void publish(LogRecord record) {
            assertEquals("Fine is the level", Level.FINE, record.getLevel());
            cnt++;
        }

        @Override
        public void flush() {
        }

        @Override
        public void close() throws SecurityException {
        }
        
    }
    
    H h = new H();
    h.setLevel(Level.ALL);
    Logger L = Logger.getLogger("");
    L.setLevel(Level.ALL);
    L.addHandler(h);
    
    Exceptions.printStackTrace(e);
    L.removeHandler(h);
    assertEquals("Called once", 1, h.cnt);
}
 
Example 8
Source File: LoggingConfigurer.java    From scriptella-etl with Apache License 2.0 5 votes vote down vote up
/**
 * Configures logging messages to use specified handler
 * @param handler to use.
 */
public static void configure(Handler handler) {
    final Logger l = getScriptellaLogger();
    l.setLevel(handler.getLevel());
    l.setUseParentHandlers(false);
    l.addHandler(handler);
}
 
Example 9
Source File: HintsTests.java    From netbeans with Apache License 2.0 5 votes vote down vote up
protected void waitHintsShown(FileObject fileToTest, int size) {
    final int delay = 1000;
    int repeat = 20;
    final Object lock = new Object();
    Runnable posted = new Runnable() {

        public void run() {
            synchronized (lock) {
                lock.notifyAll();
            }
        }
    };
    RequestProcessor RP = new RequestProcessor("TEST REQUEST PROCESSOR");
    final RequestProcessor.Task task = RP.create(posted);
    HintsHandler handl = new HintsHandler(delay, task);
    Logger logger = Logger.getLogger(AnnotationHolder.class.getName());
    logger.setLevel(Level.FINE);
    try {
        do {
            synchronized (lock) {
                task.schedule(delay);
                logger.addHandler(handl);
                lock.wait(repeat * delay);
            }
        } while ((repeat-- > 0) && (getFixes(fileToTest).size() < size));
    } catch (InterruptedException intExc) {
        throw new JemmyException("REFRESH DID NOT FINISHED IN " + repeat * delay + " SECONDS", intExc);
    } finally {
        logger.removeHandler(handl);
    }
}
 
Example 10
Source File: LogWrapper.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
private static void addDefaultConsoleHandler(Logger logger, String errorMessage, String logFilePath) {
  ConsoleHandler consoleHandler = new ConsoleHandler();
  consoleHandler.setFormatter(new GemFireFormatter());
  logger.addHandler(consoleHandler);

  System.err.println("ERROR: Could not log to file: " + logFilePath + ". Reason: " + errorMessage);
  System.err.println("Logs will be written on Console.");
  try {
    Thread.sleep(3000); //sleep for 3 secs for the message to appear
  } catch (InterruptedException ignore) {}
}
 
Example 11
Source File: Log.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public void close() {
    Logger l = this.logger;
    if (getLevel() != Level.OFF && l != null) {
        l.addHandler(this);
    }
}
 
Example 12
Source File: SubProtocol.java    From SubServers-2 with Apache License 2.0 5 votes vote down vote up
private Logger getLogger(int channel) {
    Logger log = Logger.getAnonymousLogger();
    log.setUseParentHandlers(false);
    log.addHandler(new Handler() {
        private org.slf4j.Logger log = LoggerFactory.getLogger("SubData" + ((channel != 0)? "/Sub-"+channel:""));
        private boolean open = true;

        @Override
        public void publish(LogRecord record) {
            if (open) {
                if (record.getLevel().intValue() == OFF.intValue()) {
                    // do nothing
                } else if (record.getLevel().intValue() == FINE.intValue() || record.getLevel().intValue() == FINER.intValue() || record.getLevel().intValue() == FINEST.intValue()) {
                    log.debug(record.getMessage());
                } else if (record.getLevel().intValue() == ALL.intValue() || record.getLevel().intValue() == CONFIG.intValue() || record.getLevel().intValue() == INFO.intValue()) {
                    log.info(record.getMessage());
                } else if (record.getLevel().intValue() == WARNING.intValue()) {
                    log.warn(record.getMessage());
                } else if (record.getLevel().intValue() == SEVERE.intValue()) {
                    log.error(record.getMessage());
                }
            }
        }

        @Override
        public void flush() {

        }

        @Override
        public void close() throws SecurityException {
            open = false;
        }
    });

    return log;
}
 
Example 13
Source File: ContextTest.java    From grpc-nebula-java with Apache License 2.0 5 votes vote down vote up
@Test
public void errorWhenAncestryLengthLong() {
  final AtomicReference<LogRecord> logRef = new AtomicReference<LogRecord>();
  Handler handler = new Handler() {
    @Override
    public void publish(LogRecord record) {
      logRef.set(record);
    }

    @Override
    public void flush() {
    }

    @Override
    public void close() throws SecurityException {
    }
  };
  Logger logger = Logger.getLogger(Context.class.getName());
  try {
    logger.addHandler(handler);
    Context ctx = Context.current();
    for (int i = 0; i < Context.CONTEXT_DEPTH_WARN_THRESH ; i++) {
      assertNull(logRef.get());
      ctx = ctx.fork();
    }
    ctx = ctx.fork();
    assertNotNull(logRef.get());
    assertNotNull(logRef.get().getThrown());
    assertEquals(Level.SEVERE, logRef.get().getLevel());
  } finally {
    logger.removeHandler(handler);
  }
}
 
Example 14
Source File: FailOverDirectExecutionControlTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@BeforeMethod
@Override
public void setUp() {
    Logger logger = Logger.getLogger("jdk.jshell.execution");
    logger.setLevel(Level.ALL);
    hndlr = new LogTestHandler();
    logger.addHandler(hndlr);
    logged = new HashMap<>();
    Compiler compiler = new Compiler();
    Path modDir = Paths.get("mod");
    compiler.compile(modDir,
            "package my.provide; import java.util.Map;\n" +
            "import jdk.jshell.spi.ExecutionControl;\n" +
            "import jdk.jshell.spi.ExecutionControlProvider;\n" +
            "import jdk.jshell.spi.ExecutionEnv;\n" +
            "public class AlwaysFailingProvider implements ExecutionControlProvider {\n" +
            "    @Override\n" +
            "    public String name() {\n" +
            "        return \"alwaysFailing\";\n" +
            "    }\n" +
            "    @Override\n" +
            "    public ExecutionControl generate(ExecutionEnv env, Map<String, String> parameters) throws Throwable {\n" +
            "        throw new UnsupportedOperationException(\"This operation intentionally broken.\");\n" +
            "    }\n" +
            "}\n",
            "module my.provide {\n" +
            "    requires transitive jdk.jshell;\n" +
            "    provides jdk.jshell.spi.ExecutionControlProvider\n" +
            "        with my.provide.AlwaysFailingProvider;\n" +
            " }");
    Path modPath = compiler.getPath(modDir);
    ccl = createAndRunFromModule("my.provide", modPath);

    provider = new FailOverExecutionControlProvider();
    Map<String, String> pm = provider.defaultParameters();
    pm.put("0", "alwaysFailing");
    pm.put("1", "alwaysFailing");
    pm.put("2", "jdi");
    setUp(builder -> builder.executionEngine(provider, pm));
}
 
Example 15
Source File: ModuleOraculumTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public void testModuleNameCache_ModuleInfoDeleted() throws IOException {
    final Logger l = Logger.getLogger(ModuleOraculum.class.getName());
    final Level origLogLevel = l.getLevel();
    final H h = new H();
    l.setLevel(Level.FINE);
    l.addHandler(h);
    try {
        final ClasspathInfo cpInfo = new ClasspathInfo.Builder(ClassPath.EMPTY).build();
        final JavacParser parser = new JavacParser(Collections.emptyList(), true);
        JavacTaskImpl impl = createJavacTask(
                javaFile1,
                root1,
                cpInfo,
                parser,
                null,
                false);
        assertPatchModules(impl, "Test");
        List<? extends String> names = h.getModuleNames();
        assertEquals(1, names.size());
        assertEquals("Test", names.get(0)); //NOI18N
        h.reset();
        moduleFile1.delete();
        impl = createJavacTask(
                javaFile1,
                root1,
                cpInfo,
                parser,
                null,
                false);
        assertPatchModules(impl);
        names = h.getModuleNames();
        assertEquals(1, names.size());
        assertEquals(null, names.get(0));
        h.reset();
        impl = createJavacTask(
                javaFile1,
                root1,
                cpInfo,
                parser,
                null,
                false);
        assertPatchModules(impl);
        names = h.getModuleNames();
        assertEquals(0, names.size());
    } finally {
        l.removeHandler(h);
        l.setLevel(origLogLevel);
    }
}
 
Example 16
Source File: RepositoryUpdaterTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public void testPeerRootsCalculation() throws Exception {
    //Prepare
    final TestHandler handler = new TestHandler();
    final Logger logger = Logger.getLogger(RepositoryUpdater.class.getName()+".tests");
    logger.setLevel (Level.FINEST);
    logger.addHandler(handler);
    ClassPathProviderImpl.reset();

    //Register src path {srcRoot1, srcRootWithFiles1}
    handler.reset(TestHandler.Type.ROOTS_WORK_FINISHED);
    final MutableClassPathImplementation mcpi = new MutableClassPathImplementation ();
    mcpi.addResource(this.srcRoot1);
    mcpi.addResource(this.srcRootWithFiles1);
    final ClassPath cp = ClassPathFactory.createClassPath(mcpi);
    ClassPathProviderImpl.register(srcRoot1, SOURCES, cp);
    ClassPathProviderImpl.register(srcRoot2, SOURCES, cp);
    ClassPathProviderImpl.register(srcRootWithFiles1, SOURCES, cp);
    globalPathRegistry_register(SOURCES,new ClassPath[]{cp});
    assertTrue (handler.await());
    Map<URL,List<URL>> peersMap = IndexingController.getDefault().getRootPeers();
    assertEquals(2, peersMap.size());
    List<URL> peers = peersMap.get(srcRoot1.toURL());
    assertEquals(Collections.singletonList(srcRootWithFiles1.toURL()), peers);
    peers = peersMap.get(srcRootWithFiles1.toURL());
    assertEquals(Collections.singletonList(srcRoot1.toURL()), peers);

    //Remove srcRootWithFiles1 from src path
    handler.reset(TestHandler.Type.ROOTS_WORK_FINISHED);
    mcpi.removeResource(this.srcRootWithFiles1);
    assertTrue (handler.await());
    peersMap = IndexingController.getDefault().getRootPeers();
    assertEquals(1, peersMap.size());
    peers = peersMap.get(srcRoot1.toURL());
    assertEquals(Collections.<URL>emptyList(), peers);

    //Readd the srcRootWithFiles1 to src path
    handler.reset(TestHandler.Type.ROOTS_WORK_FINISHED);
    mcpi.addResource(this.srcRootWithFiles1);
    assertTrue (handler.await());
    peersMap = IndexingController.getDefault().getRootPeers();
    assertEquals(2, peersMap.size());
    peers = peersMap.get(srcRoot1.toURL());
    assertEquals(Collections.singletonList(srcRootWithFiles1.toURL()), peers);
    peers = peersMap.get(srcRootWithFiles1.toURL());
    assertEquals(Collections.singletonList(srcRoot1.toURL()), peers);

    //Add srcRoot2 to src path
    handler.reset(TestHandler.Type.ROOTS_WORK_FINISHED);
    mcpi.addResource(this.srcRoot2);
    assertTrue (handler.await());
    peersMap = IndexingController.getDefault().getRootPeers();
    assertEquals(3, peersMap.size());
    List<URL> returnedPeers = new ArrayList<> (peersMap.get(srcRoot1.toURL()));
    Collections.sort(returnedPeers, new URLComparator());
    List<URL> expectedPeers = new ArrayList<URL> () {{add(srcRootWithFiles1.toURL()); add(srcRoot2.toURL());}};
    Collections.sort(expectedPeers, new URLComparator());
    assertEquals(expectedPeers, returnedPeers);
    returnedPeers = new ArrayList<> (peersMap.get(srcRoot2.toURL()));
    Collections.sort(returnedPeers, new URLComparator());
    expectedPeers = new ArrayList<URL> () {{add(srcRootWithFiles1.toURL()); add(srcRoot1.toURL());}};
    Collections.sort(expectedPeers, new URLComparator());
    assertEquals(expectedPeers, returnedPeers);
    returnedPeers = new ArrayList<> (peersMap.get(srcRootWithFiles1.toURL()));
    Collections.sort(returnedPeers, new URLComparator());
    expectedPeers = new ArrayList<URL> () {{add(srcRoot1.toURL()); add(srcRoot2.toURL());}};
    Collections.sort(expectedPeers, new URLComparator());
    assertEquals(expectedPeers, returnedPeers);

    //Remove srcRoot2 from src path
    handler.reset(TestHandler.Type.ROOTS_WORK_FINISHED);
    mcpi.removeResource(this.srcRoot2);
    assertTrue (handler.await());
    peersMap = IndexingController.getDefault().getRootPeers();
    assertEquals(2, peersMap.size());
    peers = peersMap.get(srcRoot1.toURL());
    assertEquals(Collections.singletonList(srcRootWithFiles1.toURL()), peers);
    peers = peersMap.get(srcRootWithFiles1.toURL());
    assertEquals(Collections.singletonList(srcRoot1.toURL()), peers);

    //Remove srcRootWithFiles1
    handler.reset(TestHandler.Type.ROOTS_WORK_FINISHED);
    mcpi.removeResource(this.srcRootWithFiles1);
    assertTrue (handler.await());
    peersMap = IndexingController.getDefault().getRootPeers();
    assertEquals(1, peersMap.size());
    peers = peersMap.get(srcRoot1.toURL());
    assertEquals(Collections.<URL>emptyList(), peers);

}
 
Example 17
Source File: EvaluatorTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public void testPropertiesThatTriggerModuleListScan169040() throws Exception {
    ModuleList.refresh();   // disable cache
    Logger logger = Logger.getLogger(ModuleList.class.getName());
    Level origLevel = logger.getLevel();
    final ModuleListLogHandler handler = new ModuleListLogHandler();
    try {
        logger.setLevel(Level.ALL);
        logger.addHandler(handler);

        long start = System.currentTimeMillis();
        PropertyEvaluator eval = javaProjectProject.evaluator();
        assertEquals("No modules scanned yet", 0, handler.scannedDirs.size());
        String js = eval.getProperty("javac.source");      // does not scan ML
        assertTrue("Valid javac.source value", js != null && !js.isEmpty() && !js.equals("javac.source"));
        assertEquals("No modules scanned yet", 0, handler.scannedDirs.size());
        /* No longer calculated due to #172203 optimization:
        String coreStartupDir = eval.getProperty("core.startup.dir");   // does not scan ML after rev #797729b2749e
        assertTrue("Correct core.startup.dir value", Pattern.matches(".*platform[\\d]*$", coreStartupDir));
         */
        assertEquals("No modules scanned yet", 0, handler.scannedDirs.size());
        String cluster = eval.getProperty("cluster");   // still should not scan ML after fix of #169040
        assertEquals("No modules scanned yet", 0, handler.scannedDirs.size());
        assertTrue("java.project in java cluster", cluster.endsWith(TestBase.CLUSTER_JAVA));
        assertTrue("Absolute cluster dir", (new File(cluster)).isAbsolute());
        assertTrue("Existing cluster dir", (new File(cluster)).isDirectory());
        assertNotNull("Normalized cluster dir path", FileUtil.toFileObject(new File(cluster)));
        String testDir = eval.getProperty("test.unit.src.dir");
        assertEquals("No modules scanned yet", 0, handler.scannedDirs.size());
        assertTrue("Existing test src dir", PropertyUtils.resolveFile(javaProjectProject.getProjectDirectoryFile(), testDir).isDirectory());
        String mf = eval.getProperty("manifest.mf");
        assertEquals("No modules scanned yet", 0, handler.scannedDirs.size());
        
        String runCP = eval.getProperty("module.classpath");    // scans ML (or at least transitive deps)
        assertTrue("Some modules scanned", handler.scannedDirs.size() > 0);
        System.out.println("Synchronous scan, " + handler.scannedDirs.size() + " modules scanned.");

        System.out.println("Scan took " + (System.currentTimeMillis() - start) + " msec.");
    } finally {
        logger.removeHandler(handler);
        logger.setLevel(origLevel);
    }
}
 
Example 18
Source File: FolderListTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
/**
 * Test for bug 240388.
 *
 * @throws java.io.IOException
 */
public void testComparatorTaskCalledOnlyOnce() throws IOException {

    Logger err = Logger.getLogger("org.openide.loaders.FolderList");
    Log.enable(err.getName(), Level.FINE);
    final int[] comparisons = new int[1];
    final Semaphore canSort = new Semaphore(0);

    Handler h = new Handler() {

        @Override
        public void publish(LogRecord record) {
            String message = record.getMessage();
            if (message != null) {
                if (message.equals("changeComparator on {0}: previous")) {
                    try {
                        canSort.acquire();
                    } catch (InterruptedException ex) {
                        Exceptions.printStackTrace(ex);
                    }
                } else if (message.equals("changeComparator: get new")) {
                    comparisons[0]++;
                }
            }
        }

        @Override
        public void flush() {
        }

        @Override
        public void close() throws SecurityException {
        }
    };

    list.computeChildrenList(new L()).waitFinished();
    err.addHandler(h);
    try {
        a.setAttribute("position", 300);
        b.setAttribute("position", 200);
        c.setAttribute("position", 100);

        canSort.release(99); //Postpone sorting until all positions are set.

        L listener = new L();
        RequestProcessor.Task t = list.computeChildrenList(listener);
        t.waitFinished();
    } finally {
        err.removeHandler(h);
    }

    assertEquals("Comparator task should be called only once.", 1,
            comparisons[0]);
}
 
Example 19
Source File: FileHandlerQuerierTest.java    From bazel with Apache License 2.0 4 votes vote down vote up
private Logger getLoggerWithFileHandler(FileHandler handler) {
  Logger logger = Logger.getAnonymousLogger();
  logger.addHandler(handler);
  return logger;
}
 
Example 20
Source File: ClientMainFrame.java    From Open-Lowcode with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * Initiate console log and file log
 * 
 * @throws IOException if anything bad happens creating log giles
 */
public void initiateLog() throws IOException {
	Logger mainlogger = Logger.getLogger("");

	for (int i = 0; i < mainlogger.getHandlers().length; i++) {
		mainlogger.removeHandler(mainlogger.getHandlers()[i]);
	}
	if (!nolog) {
		ConsoleHandler consolehandler = new ConsoleHandler();
		consolehandler.setFormatter(new ConsoleFormatter());
		consolehandler.setLevel(Level.ALL);
		consolefilter = new OpenLowcodeLogFilter(Level.FINER, "Console Filter", consolehandler);
		consolehandler.setFilter(consolefilter);
		mainlogger.addHandler(consolehandler);
		File file = new File("./log/");
		if (!file.exists()) {
			boolean result = file.mkdir();
			if (!result)
				throw new RuntimeException("Trying to create log folder " + file.getPath() + ", does not work");
		}
		System.err.println("log folder = " + file.getAbsolutePath());
		FileHandler logfilehandler = new FileHandler("./log/OLcClient%g.log", 10000000, 1000, true);
		logfilefilter = new OpenLowcodeLogFilter(Level.FINER, "Log File Filter", logfilehandler);
		logfilehandler.setFilter(logfilefilter);

		logfilehandler.setLevel(Level.ALL);
		logfilehandler.setFormatter(new FileFormatter(true));
		mainlogger.addHandler(logfilehandler);

		mainlogger.setUseParentHandlers(false);
		
		Logger rootlogger = Logger.getLogger(Logger.GLOBAL_LOGGER_NAME);
		for (int i = 0; i < rootlogger.getHandlers().length; i++) {
			rootlogger.removeHandler(rootlogger.getHandlers()[i]);
		}
		rootlogger.addHandler(logfilehandler);
		rootlogger.setLevel(Level.ALL);

		rootlogger.addHandler(consolehandler);
		rootlogger.setUseParentHandlers(false);
	}
}