Java Code Examples for java.util.logging.Logger.removeHandler()

The following are Jave code examples for showing how to use removeHandler() of the java.util.logging.Logger class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: incubator-netbeans   File: BaseActionProviderTest.java   Source Code and License Vote up 7 votes
@Test
public void testOverridenGetTargetNames() throws Exception {
    assertNotNull(ap);
    final Logger log = Logger.getLogger(ActionProviderSupport.class.getName());
    final Level origLevel = log.getLevel();
    final MockHandler handler = new MockHandler();
    log.setLevel(Level.FINE);
    log.addHandler(handler);
    try {
        SwingUtilities.invokeAndWait(() -> {
            ap.invokeAction(ActionProvider.COMMAND_CLEAN, Lookup.EMPTY);
        });
        assertEquals("1", handler.props.get("a"));      //NOI18N
        assertEquals("2", handler.props.get("b"));      //NOI18N
    } finally {
        log.setLevel(origLevel);
        log.removeHandler(handler);
    }
}
 
Example 2
Project: incubator-netbeans   File: RepositoryUpdaterTest.java   Source Code and License Vote up 7 votes
@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 3
Project: GitHub   File: WebSocketHttpTest.java   Source Code and License Vote up 6 votes
@Ignore("AsyncCall currently lets runtime exceptions propagate.")
@Test public void throwingOnFailLogs() throws InterruptedException {
  TestLogHandler logs = new TestLogHandler();
  Logger logger = Logger.getLogger(OkHttpClient.class.getName());
  logger.addHandler(logs);

  webServer.enqueue(new MockResponse().setResponseCode(200).setBody("Body"));

  final RuntimeException e = new RuntimeException();
  clientListener.setNextEventDelegate(new WebSocketListener() {
    @Override public void onFailure(WebSocket webSocket, Throwable t, Response response) {
      throw e;
    }
  });

  newWebSocket();

  assertEquals("", logs.take());
  logger.removeHandler(logs);
}
 
Example 4
Project: incubator-netbeans   File: VisibilityChangeTest.java   Source Code and License Vote up 6 votes
@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
Project: incubator-netbeans   File: IndexerOrderingTest.java   Source Code and License Vote up 6 votes
public void testEmbeddingIndexerOrdering() throws InterruptedException {
    assertTrue(GlobalPathRegistry.getDefault().getPaths(SRC_EMB).isEmpty());
    final RepositoryUpdaterTest.TestHandler handler = new RepositoryUpdaterTest.TestHandler();
    final Logger logger = Logger.getLogger(RepositoryUpdater.class.getName()+".tests"); //NOI18N
    logger.setLevel (Level.FINEST);
    logger.addHandler(handler);
    try {
        final ClassPath cp = ClassPathSupport.createClassPath(eroot);
        calls.clear();
        globalPathRegistry_register(SRC_EMB, new ClassPath[]{cp});
        assertTrue (handler.await());
        assertEquals(5, calls.size());
        final Iterator<SourceIndexerFactory> callsIt = calls.iterator();
        for (int i=1; i<=5; i++) {
            assertEquals(
                String.format("EI%d",i),    //NOI18N
                callsIt.next().getIndexerName());
        }
        
    } finally {
        logger.removeHandler(handler);
    }
}
 
Example 6
Project: incubator-netbeans   File: Installer.java   Source Code and License Vote up 6 votes
public final void doClose() {
    Logger log = Logger.getLogger(UI_LOGGER_NAME);
    log.removeHandler(ui);
    uiLogger = null;
    Logger all = Logger.getLogger(""); // NOI18N
    all.removeHandler(handler);
    allLogger = null;
    log = Logger.getLogger(METRICS_LOGGER_NAME);
    log.removeHandler(metrics);
    metricsLogger = null;

    closeLogStream();
    closeLogStreamMetrics();
    synchronized (restored) {
        restored.set(false);
    }
}
 
Example 7
Project: incubator-netbeans   File: WatcherLoggingTest.java   Source Code and License Vote up 6 votes
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 8
Project: incubator-netbeans   File: ScanSeveralProjectsPerfTest.java   Source Code and License Vote up 5 votes
public void testScanProjects() throws Exception {
    File projectsDir = getWorkDir();
    for (String projectName : Utilities.PROJECTS.keySet()) {
        Utilities.projectDownloadAndUnzip(projectName, projectsDir);
    }
    Logger repositoryUpdater = Logger.getLogger(RepositoryUpdater.class.getName());
    repositoryUpdater.setLevel(Level.INFO);
    handler = new ScanningHandler("test projects", 70000, 140000, 1000, 15000);
    repositoryUpdater.addHandler(handler);

    Logger log = Logger.getLogger("org.openide.filesystems.MIMESupport");
    log.setLevel(Level.WARNING);
    Utilities.ReadingHandler readHandler = new Utilities.ReadingHandler();
    log.addHandler(readHandler);

    Utilities.openProjects(projectsDir, Utilities.PROJECTS.keySet().toArray(new String[0]));
    Utilities.waitScanningFinished(projectsDir);
    handler.setType(ScanningHandler.ScanType.UP_TO_DATE);
    Utilities.refreshIndexes();
    Utilities.waitScanningFinished(projectsDir);
    OpenProjects.getDefault().close(OpenProjects.getDefault().getOpenProjects());
    repositoryUpdater.removeHandler(handler);
    // wait for scanning of unowned roots after all projects are closed
    synchronized(this) {
        this.wait(10000);
}
}
 
Example 9
Project: incubator-netbeans   File: FileUtilTest.java   Source Code and License Vote up 5 votes
/** Test recovery of FileUtil.createFolder(FileObject, String) method when
 * other thread created folder in the middle of processing (see #152219).
 */
public void testFolderAlreadyExists152219() {
    final FileObject folder = FileUtil.createMemoryFileSystem().getRoot();
    final String name = "subfolder";
    Handler handler = new Handler() {

        @Override
        public void publish(LogRecord record) {
            if (record.getMessage().equals("createFolder - before create folder if not exists.")) {
                try {
                    folder.createFolder(name);
                } catch (IOException ex) {
                    throw new RuntimeException(ex);
                }
            }
        }

        @Override
        public void flush() {
        }

        @Override
        public void close() throws SecurityException {
        }
    };
    Logger logger = Logger.getLogger(FileUtil.class.getName());
    logger.addHandler(handler);
    logger.setLevel(Level.FINEST);
    try {
        FileUtil.createFolder(folder, name);
    } catch (IOException ioe) {
        fail("FileUtil.createFolder(FileObject, String) should try to refresh folder because other thread can create folder before.");
    } finally {
        logger.removeHandler(handler);
    }
}
 
Example 10
Project: incubator-netbeans   File: TestKit.java   Source Code and License Vote up 5 votes
public static void removeHandlers(Logger log) {
	if (log != null) {
		Handler[] handlers = log.getHandlers();
		for (int i = 0; i < handlers.length; i++) {
			log.removeHandler(handlers[i]);
		}
	}
}
 
Example 11
Project: alog   File: Alog.java   Source Code and License Vote up 5 votes
/**
 * Removes existing handlers from the root logger and installs a
 * PrintStreamLogHandler for System.out.
 */
public static void replaceRootHandler() {
    Logger global = Logger.getLogger("");
    for (Handler handler : global.getHandlers()) {
        global.removeHandler(handler);
    }
    global.addHandler(new PrintStreamLogHandler("Root Logger", System.out));
}
 
Example 12
Project: incubator-netbeans   File: ModuleListTest.java   Source Code and License Vote up 5 votes
public void testConcurrentScanningBinary() throws Exception {
    // now testing scan of binary clusters
    ModuleList.refresh();
    final ModuleList mlref[] = new ModuleList[1];
    Logger logger = Logger.getLogger(ModuleList.class.getName());
    Level origLevel = logger.getLevel();
    ModuleListLogHandler handler = new ModuleListLogHandler();
    assertTrue("NB dest. dir exists: " + destDirF, destDirF.exists());
    try {
        logger.setLevel(Level.ALL);
        logger.addHandler(handler);

        Thread t = new Thread() {

            @Override
            public void run() {
                try {
                    mlref[0] = ModuleList.findOrCreateModuleListFromBinaries(destDirF);
                } catch (IOException ex) {
                    throw new RuntimeException(ex);
                }
            }
        };
        long start = System.currentTimeMillis();
        t.start();
        ModuleList ml = ModuleList.findOrCreateModuleListFromBinaries(destDirF);
        t.join();
        System.out.println("Concurrent scans took " + (System.currentTimeMillis() - start) + "msec.");
        assertNull(handler.error, handler.error);   // error is non-null when duplicate scan detected
        assertNotNull("Module list for dir " + destDirF + " returned null", ml);
        assertNotNull("Module list for dir " + destDirF + " returned null", mlref[0]);
        assertTrue("No clusters scanned.", handler.scannedDirs.size() > 0);
        System.out.println("Total " + handler.scannedDirs.size() + " clusters scanned.");
        // XXX Some more possible concurrent scans could be tested, not that easy to set up,
        // e.g. ML#findOrCreateModuleListFromSuite, ...FromStandaloneModule, ...
    } finally {
        logger.removeHandler(handler);
        logger.setLevel(origLevel);
    }
}
 
Example 13
Project: incubator-netbeans   File: LinuxNotifier235632Test.java   Source Code and License Vote up 5 votes
/**
 * Test of nextEvent method, of class LinuxNotifier.
 *
 * @throws java.lang.Exception
 */
public void testNextEvent() throws Exception {

    if (Utilities.getOperatingSystem() != Utilities.OS_LINUX) {
        System.out.println("Skipping linux-only test: " + getName());
        return;
    }

    prepareFiles();

    final AtomicBoolean folder2refreshed = new AtomicBoolean(false);
    Logger log = Logger.getLogger(FolderObj.class.getName());

    Handler h = createHandler(folder2refreshed);
    log.addHandler(h);
    try {
        FileChangeListener l = new FileChangeAdapter();
        FileUtil.addFileChangeListener(l, folder1text1Txt);
        // This causes an IN_IGNORED native event.
        FileUtil.removeFileChangeListener(l, folder1text1Txt);
        // Native listeners may need some time.
        Thread.sleep(2000);
    } finally {
        log.removeHandler(h);
    }
    assertFalse("Folder folder2 should not be refreshed.",
            folder2refreshed.get());
}
 
Example 14
Project: incubator-netbeans   File: TestKit.java   Source Code and License Vote up 5 votes
public static void removeHandlers(Logger log) {
    if (log != null) {
        Handler[] handlers = log.getHandlers();
        for (int i = 0; i < handlers.length; i++) {
            log.removeHandler(handlers[i]);
        }
    }
}
 
Example 15
Project: incubator-netbeans   File: VisibilityChangeTest.java   Source Code and License Vote up 5 votes
/**
 * Tests specific VisibilityChange but outside of the source roots.
 * Change to file (folder) outside of source roots -> no scan.
 */
public void testVisibilityChangeOutsideOfRoot() throws InterruptedException, IOException {

    assertTrue(GlobalPathRegistry.getDefault().getPaths(FOO_SOURCES).isEmpty());
    final RepositoryUpdaterTest.TestHandler handler = new RepositoryUpdaterTest.TestHandler();
    final Logger logger = Logger.getLogger(RepositoryUpdater.class.getName()+".tests"); //NOI18N
    logger.setLevel (Level.FINEST);
    logger.addHandler(handler);
    try {
        globalPathRegistry_register(FOO_SOURCES,new ClassPath[]{cp1});
        assertTrue (handler.await());
        assertEquals(0, handler.getBinaries().size());
        assertEquals(4, handler.getSources().size());
        assertEquals(
            new URI[] {
                src1file1.toURI(),
                src1file2.toURI(),
                src2file1.toURI(),
                src2file2.toURI(),
                src3file1.toURI(),
                src3file2.toURI(),
                src4file1.toURI(),
                src4file2.toURI()
            },
            MimeLookup.getLookup(MimePath.get(FOO_MIME)).lookup(FooIndexerFactory.class).clearIndexedFiles());
        assertEquals(
            new URI[0],
            MimeLookup.getLookup(MimePath.get(FOO_MIME)).lookup(FooIndexerFactory.class).clearRemovedFiles());
        handler.reset();
        Lookup.getDefault().lookup(MockVisibilityQuery.class).hide(outside);
        assertFalse(handler.await(RepositoryUpdaterTest.NEGATIVE_TIME));
        assertNull(handler.getBinaries());
        assertNull(handler.getSources());
    } finally {
        logger.removeHandler(handler);
    }
}
 
Example 16
Project: incubator-netbeans   File: ExternalChangesTest.java   Source Code and License Vote up 5 votes
@RandomlyFails
public void testLogExtCmdChanges () throws Exception {
    waitForInitialScan();
    FileChangeAdapter fca = new FileChangeAdapter();
    workdirFO.addRecursiveListener(fca);
    final File toAdd = new File(modifiedFile.getParentFile(), "toAdd");
    File toDelete = new File(modifiedFile.getParentFile(), "toDelete");
    toDelete.createNewFile();
    FileUtil.refreshFor(repositoryLocation);
    Thread.sleep(11000); // some time for initial scans to finish and event logger to settle down
    File gitFolder = new File(repositoryLocation, ".git");
    final File lockFile = new File(gitFolder, "index.lock");
    
    Logger.getLogger(FilesystemInterceptor.class.getName()).setLevel(Level.ALL);
    ConsoleHandler ch = new ConsoleHandler();
    ch.setLevel(Level.ALL);
    Logger.getLogger(FilesystemInterceptor.class.getName()).addHandler(ch);
    
    assertTrue(lockFile.createNewFile());
    FileUtil.refreshFor(repositoryLocation);
    pause();
    Thread.sleep(1100);
    assertTrue(lockFile.delete());
    FileUtil.refreshFor(repositoryLocation);
    Thread.sleep(1100);
    
    Logger GESTURES_LOG = Logger.getLogger("org.netbeans.ui.vcs");
    ExternalCommandUsageHandler h = new ExternalCommandUsageHandler();
    GESTURES_LOG.addHandler(h);
    assertTrue(lockFile.createNewFile());
    FileUtil.refreshFor(repositoryLocation);
    // modification
    write(modifiedFile, "testExternalCommandLoggedChanges");
    // delete
    toDelete.delete();
    // create
    toAdd.createNewFile();
    FileUtil.refreshFor(repositoryLocation);
    pause();
    Thread.sleep(1100);
    assertTrue(lockFile.delete());
    FileUtil.refreshFor(repositoryLocation);
    
    h.waitForEvent();
    assertNotNull(h.event);
    assertEquals(1, h.numberOfEvents);
    assertTrue(h.event.time > 0);
    assertEquals("GIT", h.event.vcs);
    assertEquals("UNKNOWN", h.event.command);
    assertTrue(h.event.external);
    assertEquals(Long.valueOf(3), h.event.modifications);
    GESTURES_LOG.removeHandler(h);
    workdirFO.removeRecursiveListener(fca);
    Logger.getLogger(FilesystemInterceptor.class.getName()).removeHandler(ch);
}
 
Example 17
Project: dsp4e   File: LogMessageAccumulator.java   Source Code and License Vote up 5 votes
public void unregister() {
	for (Logger logger : registeredLoggers) {
		logger.removeHandler(this);
		logger.setUseParentHandlers(true);
	}
	registeredLoggers.clear();
}
 
Example 18
Project: incubator-netbeans   File: VisibilityChangeTest.java   Source Code and License Vote up 4 votes
/**
 * Tests unspecific VisibilityChange.
 * No specific file (folder) given -> everything should be refreshed.
 */
public void testGlobalVisibilityChange() throws InterruptedException, IOException {

    assertTrue(GlobalPathRegistry.getDefault().getPaths(FOO_SOURCES).isEmpty());
    final RepositoryUpdaterTest.TestHandler handler = new RepositoryUpdaterTest.TestHandler();
    final Logger logger = Logger.getLogger(RepositoryUpdater.class.getName()+".tests"); //NOI18N
    logger.setLevel (Level.FINEST);
    logger.addHandler(handler);
    try {
        globalPathRegistry_register(FOO_SOURCES,new ClassPath[]{cp1});
        assertTrue (handler.await());
        assertEquals(0, handler.getBinaries().size());
        assertEquals(4, handler.getSources().size());
        assertEquals(
            new URI[] {
                src1file1.toURI(),
                src1file2.toURI(),
                src2file1.toURI(),
                src2file2.toURI(),
                src3file1.toURI(),
                src3file2.toURI(),
                src4file1.toURI(),
                src4file2.toURI()
            },
            MimeLookup.getLookup(MimePath.get(FOO_MIME)).lookup(FooIndexerFactory.class).clearIndexedFiles());
        assertEquals(
            new URI[0],
            MimeLookup.getLookup(MimePath.get(FOO_MIME)).lookup(FooIndexerFactory.class).clearRemovedFiles());
        handler.reset();
        Lookup.getDefault().lookup(MockVisibilityQuery.class).globalChange();
        assertTrue (handler.await());
        assertEquals(0, handler.getBinaries().size());
        assertEquals(4, handler.getSources().size());
        assertEquals(
            new URI[0],
            MimeLookup.getLookup(MimePath.get(FOO_MIME)).lookup(FooIndexerFactory.class).clearIndexedFiles());
        assertEquals(
            new URI[0],
            MimeLookup.getLookup(MimePath.get(FOO_MIME)).lookup(FooIndexerFactory.class).clearRemovedFiles());
    } finally {
        logger.removeHandler(handler);
    }
}
 
Example 19
Project: incubator-netbeans   File: FileListWorkOrderingTest.java   Source Code and License Vote up 4 votes
/**
 * Tests that consequent file list works on single root are collapsed into single one.
 * Runs special work at start which in execution schedules 2 FLWs -> just 1 FLW should
 * be executed.
 */
public void testFLWOnSingleRootAreAbsorbed() throws InterruptedException, IOException {

    assertTrue(GlobalPathRegistry.getDefault().getPaths(FOO_SOURCES).isEmpty());
    final RepositoryUpdaterTest.TestHandler handler = new RepositoryUpdaterTest.TestHandler();
    final Logger logger = Logger.getLogger(RepositoryUpdater.class.getName()+".tests"); //NOI18N
    logger.setLevel (Level.FINEST);
    logger.addHandler(handler);
    try {
        globalPathRegistry_register(FOO_SOURCES,new ClassPath[]{cp1});
        assertTrue (handler.await());
        assertEquals(0, handler.getBinaries().size());
        assertEquals(2, handler.getSources().size());

        handler.reset(RepositoryUpdaterTest.TestHandler.Type.FILELIST);
        MimeLookup.getLookup(MimePath.get(FOO_MIME)).
                lookup(FooIndexerFactory.class).
                reset();
        RepositoryUpdater.getDefault().runAsWork(
            new Runnable() {
               @Override
               public void run() {
                   //First schedule of refresh for src1
                   IndexingManager.getDefault().refreshIndex(
                      src1.toURL(),
                      Collections.<URL>emptyList(),
                      false);
                   //Second schedule of refresh for src1
                   IndexingManager.getDefault().refreshIndex(
                      src1.toURL(),
                      Collections.<URL>emptyList(),
                      false);
               }
            });              
        assertTrue (handler.await());
        assertTrue (awaitRUSilence());
        assertEquals(1, MimeLookup.getLookup(MimePath.get(FOO_MIME)).
                        lookup(FooIndexerFactory.class).
                        getIndexingCount());
    } finally {
        logger.removeHandler(handler);
    }
}
 
Example 20
Project: incubator-netbeans   File: ModuleOraculumTest.java   Source Code and License Vote up 4 votes
public void testModuleNameCache_ModuleInfoUpdated() 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 = JavacParser.createJavacTask(
                javaFile1,
                root1,
                cpInfo,
                parser,
                null,
                false);
        assertEquals("Test", Options.instance(impl.getContext()).get("-XD-Xmodule:"));    //NOI18N
        List<? extends String> names = h.getModuleNames();
        assertEquals(1, names.size());
        assertEquals("Test", names.get(0)); //NOI18N
        h.reset();
        createModule(root1, "TestUpdated");
        impl = JavacParser.createJavacTask(
                javaFile1,
                root1,
                cpInfo,
                parser,
                null,
                false);
        assertEquals("TestUpdated", Options.instance(impl.getContext()).get("-XD-Xmodule:"));    //NOI18N
        names = h.getModuleNames();
        assertEquals(1, names.size());
        assertEquals("TestUpdated", names.get(0)); //NOI18N
        h.reset();
        impl = JavacParser.createJavacTask(
                javaFile1,
                root1,
                cpInfo,
                parser,
                null,
                false);
        assertEquals("TestUpdated", Options.instance(impl.getContext()).get("-XD-Xmodule:"));    //NOI18N
        names = h.getModuleNames();
        assertEquals(0, names.size());
    } finally {
        l.removeHandler(h);
        l.setLevel(origLogLevel);
    }
}