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

The following are Jave code examples for showing how to use setLevel() 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.
+ Save this method
Example 1
Project: googles-monorepo-demo   File: ServiceManagerTest.java   View Source Code Vote up 6 votes
/**
 * Catches a bug where when constructing a service manager failed, later interactions with the
 * service could cause IllegalStateExceptions inside the partially constructed ServiceManager.
 * This ISE wouldn't actually bubble up but would get logged by ExecutionQueue.  This obfuscated
 * the original error (which was not constructing ServiceManager correctly).
 */
public void testPartiallyConstructedManager() {
  Logger logger = Logger.getLogger("global");
  logger.setLevel(Level.FINEST);
  TestLogHandler logHandler = new TestLogHandler();
  logger.addHandler(logHandler);
  NoOpService service = new NoOpService();
  service.startAsync();
  try {
    new ServiceManager(Arrays.asList(service));
    fail();
  } catch (IllegalArgumentException expected) {}
  service.stopAsync();
  // Nothing was logged!
  assertEquals(0, logHandler.getStoredLogRecords().size());
}
 
Example 2
Project: incubator-netbeans   File: RepositoryUpdaterTest.java   View Source Code Vote up 6 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: incubator-netbeans   File: IndexingSupportACIDTest.java   View Source Code Vote up 6 votes
public void testChangesNotVisibleAfterRollBack() 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);

        MimeLookup.getLookup(MimePath.get(FOO_MIME)).lookup(FooIndexerFactory.class).setCancelScanning(true);

        globalPathRegistry_register(FOO_SOURCES,new ClassPath[]{cp1});
        assertTrue (handler.await());
        assertEquals(0, handler.getBinaries().size());
        assertEquals(1, handler.getSources().size());
        assertEquals(this.src1.toURL(), handler.getSources().get(0));
        assertFalse(MimeLookup.getLookup(MimePath.get(FOO_MIME)).lookup(FooIndexerFactory.class).isSuccess());
        QuerySupport qs = QuerySupport.forRoots(FooIndexerFactory.NAME, FooIndexerFactory.VERSION, src1);
        final Collection<? extends IndexResult> res = qs.query("_sn", "", QuerySupport.Kind.PREFIX, (String[]) null);   //NOI18N
        assertEquals(0, res.size());
    }
 
Example 4
Project: incubator-netbeans   File: ConstrainedBinaryIndexerTest.java   View Source Code Vote up 6 votes
MockConstrainedIndexer() {
    h = new Handler() {
        @Override
        public void publish(LogRecord record) {
            if (record.getMessage().equals("RootsWork-finished")) {
                sem.release();
            }
        }
        @Override
        public void flush() {
        }

        @Override
        public void close() throws SecurityException {
        }
    };
    final Logger log = Logger.getLogger(RepositoryUpdater.class.getName() + ".tests"); //NOI18N
    log.setLevel(Level.FINEST);
    log.addHandler(h);
}
 
Example 5
Project: incubator-netbeans   File: VisibilityChangeTest.java   View Source Code 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 6
Project: openjdk-jdk10   File: TestAnonymousLogger.java   View Source Code Vote up 5 votes
public static void main(String[] args) {
    System.setSecurityManager(new SecurityManager());
    Logger anonymous = Logger.getAnonymousLogger();

    final TestHandler handler = new TestHandler();
    final TestFilter filter = new TestFilter();
    final ResourceBundle bundle = ResourceBundle.getBundle(TestBundle.class.getName());
    anonymous.setLevel(Level.FINEST);
    anonymous.addHandler(handler);
    anonymous.setFilter(filter);
    anonymous.setUseParentHandlers(true);
    anonymous.setResourceBundle(bundle);

    if (anonymous.getLevel() != Level.FINEST) {
        throw new RuntimeException("Unexpected level: " + anonymous.getLevel());
    } else {
        System.out.println("Got expected level: " + anonymous.getLevel());
    }
    if (!Arrays.asList(anonymous.getHandlers()).contains(handler)) {
        throw new RuntimeException("Expected handler not found in: "
                + Arrays.asList(anonymous.getHandlers()));
    } else {
        System.out.println("Got expected handler in: " + Arrays.asList(anonymous.getHandlers()));
    }
    if (anonymous.getFilter() != filter) {
        throw new RuntimeException("Unexpected filter: " + anonymous.getFilter());
    } else {
        System.out.println("Got expected filter: " + anonymous.getFilter());
    }
    if (!anonymous.getUseParentHandlers()) {
        throw new RuntimeException("Unexpected flag: " + anonymous.getUseParentHandlers());
    } else {
        System.out.println("Got expected flag: " + anonymous.getUseParentHandlers());
    }
    if (anonymous.getResourceBundle() != bundle) {
        throw new RuntimeException("Unexpected bundle: " + anonymous.getResourceBundle());
    } else {
        System.out.println("Got expected bundle: " + anonymous.getResourceBundle());
    }
    try {
        anonymous.setParent(Logger.getLogger("foo.bar"));
        throw new RuntimeException("Expected SecurityException not raised!");
    } catch (SecurityException x) {
        System.out.println("Got expected exception: " + x);
    }
    if (anonymous.getParent() != Logger.getLogger("")) {
        throw new RuntimeException("Unexpected parent: " + anonymous.getParent());
    } else {
        System.out.println("Got expected parent: " + anonymous.getParent());
    }
}
 
Example 7
Project: tomcat7   File: Tomcat.java   View Source Code Vote up 5 votes
/**
 * Controls if the loggers will be silenced or not.
 * @param silent    <code>true</code> sets the log level to WARN for the
 *                  loggers that log information on Tomcat start up. This
 *                  prevents the usual startup information being logged.
 *                  <code>false</code> sets the log level to the default
 *                  level of INFO.
 */
public void setSilent(boolean silent) {
    this.silent = silent;
    for (String s : silences) {
        Logger logger = Logger.getLogger(s);
        pinnedLoggers.put(s, logger);
        if (silent) {
            logger.setLevel(Level.WARNING);
        } else {
            logger.setLevel(Level.INFO);
        }
    }
}
 
Example 8
Project: incubator-netbeans   File: DefaultClassPathProviderTest.java   View Source Code Vote up 5 votes
public void testJavaPlatformCaching() throws IOException {
    FileObject artefact = getSourceFile (FILE_IN_PACKAGE);
    Lookup.getDefault().lookup(MockSLQ.class).register(this.srcRoot, new SpecificationVersion("9"));  //NOI18N
    assertEquals("9", SourceLevelQuery.getSourceLevel(artefact)); //NOI18N
    ClassPathProvider cpp = new DefaultClassPathProvider ();
    final Logger log = Logger.getLogger(DefaultClassPathProvider.class.getName());
    final H h = new H();
    final Level origLevel = log.getLevel();
    log.setLevel(Level.FINE);
    log.addHandler(h);
    try {
        ClassPath cp = cpp.findClassPath(artefact, JavaClassPathConstants.MODULE_BOOT_PATH);
        assertEquals ("DefaultClassPathProvider returned invalid classpath for MODULE_BOOT_PATH with source level 9",
                j9.getBootstrapLibraries(),
                cp);
        List<Optional<JavaPlatform>> plts = h.getCachedPlatforms();
        assertEquals(1, plts.size());
        assertEquals(j9, plts.get(0).get());
        h.reset();
        artefact = getSourceFile (FILE_IN_PACKAGE);
        cp = cpp.findClassPath(artefact, JavaClassPathConstants.MODULE_BOOT_PATH);
        assertEquals ("DefaultClassPathProvider returned invalid classpath for MODULE_BOOT_PATH with source level 9",
                j9.getBootstrapLibraries(),
                cp);
        plts = h.getCachedPlatforms();
        assertEquals(0, plts.size());
    } finally {
        log.removeHandler(h);
        log.setLevel(origLevel);
    }
}
 
Example 9
Project: incubator-netbeans   File: BaseFileObjectTestHid.java   View Source Code Vote up 5 votes
public void testDeletedFileDoesNotReturnInputStream() throws Exception {
    final FileObject testFo = FileUtil.createData(root,"testfile.data");
    final File testFile = FileUtil.toFile(testFo);
    final Logger LOGGER = Logger.getLogger(FileObj.class.getName());
    final Handler handler = new Handler() {
        @Override
        public void publish(LogRecord record) {
            if ("FileObj.getInputStream_after_is_valid".equals(record.getMessage())) {
                testFile.delete();
            }
        }
        @Override
        public void flush() {
        }
        @Override
        public void close() throws SecurityException {
        }
    };
    final Level originalLevel = LOGGER.getLevel();
    LOGGER.setLevel(Level.FINEST);
    try {
        LOGGER.addHandler(handler);
        try {
            testFo.getInputStream();
            assertTrue("Exception not thrown by deleted file getInputStream()", false);
        } catch (FileNotFoundException e) {
            //pass - expected exception
        } finally {
            LOGGER.removeHandler(handler);
        }
    } finally {
        LOGGER.setLevel(originalLevel);
    }
}
 
Example 10
Project: apache-tomcat-7.0.73-with-comment   File: Tomcat.java   View Source Code Vote up 5 votes
/**
 * Controls if the loggers will be silenced or not.
 * @param silent    <code>true</code> sets the log level to WARN for the
 *                  loggers that log information on Tomcat start up. This
 *                  prevents the usual startup information being logged.
 *                  <code>false</code> sets the log level to the default
 *                  level of INFO.
 */
public void setSilent(boolean silent) {
    this.silent = silent;
    for (String s : silences) {
        Logger logger = Logger.getLogger(s);
        pinnedLoggers.put(s, logger);
        if (silent) {
            logger.setLevel(Level.WARNING);
        } else {
            logger.setLevel(Level.INFO);
        }
    }
}
 
Example 11
Project: incubator-netbeans   File: StampsDifferentPopulateTest.java   View Source Code Vote up 5 votes
@Override
protected void setUp() throws Exception {
    branding = NbBundle.getBranding();
    locale = Locale.getDefault();
    
    clearWorkDir();
    
    install = new File(getWorkDir(), "install");
    platform = new File(install, "platform");
    ide = new File(install, "ide");
    userdir = new File(getWorkDir(), "tmp");
    cache = new File(install, "cache");
    
    System.setProperty("netbeans.home", platform.getPath());
    System.setProperty("netbeans.dirs", ide.getPath());
    System.setProperty("netbeans.user", userdir.getPath());
    
    createModule("org.openide.awt", platform, 50000L);
    createModule("org.openide.nodes", platform, 60000L);
    createModule("org.netbeans.api.languages", ide, 90000L);
    createModule("org.netbeans.modules.logmanagement", userdir, 10000L);
    
    Thread.sleep(100);
    
    createPopulateZip();

    Logger l = Logger.getLogger("org");
    l.setLevel(Level.OFF);
    l.setUseParentHandlers(false);
}
 
Example 12
Project: ysoserial-plus   File: JBoss.java   View Source Code Vote up 5 votes
private static void doRun ( URI u, final Object payloadObject, String username, String password ) {
    ConnectionProvider instance = null;
    ConnectionProviderContextImpl context = null;
    ConnectionHandler ch = null;
    Channel c = null;
    VersionedConnection vc = null;
    try {
        Logger logger = LogManager.getLogManager().getLogger("");
        logger.addHandler(new ConsoleLogHandler());
        logger.setLevel(Level.INFO);
        OptionMap options = OptionMap.builder().set(Options.SSL_ENABLED, u.getScheme().equals("https")).getMap();
        context = new ConnectionProviderContextImpl(options, "endpoint");
        instance = new HttpUpgradeConnectionProviderFactory().createInstance(context, options);
        String host = u.getHost();
        int port = u.getPort() > 0 ? u.getPort() : 9990;
        SocketAddress destination = new InetSocketAddress(host, port);
        ConnectionHandlerFactory chf = getConnection(destination, username, password, context, instance, options);
        ch = chf.createInstance(new ConnectionHandlerContextImpl(context));
        c = getChannel(context, ch, options);
        System.err.println("Connected");
        vc = makeVersionedConnection(c);
        MBeanServerConnection mbc = vc.getMBeanServerConnection(null);
        doExploit(payloadObject, mbc);
        System.err.println("DONE");
    }
    catch ( Throwable e ) {
        e.printStackTrace(System.err);
    }
    finally {
        cleanup(instance, context, ch, c, vc);
    }
}
 
Example 13
Project: incubator-netbeans   File: FileUtilTest.java   View Source Code 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 14
Project: openjdk-jdk10   File: SmokeTest.java   View Source Code Vote up 5 votes
static void initServer() throws Exception {

        Logger logger = Logger.getLogger("com.sun.net.httpserver");
        ConsoleHandler ch = new ConsoleHandler();
        logger.setLevel(Level.SEVERE);
        ch.setLevel(Level.SEVERE);
        logger.addHandler(ch);

        String root = System.getProperty ("test.src")+ "/docs";
        InetSocketAddress addr = new InetSocketAddress (0);
        s1 = HttpServer.create (addr, 0);
        if (s1 instanceof HttpsServer) {
            throw new RuntimeException ("should not be httpsserver");
        }
        s2 = HttpsServer.create (addr, 0);
        HttpHandler h = new FileServerHandler(root);

        HttpContext c1 = s1.createContext("/files", h);
        HttpContext c2 = s2.createContext("/files", h);
        HttpContext c3 = s1.createContext("/echo", new EchoHandler());
        redirectHandler = new RedirectHandler("/redirect");
        redirectHandlerSecure = new RedirectHandler("/redirect");
        HttpContext c4 = s1.createContext("/redirect", redirectHandler);
        HttpContext c41 = s2.createContext("/redirect", redirectHandlerSecure);
        HttpContext c5 = s2.createContext("/echo", new EchoHandler());
        HttpContext c6 = s1.createContext("/keepalive", new KeepAliveHandler());
        redirectErrorHandler = new RedirectErrorHandler("/redirecterror");
        redirectErrorHandlerSecure = new RedirectErrorHandler("/redirecterror");
        HttpContext c7 = s1.createContext("/redirecterror", redirectErrorHandler);
        HttpContext c71 = s2.createContext("/redirecterror", redirectErrorHandlerSecure);
        delayHandler = new DelayHandler();
        HttpContext c8 = s1.createContext("/delay", delayHandler);
        HttpContext c81 = s2.createContext("/delay", delayHandler);

        executor = Executors.newCachedThreadPool();
        s1.setExecutor(executor);
        s2.setExecutor(executor);
        ctx = new SimpleSSLContext().get();
        sslparams = ctx.getSupportedSSLParameters();
        s2.setHttpsConfigurator(new Configurator(ctx));
        s1.start();
        s2.start();

        port = s1.getAddress().getPort();
        System.out.println("HTTP server port = " + port);
        httpsport = s2.getAddress().getPort();
        System.out.println("HTTPS server port = " + httpsport);
        httproot = "http://127.0.0.1:" + port + "/";
        httpsroot = "https://127.0.0.1:" + httpsport + "/";

        proxy = new ProxyServer(0, false);
        proxyPort = proxy.getPort();
        System.out.println("Proxy port = " + proxyPort);
    }
 
Example 15
Project: incubator-netbeans   File: SourcePrefetcherTest.java   View Source Code Vote up 5 votes
public void testDeletedFile() throws Exception {
    CompileTuple ct = files.iterator().next();
    final FileObject fo = URLMapper.findFileObject(ct.indexable.getURL());        
    fo.delete();
    
    JavaIndexerWorker.TEST_DO_PREFETCH = true;
    final LogHandler handler = new LogHandler();
    handler.expect("Using concurrent iterator, {0} workers");    //NOI18N
    final Logger log = Logger.getLogger(JavaIndexerWorker.class.getName());
    log.setLevel(Level.FINE);
    log.addHandler(handler);
    try {
        SourcePrefetcher pf = SourcePrefetcher.create(files, SuspendSupport.NOP);
        assertTrue(handler.isFound());
        final Deque<CompileTuple> got = new ArrayDeque<CompileTuple>(FILE_COUNT);
        while (pf.hasNext()) {
            ct = pf.next();
            try {
                if (ct != null) {
                    assertNotNull(getCache(ct.jfo));
                    got.offer(ct);
                }
            } finally {
                pf.remove();
            }
            if (ct != null) {
                assertNull(getCache(ct.jfo));
            }
        }
        final List<CompileTuple> allButFirst = new LinkedList<CompileTuple>(files);
        allButFirst.remove(0);
        assertCollectionsEqual(allButFirst,got);
    } finally {
        log.removeHandler(handler);
    }
}
 
Example 16
Project: incubator-netbeans   File: FileListWorkOrderingTest.java   View Source Code Vote up 4 votes
/**
 * Tests that consequent file list works on different roots with intermediate delete work on first root
 * are not collapsed.
 * Runs special work at start which in execution schedules FLW(src1), DEL(src1), FLW(src2), FLW(src1) -> 3 FLWs should
 * be executed.
 */
public void testFLWOnMultipleRootsWithIntermediateDelWorkFollowedByFLWNotAbsorbed() 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 schedulte some delete in src2
                   RepositoryUpdater.getDefault().addDeleteJob(
                      src1.toURL(),
                      Collections.<String>emptySet(),
                      LogContext.create(LogContext.EventType.PATH, "Test"));    //NOI18N
                   //Third schedule of refresh for src1
                   IndexingManager.getDefault().refreshIndex(
                      src2.toURL(),
                      Collections.<URL>emptyList(),
                      false);
                   //Fourth schedule of refresh for src1
                   IndexingManager.getDefault().refreshIndex(
                      src1.toURL(),
                      Collections.<URL>emptyList(),
                      false);
               }
            });
        assertTrue (handler.await());
        assertTrue (awaitRUSilence());
        assertEquals(3, MimeLookup.getLookup(MimePath.get(FOO_MIME)).
                        lookup(FooIndexerFactory.class).
                        getIndexingCount());
    } finally {
        logger.removeHandler(handler);
    }
}
 
Example 17
Project: incubator-netbeans   File: RepositoryUpdaterTest.java   View Source Code Vote up 4 votes
@RandomlyFails
public void testBinaryDeletedAdded() throws Exception {
    final TestHandler handler = new TestHandler();
    final Logger logger = Logger.getLogger(RepositoryUpdater.class.getName()+".tests");
    logger.setLevel (Level.FINEST);
    logger.addHandler(handler);

    final FileObject jarFile = FileUtil.toFileObject(getDataDir()).getFileObject("JavaApplication1.jar");
    assertNotNull(jarFile);
    assertTrue(FileUtil.isArchiveFile(jarFile));

    final FileObject wd = FileUtil.toFileObject(getWorkDir());
    final FileObject[] jar2Delete = new FileObject[] {jarFile.copy(wd, "test", "jar")};
    ClassPath cp = ClassPathSupport.createClassPath(new FileObject[] {FileUtil.getArchiveRoot(jar2Delete[0])});

    globalPathRegistry_register(PLATFORM,new ClassPath[] {cp});
    assertTrue(handler.await());
    assertEquals(1, handler.getBinaries().size());

    handler.reset(TestHandler.Type.BINARY);

    final long timeStamp = jar2Delete[0].lastModified().getTime();

    jar2Delete[0].delete();
    handler.await();

    binIndexerFactory.indexer.indexedAllFilesIndexing.clear();
    handler.reset(TestHandler.Type.BINARY);
    FileUtil.runAtomicAction(new Runnable(){
        @Override
        public void run() {
            try {
                jar2Delete[0] = jarFile.copy(wd, "test", "jar");
                FileUtil.toFile(jar2Delete[0]).setLastModified(timeStamp);
            } catch (IOException ioe) {
                throw new RuntimeException(ioe);
            }
        }
    });
    assertTrue(handler.await());
    assertTrue(binIndexerFactory.indexer.indexedAllFilesIndexing.toString(), binIndexerFactory.indexer.indexedAllFilesIndexing.contains(FileUtil.getArchiveRoot(jar2Delete[0]).toURL()));

}
 
Example 18
Project: incubator-netbeans   File: VisibilityChangeTest.java   View Source Code Vote up 4 votes
public void testRootVisibilityChangeInSingleRoot() 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(RepositoryUpdaterTest.TestHandler.Type.DELETE);
            Lookup.getDefault().lookup(MockVisibilityQuery.class).hide(src1);
            assertTrue (handler.await());
            assertEquals(
                new URI[0],
                MimeLookup.getLookup(MimePath.get(FOO_MIME)).lookup(FooIndexerFactory.class).clearIndexedFiles());
            assertEquals(
                new URI[]{
                    src1file1.toURI(),
                    src1file2.toURI()
                },
                MimeLookup.getLookup(MimePath.get(FOO_MIME)).lookup(FooIndexerFactory.class).clearRemovedFiles());
            handler.reset(RepositoryUpdaterTest.TestHandler.Type.FILELIST);
            Lookup.getDefault().lookup(MockVisibilityQuery.class).show(src1);
            assertTrue (handler.await());
            assertEquals(
                new URI[]{
                    src1file1.toURI(),
                    src1file2.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());
        } finally {
            logger.removeHandler(handler);
        }
    }
 
Example 19
Project: incubator-netbeans   File: FileListWorkOrderingTest.java   View Source Code Vote up 4 votes
/**
 * Tests that consequent file list works on different roots are not collapsed into single one.
 * Runs special work at start which in execution schedules FLW(src1) and FLW(src2) -> 2 FLWs should
 * be executed.
 */
public void testFLWOnDifferentRootsAreNotAbsorbed() 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(
                      src2.toURL(),
                      Collections.<URL>emptyList(),
                      false);
               }
            });
        assertTrue (handler.await());
        assertTrue (awaitRUSilence());
        assertEquals(2, MimeLookup.getLookup(MimePath.get(FOO_MIME)).
                        lookup(FooIndexerFactory.class).
                        getIndexingCount());
    } finally {
        logger.removeHandler(handler);
    }
}
 
Example 20
Project: jdk8u-jdk   File: TestLoggerBundleSync.java   View Source Code Vote up 4 votes
@Override
public void run() {
    try {
        handler.setLevel(Level.FINEST);
        while (goOn) {
            Logger l;
            Logger foo = Logger.getLogger("foo");
            Logger bar = Logger.getLogger("foo.bar");
            for (long i=0; i < nextLong.longValue() + 100 ; i++) {
                if (!goOn) break;
                l = Logger.getLogger("foo.bar.l"+i);
                final ResourceBundle b = l.getResourceBundle();
                final String name = l.getResourceBundleName();
                if (b != null) {
                    if (!name.equals(b.getBaseBundleName())) {
                        throw new RuntimeException("Unexpected bundle name: "
                                +b.getBaseBundleName());
                    }
                }
                Logger ll = Logger.getLogger(l.getName()+".bie.bye");
                ResourceBundle hrb;
                String hrbName;
                if (handler.getLevel() != Level.FINEST) {
                    throw new RuntimeException("Handler level is not finest: "
                            + handler.getLevel());
                }
                final int countBefore = handler.count;
                handler.reset();
                ll.setLevel(Level.FINEST);
                ll.addHandler(handler);
                ll.log(Level.FINE, "dummy {0}", this);
                ll.removeHandler(handler);
                final int countAfter = handler.count;
                if (countBefore == countAfter) {
                    throw new RuntimeException("Handler not called for "
                            + ll.getName() + "("+ countAfter +")");
                }
                hrb = handler.rb;
                hrbName = handler.rbName;
                if (name != null) {
                    // if name is not null, then it implies that it
                    // won't change, since setResourceBundle() cannot
                    // replace a non null name.
                    // Since we never set the resource bundle on 'll',
                    // then ll must inherit its resource bundle [name]
                    // from l - and therefor we should find it in
                    // handler.rb/handler.rbName
                    if (!name.equals(hrbName)) {
                        throw new RuntimeException("Unexpected bundle name: "
                                +hrbName);
                    }
                    // here we know that hrbName is not null so hrb
                    // should not be null either.
                    if (!name.equals(hrb.getBaseBundleName())) {
                        throw new RuntimeException("Unexpected bundle name: "
                                +hrb.getBaseBundleName());
                    }
                }

                // Make sure to refer to 'l' explicitly in order to
                // prevent eager garbage collecting before the end of
                // the test (JDK-8030192)
                if (!ll.getName().startsWith(l.getName())) {
                    throw new RuntimeException("Logger " + ll.getName()
                            + "does not start with expected prefix "
                            + l.getName());
                }

                getRBcount.incrementAndGet();
                if (!goOn) break;
                Thread.sleep(1);
            }
        }
   } catch (Exception x) {
       fail(x);
   }
}