Java 类java.util.logging.LogManager 实例源码

项目:ProjectAres    文件:ClassLogger.java   
public static ClassLogger get(@Nullable Logger parent, Class<?> klass, @Nullable String instanceKey) {
    if(parent == null) {
        parent = Logger.getLogger("");
    }

    ClassLogger logger = find(parent, klass, instanceKey);
    if(logger == null) {
        logger = new ClassLogger(parent, klass, instanceKey);
        // TODO: call addLogger from the constructuor, when it's no longer public
        final LogManager logManager = LogManager.getLogManager();
        if(logManager.addLogger(logger)) {
            // addLogger will set the parent, so we have to set it back again
            logger.setParent(parent);
        } else {
            // Logger was created by another thread
            logger = find(parent, klass, instanceKey);
            if(logger == null) {
                throw new IllegalStateException("Failed to register logger " + getName(klass, instanceKey));
            }
        }
    }

    return logger;
}
项目:incubator-netbeans    文件:Log.java   
static void configure(Level lev, String root, NbTestCase current) {
    IL il = new IL(false);

    String c = "handlers=" + Log.class.getName() + "\n" +
               root + ".level=" + lev.intValue() + "\n";

    ByteArrayInputStream is = new ByteArrayInputStream(c.getBytes());
    try {
        LogManager.getLogManager().readConfiguration(is);
    } catch (IOException ex) {
        // exception
        ex.printStackTrace();
    }

    Log.current = current;
    Log.messages.setLength(0);
    Log.messages.append("Starting test ");
    Log.messages.append(current.getName());
    Log.messages.append('\n');
    Log.initialMessages = Log.messages.length();
}
项目:openjdk-jdk10    文件:LoggingDeadlock.java   
public static void main(String[] args) throws InterruptedException{
    Thread t1 = new Thread(new Runnable() {
        public void run() {
            randomDelay();
            // Trigger Logger.<clinit>
            Logger.getAnonymousLogger();
        }
    });

    Thread t2 = new Thread(new Runnable() {
        public void run() {
            randomDelay();
            // Trigger LogManager.<clinit>
            LogManager.getLogManager();
        }
    });

    t1.start();
    t2.start();

    t1.join();
    t2.join();
    System.out.println("\nTest passed");
}
项目:incubator-netbeans    文件:TopLoggingTest.java   
public void testCanInfluenceBehaviourBySettingALevelPropertyOnParent() throws Exception {
    System.setProperty("ha.nu.level", "100");
    Reference<?> ref = new WeakReference<Object>(Logger.getLogger("ha.nu.wirta"));
    assertGC("ha.nu.wirta should not exist after this line", ref);

    LogManager.getLogManager().readConfiguration();

    final Logger log = Logger.getLogger("ha.nu.wirta");
    log.log(Level.FINER, "Finer level msg");

    Pattern p = Pattern.compile("FINER.*Finer level msg");
    String disk = readLog(true);
    Matcher d = p.matcher(disk);

    if (!d.find()) {
        fail("msg shall be logged to file: " + disk);
    }
}
项目:incubator-netbeans    文件:TopLoggingTest.java   
public void testCanInfluenceBehaviourBySettingALevelPropertyOnExistingParent() throws Exception {
    System.setProperty("ha.nu.level", "100");

    Logger l = Logger.getLogger("ha.nu.wirta");

    LogManager.getLogManager().readConfiguration();

    l.log(Level.FINER, "Finer level msg");

    Pattern p = Pattern.compile("FINER.*Finer level msg");
    String disk = readLog(true);
    Matcher d = p.matcher(disk);

    if (!d.find()) {
        fail("msg shall be logged to file: " + disk);
    }
}
项目:incubator-netbeans    文件:TopLoggingOwnConfigClassTest.java   
public Cfg() throws IOException {

            ByteArrayOutputStream os = new ByteArrayOutputStream();
            OutputStreamWriter w = new OutputStreamWriter(os);
            w.write("handlers=java.util.logging.FileHandler\n");
            w.write(".level=100\n");
            w.write("java.util.logging.FileHandler.pattern=" + log.toString().replace('\\', '/') +"\n");
            w.close();

            LogManager.getLogManager().readConfiguration(new ByteArrayInputStream(os.toByteArray()));

        }
项目:incubator-netbeans    文件:NbErrorManagerTest.java   
public void testLog() throws Exception {
    assertFalse(err.isLoggable(ErrorManager.INFORMATIONAL));
    err.log("some msg");
    String s = readLog();
    assertTrue(s.indexOf("some msg") == -1);
    assertTrue(err.isLoggable(ErrorManager.WARNING));
    err.log(ErrorManager.WARNING, "another msg");
    s = readLog();
    assertTrue(s.indexOf("another msg") != -1);
    ErrorManager err2 = err.getInstance("foo.bar.baz");
    assertFalse(err2.isLoggable(ErrorManager.INFORMATIONAL));
    err2.log("sub msg #1");
    s = readLog();
    assertTrue(s.indexOf("sub msg #1") == -1);
    System.setProperty("quux.hoho.level", "0");

    LogManager.getLogManager().readConfiguration();

    err2 = err.getInstance("quux.hoho.yaya");
    assertTrue(err2.isLoggable(ErrorManager.INFORMATIONAL));
    err2.log("sub msg #2");
    s = readLog();
    assertTrue(s, s.indexOf("sub msg #2") != -1);
    assertTrue(s, s.indexOf("quux.hoho.yaya") != -1);
}
项目:incubator-netbeans    文件:NbErrorManagerTest.java   
private String readLog() throws IOException {
    LogManager.getLogManager().readConfiguration();

    File log = new File(new File(new File(getWorkDir(), "var"), "log"), "messages.log");
    assertTrue("Log file exists: " + log, log.canRead());

    FileInputStream is = new FileInputStream(log);

    byte[] arr = new byte[(int)log.length()];
    int r = is.read(arr);
    assertEquals("all read", arr.length, r);
    is.close();

    new FileOutputStream(log).close(); // truncate

    return "---%<--- [start log of " + getName() + "]\n" + new String(arr).replaceFirst("\0+", "") + "\n---%<--- [end log of " + getName() + "]\n";
}
项目:launcher-backend    文件:LoggingConfig.java   
public LoggingConfig() {
    try {
        // Load a properties file from class path java.util.logging.config.file
        final LogManager logManager = LogManager.getLogManager();
        URL configURL = getClass().getResource("/logging.properties");
        if (configURL != null) {
            try (InputStream is = configURL.openStream()) {
                logManager.readConfiguration(is);
            }
        } else {
            // Programmatic configuration
            System.setProperty("java.util.logging.SimpleFormatter.format",
                               "%1$tY-%1$tm-%1$td %1$tH:%1$tM:%1$tS.%1$tL %4$-7s [%3$s] %5$s %6$s%n");

            final ConsoleHandler consoleHandler = new ConsoleHandler();
            consoleHandler.setLevel(Level.FINEST);
            consoleHandler.setFormatter(new SimpleFormatter());

            final Logger app = Logger.getLogger("app");
            app.setLevel(Level.FINEST);
            app.addHandler(consoleHandler);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
项目:openjdk-jdk10    文件:SimpleUpdateConfigWithInputStreamTest.java   
public void execute(Runnable run) {
    System.out.println("Running test case: " + name());
    try {
       Configure.setUp(this);
       Configure.doPrivileged(run, SimplePolicy.allowControl);
    } finally {
       Configure.doPrivileged(() -> {
           try {
               setSystemProperty("java.util.logging.config.file", null);
               LogManager.getLogManager().readConfiguration();
               System.gc();
           } catch (Exception x) {
               throw new RuntimeException(x);
           }
       }, SimplePolicy.allowAll);
    }
}
项目:jdk8u-jdk    文件:TestAppletLoggerContext.java   
public static void testFive() {
    for (int i=0; i<3 ; i++) {
        Logger logger1 = LogManager.getLogManager().getLogger(Logger.GLOBAL_LOGGER_NAME);
        Logger logger1b = LogManager.getLogManager().getLogger(Logger.GLOBAL_LOGGER_NAME);
        assertNotNull(logger1);
        assertNotNull(logger1b);
        assertEquals(logger1, logger1b);

        Bridge.changeContext();

        Logger logger2 = LogManager.getLogManager().getLogger(Logger.GLOBAL_LOGGER_NAME);
        Logger logger2b = LogManager.getLogManager().getLogger(Logger.GLOBAL_LOGGER_NAME);
        assertNotNull(logger2);
        assertNotNull(logger2b);
        assertEquals(logger2, logger2b);

        assertEquals(logger1, logger2);
    }
}
项目:tomcat7    文件:Catalina.java   
@Override
public void run() {
    try {
        if (getServer() != null) {
            Catalina.this.stop();
        }
    } catch (Throwable ex) {
        ExceptionUtils.handleThrowable(ex);
        log.error(sm.getString("catalina.shutdownHookFail"), ex);
    } finally {
        // If JULI is used, shut JULI down *after* the server shuts down
        // so log messages aren't lost
        LogManager logManager = LogManager.getLogManager();
        if (logManager instanceof ClassLoaderLogManager) {
            ((ClassLoaderLogManager) logManager).shutdown();
        }
    }
}
项目:openjdk-jdk10    文件:TestAppletLoggerContext.java   
public static void testLoadingMain() {
    Bridge.desactivate();

    Logger bar = new Bridge.CustomLogger("com.foo.Bar");
    LogManager.getLogManager().addLogger(bar);
    assertNotNull(bar.getParent());
    testParent(bar);
    testParent(LogManager.getLogManager().getLogger("global"));
    testParent(LogManager.getLogManager().getLogger(bar.getName()));

    Bridge.changeContext();

    Logger foo = new Bridge.CustomLogger("com.foo.Foo");
    boolean b = LogManager.getLogManager().addLogger(foo);
    assertEquals(Boolean.TRUE, Boolean.valueOf(b));
    assertNotNull(foo.getParent());
    testParent(foo);
    testParent(LogManager.getLogManager().getLogger("global"));
    testParent(LogManager.getLogManager().getLogger(foo.getName()));

}
项目:openjdk-jdk10    文件:TestConfigurationLock.java   
@Override
public void run() {
    while (goOn) {
        try {
            if (Math.random() > CONFSYNCTHRESHOLD) {
                // calling readConfiguration while holding a lock can
                // increase deadlock probability...
                synchronized(fakeConfExternalLock()) {
                    LogManager.getLogManager().readConfiguration();
                }
            } else {
                LogManager.getLogManager().readConfiguration();
            }
            Logger blah = Logger.getLogger(BLAH);
            blah.setLevel(Level.FINEST);
            blah.fine(BLAH);
            readCount.incrementAndGet();
            pause(1);
        } catch (Exception x) {
            fail(x);
        }
    }
}
项目:Open-DM    文件:FileHandler.java   
private static String getPattern() {
    LogManager manager = LogManager.getLogManager();

    String cname = FileHandler.class.getName();

    String pattern = manager.getProperty(cname + ".pattern");
    if (pattern == null) {
        pattern = "%h/java%u.log";
    }

    return pattern;
}
项目:lazycat    文件:Catalina.java   
@Override
public void run() {
    try {
        if (getServer() != null) {
            Catalina.this.stop();
        }
    } catch (Throwable ex) {
        ExceptionUtils.handleThrowable(ex);
        log.error(sm.getString("catalina.shutdownHookFail"), ex);
    } finally {
        // If JULI is used, shut JULI down *after* the server shuts down
        // so log messages aren't lost
        LogManager logManager = LogManager.getLogManager();
        if (logManager instanceof ClassLoaderLogManager) {
            ((ClassLoaderLogManager) logManager).shutdown();
        }
    }
}
项目:openjdk-jdk10    文件:TestAppletLoggerContext.java   
public static void testThree() {
    for (int i=0; i<3 ; i++) {
        Logger logger1 = LogManager.getLogManager().getLogger("");
        Logger logger1b = LogManager.getLogManager().getLogger("");
        assertNotNull(logger1);
        assertNotNull(logger1b);
        assertEquals(logger1, logger1b);
        Bridge.changeContext();
        Logger logger2 = LogManager.getLogManager().getLogger("");
        Logger logger2b = LogManager.getLogManager().getLogger("");
        assertNotNull(logger2);
        assertNotNull(logger2b);
        assertEquals(logger2, logger2b);
        assertEquals(logger1, logger2);
    }
}
项目:openjdk-jdk10    文件:SimpleUpdateConfigurationTest.java   
public void execute(Runnable run) {
    System.out.println("Running test case: " + name());
    try {
       Configure.setUp(this);
       Configure.doPrivileged(run, SimplePolicy.allowControl);
    } finally {
       Configure.doPrivileged(() -> {
           try {
               setSystemProperty("java.util.logging.config.file", null);
               LogManager.getLogManager().readConfiguration();
               System.gc();
           } catch (Exception x) {
               throw new RuntimeException(x);
           }
       }, SimplePolicy.allowAll);
    }
}
项目:scorekeeperfrontend    文件:AppSetup.java   
/**
 * Do some common setup for all applications at startup
 * @param name the application name used for Java logging and database logging
 */
public static void appSetup(String name)
{
    // Set our platform wide L&F 
    System.setProperty("swing.defaultlaf", "javax.swing.plaf.nimbus.NimbusLookAndFeel");
    UIDefaults defaults = UIManager.getLookAndFeelDefaults();
    defaults.put("Table.gridColor", new Color(140,140,140));
    defaults.put("Table.showGrid", true);

    // Set the program name which is used by PostgresqlDatabase to identify the app in logs
    System.setProperty("program.name", name);

    // Start with a fresh root set at warning
    Logger root = LogManager.getLogManager().getLogger("");
    Formatter format = new SingleLineFormatter();

    root.setLevel(Level.WARNING);
    for(Handler handler : root.getHandlers()) {
        root.removeHandler(handler);
    }

    // Set prefs levels before windows preference load barfs useless data on the user
    Logger.getLogger("java.util.prefs").setLevel(Level.SEVERE);
    // postgres JDBC spits out a lot of data even though we catch the exception
    Logger.getLogger("org.postgresql.jdbc").setLevel(Level.OFF);
    Logger.getLogger("org.postgresql.Driver").setLevel(Level.OFF);

    // Add console handler if running in debug mode
    if (Prefs.isDebug()) {
        ConsoleHandler ch = new ConsoleHandler();
        ch.setLevel(Level.ALL);
        ch.setFormatter(format);
        root.addHandler(ch);
    }

    // For our own logs, we can set super fine level or info depending on if debug mode and attach dialogs to those
    Logger applog = Logger.getLogger("org.wwscc");
    applog.setLevel(Prefs.isDebug() ? Level.FINEST : Level.INFO);
    applog.addHandler(new AlertHandler());

    Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() {
        @Override
        public void uncaughtException(Thread t, Throwable e) {
            applog.log(Level.WARNING, String.format("\bUncaughtException in %s: %s", t, e), e);
        }});

    try {
        File logdir = Prefs.getLogDirectory().toFile();
        if (!logdir.exists())
            if (!logdir.mkdirs())
                throw new IOException("Can't create log directory " + logdir);
        FileHandler fh = new FileHandler(new File(logdir, name+".%g.log").getAbsolutePath(), 1000000, 10, true);
        fh.setFormatter(format);
        fh.setLevel(Level.ALL);
        root.addHandler(fh);
    } catch (IOException ioe) {
        JOptionPane.showMessageDialog(FocusManager.getCurrentManager().getActiveWindow(),
                "Unable to enable logging to file: " + ioe, "Log Error", JOptionPane.ERROR_MESSAGE);
    }

    // force the initialization of IdGenerator on another thread so app can start now without an odd delay later
    new Thread() {
        public void run() {
            IdGenerator.generateId();
        }
    }.start();
}
项目:jdk8u-jdk    文件:TestAppletLoggerContext.java   
public static void testLoadingApplet() {
    Bridge.changeContext();

    Logger bar = new Bridge.CustomLogger("com.foo.Bar");
    LogManager.getLogManager().addLogger(bar);
    assertNotNull(bar.getParent());
    testParent(bar);
    testParent(LogManager.getLogManager().getLogger("global"));
    testParent(LogManager.getLogManager().getLogger(bar.getName()));

    Bridge.desactivate();

    Logger foo = new Bridge.CustomLogger("com.foo.Foo");
    boolean b = LogManager.getLogManager().addLogger(foo);
    assertEquals(Boolean.TRUE, Boolean.valueOf(b));
    assertNotNull(foo.getParent());
    testParent(foo);
    testParent(LogManager.getLogManager().getLogger("global"));
    testParent(LogManager.getLogManager().getLogger(foo.getName()));
}
项目:openjdk-jdk10    文件:TestConfigurationLock.java   
@Override
public void run() {
    while (goOn) {
        try {
            if (Math.random() > CONFSYNCTHRESHOLD) {
                // calling reset while holding a lock can increase
                // deadlock probability...
                synchronized(fakeConfExternalLock()) {
                    LogManager.getLogManager().reset();
                }
            } else {
                LogManager.getLogManager().reset();
            }
            Logger blah = Logger.getLogger(BLAH);
            blah.setLevel(Level.FINEST);
            blah.fine(BLAH);
            resetCount.incrementAndGet();
            pause(1);
        } catch (Exception x) {
            fail(x);
        }
    }
}
项目:openjdk-jdk10    文件:LoggingProviderImpl.java   
/**
 * Creates a java.util.logging.Logger for the given module.
 * @param name the logger name.
 * @param module the module for which the logger should be created.
 * @return a Logger suitable for use in the given module.
 */
private static java.util.logging.Logger demandJULLoggerFor(final String name,
                                                           Module module) {
    final LogManager manager = LogManager.getLogManager();
    final SecurityManager sm = System.getSecurityManager();
    if (sm == null) {
        return logManagerAccess.demandLoggerFor(manager, name, module);
    } else {
        final PrivilegedAction<java.util.logging.Logger> pa =
                () -> logManagerAccess.demandLoggerFor(manager, name, module);
        return AccessController.doPrivileged(pa, null, LOGGING_CONTROL_PERMISSION);
    }
}
项目:Reer    文件:JavaUtilLoggingSystem.java   
private void uninstall(Level level) {
    if (!installed) {
        return;
    }

    LogManager.getLogManager().reset();
    logger.setLevel(level);
    installed = false;
}
项目:L2jBrasil    文件:GameServer.java   
public static void main(String[] args) throws Exception
{ 
    Server.serverMode = Server.MODE_GAMESERVER;
    // Local Constants
    final String LOG_FOLDER = "log"; // Name of folder for log file
    final String LOG_NAME   = "./config/other/log.cfg"; // Name of log file

    // Create log folder
    File logFolder = new File(Config.DATAPACK_ROOT, LOG_FOLDER);
    logFolder.mkdir();

    // Create input stream for log file -- or store file data into memory
    InputStream is =  new FileInputStream(new File(LOG_NAME));
    LogManager.getLogManager().readConfiguration(is);
    is.close();

    // Initialize config
    Config.load();

    Util.printSection("Data Base"); 
    L2DatabaseFactory.getInstance();
    gameServer = new GameServer();

    if (Config.IS_TELNET_ENABLED) 
    {
        _statusServer = new Status(Server.serverMode);
        _statusServer.start();
    }
    else 
        System.out.println("Telnet is disabled.");
}
项目:jdk8u-jdk    文件:TestLogConfigurationDeadLockWithConf.java   
@Override
public void run() {
    while (goOn) {
        try {
            LogManager.getLogManager().readConfiguration();
            readCount.incrementAndGet();
            Thread.sleep(1);
        } catch (Exception x) {
            fail(x);
        }
    }
}
项目:openjdk-jdk10    文件:SimpleUpdateConfigurationTest.java   
static void updateConfigurationWith(Properties propertyFile,
        Function<String,BiFunction<String,String,String>> remapper) {
    try {
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        propertyFile.store(bytes, propertyFile.getProperty("test.name"));
        ByteArrayInputStream bais = new ByteArrayInputStream(bytes.toByteArray());
        LogManager.getLogManager().updateConfiguration(bais, remapper);
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    }
}
项目:jdk8u-jdk    文件:RootLevelInConfigFile.java   
public static void main(String[] args) throws IOException {
    System.setProperty(CONFIG_FILE_KEY,
            new File(System.getProperty("test.src", "."),
                    "rootlogger.properties").getAbsolutePath());
    System.out.println(CONFIG_FILE_KEY + "="
            + System.getProperty(CONFIG_FILE_KEY));
    if (! new File(System.getProperty(CONFIG_FILE_KEY)).canRead()) {
        throw new RuntimeException("can't read config file: "
                + System.getProperty(CONFIG_FILE_KEY));
    }

    final String configFile = System.getProperty(CONFIG_FILE_KEY);

    test("no security");

    LogManager.getLogManager().readConfiguration();

    Policy.setPolicy(new SimplePolicy(configFile));
    System.setSecurityManager(new SecurityManager());

    test("security");

    LogManager.getLogManager().readConfiguration();

    final JavaAWTAccessStub access = new JavaAWTAccessStub();
    SharedSecrets.setJavaAWTAccess(access);

    test("security and no context");

    for (Context ctx : Context.values()) {

        LogManager.getLogManager().readConfiguration();

        access.setContext(ctx);

        test("security and context " + ctx);
    }
}
项目:openjdk-jdk10    文件:FileHandlerPath.java   
static void setUp(TestCase test, Properties propertyFile) {
    switch (test) {
        case SECURE:
            if (policy == null && System.getSecurityManager() != null) {
                throw new IllegalStateException("SecurityManager already set");
            } else if (policy == null) {
                policy = new SimplePolicy(TestCase.SECURE, allowAll);
                Policy.setPolicy(policy);
                System.setSecurityManager(new SecurityManager());
            }
            if (System.getSecurityManager() == null) {
                throw new IllegalStateException("No SecurityManager.");
            }
            if (policy == null) {
                throw new IllegalStateException("policy not configured");
            }
            break;
        case UNSECURE:
            if (System.getSecurityManager() != null) {
                throw new IllegalStateException("SecurityManager already set");
            }
            break;
        default:
            new InternalError("No such testcase: " + test);
    }
    doPrivileged(() -> {
        try {
            ByteArrayOutputStream bytes = new ByteArrayOutputStream();
            propertyFile.store(bytes, propertyFile.getProperty("test.name"));
            ByteArrayInputStream bais = new ByteArrayInputStream(bytes.toByteArray());
            LogManager.getLogManager().readConfiguration(bais);
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        }
    });
}
项目:openjdk-jdk10    文件:HandlersOnComplexUpdate.java   
static void updateConfigurationWith(Properties propertyFile, boolean append) {
    try {
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        propertyFile.store(bytes, propertyFile.getProperty("test.name"));
        ByteArrayInputStream bais = new ByteArrayInputStream(bytes.toByteArray());
        Function<String, BiFunction<String,String,String>> remapper =
                append ? (x) -> ((o, n) -> n == null ? o : n)
                       : (x) -> ((o, n) -> n);
        LogManager.getLogManager().updateConfiguration(bais, remapper);
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    }
}
项目:openjdk-jdk10    文件:TestLoggerNames.java   
static void checkLoggerNames(List<Logger> loggers) {
    Enumeration<String> names = LogManager.getLogManager().getLoggerNames();
    if (names instanceof Iterator) {
        for (Iterator<?> it = Iterator.class.cast(names); it.hasNext(); ) {
            try {
                it.remove();
                throw new RuntimeException("Iterator supports remove!");
            } catch (UnsupportedOperationException x) {
                System.out.println("OK: Iterator doesn't support remove.");
            }
        }
        // We're not supposed to come here, but if we do then we
        // need to rewind names...
        names = LogManager.getLogManager().getLoggerNames();
    }

    List<String> loggerNames = Collections.list(names);
    if (!loggerNames.contains("")) {
        throw new RuntimeException("\"\"" +
                " not found in " + loggerNames);
    }
    if (!loggerNames.contains("global")) {
        throw new RuntimeException("global" +
                " not found in " + loggerNames);
    }
    for (Logger l : loggers) {
        if (!loggerNames.contains(l.getName())) {
            throw new RuntimeException(l.getName() +
                    " not found in " + loggerNames);
        }
    }
    System.out.println("Got all expected logger names");
}
项目:openjdk-jdk10    文件:FileHandlerPatternExceptions.java   
static void setUp(TestCase test, Properties propertyFile) {
    switch (test) {
        case SECURE:
            if (policy == null && System.getSecurityManager() != null) {
                throw new IllegalStateException("SecurityManager already set");
            } else if (policy == null) {
                policy = new SimplePolicy(TestCase.SECURE, allowAll);
                Policy.setPolicy(policy);
                System.setSecurityManager(new SecurityManager());
            }
            if (System.getSecurityManager() == null) {
                throw new IllegalStateException("No SecurityManager.");
            }
            if (policy == null) {
                throw new IllegalStateException("policy not configured");
            }
            break;
        case UNSECURE:
            if (System.getSecurityManager() != null) {
                throw new IllegalStateException("SecurityManager already set");
            }
            break;
        default:
            new InternalError("No such testcase: " + test);
    }
    doPrivileged(() -> {
        try {
            ByteArrayOutputStream bytes = new ByteArrayOutputStream();
            propertyFile.store(bytes, propertyFile.getProperty("test.name"));
            ByteArrayInputStream bais = new ByteArrayInputStream(bytes.toByteArray());
            LogManager.getLogManager().readConfiguration(bais);
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        }
    });
}
项目:alog    文件:AlogTests.java   
@Test
public void test4() throws Exception {
    System.setProperty("com.comfortanalytics.alog.maxQueue", "12345");
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    System.getProperties().store(out, null);
    LogManager.getLogManager().readConfiguration(new ByteArrayInputStream(out.toByteArray()));
    Alog.loadDefaults();
    Assert.assertTrue(Alog.DEFAULT_MAX_QUEUE == 12345);
}
项目:vogar    文件:TestEnvironment.java   
public void reset() {
    // Reset system properties.
    System.setProperties(null);

    // From "L" release onwards, calling System.setProperties(null) clears the java.io.tmpdir,
    // so we set it again. No-op on earlier releases.
    System.setProperty("java.io.tmpdir", tmpDir);

    if (JAVA_RUNTIME_VERSION != null) {
        System.setProperty("java.runtime.version", JAVA_RUNTIME_VERSION);
    }
    if (JAVA_VM_INFO != null) {
        System.setProperty("java.vm.info", JAVA_VM_INFO);
    }
    if (JAVA_VM_VERSION != null) {
        System.setProperty("java.vm.version", JAVA_VM_VERSION);
    }
    if (JAVA_VM_VENDOR != null) {
        System.setProperty("java.vm.vendor", JAVA_VM_VENDOR);
    }
    if (JAVA_VM_NAME != null) {
        System.setProperty("java.vm.name", JAVA_VM_NAME);
    }

    // Require writable java.home and user.dir directories for preferences
    if ("Dalvik".equals(System.getProperty("java.vm.name"))) {
        String javaHome = tmpDir + "/java.home";
        IoUtils.safeMkdirs(new File(javaHome));
        System.setProperty("java.home", javaHome);
    }
    String userHome = System.getProperty("user.home");
    if (userHome.length() == 0) {
        userHome = tmpDir + "/user.home";
        IoUtils.safeMkdirs(new File(userHome));
        System.setProperty("user.home", userHome);
    }

    // Localization
    Locale.setDefault(Locale.US);
    TimeZone.setDefault(TimeZone.getTimeZone("America/Los_Angeles"));

    // Preferences
    // Temporarily silence the java.util.prefs logger, which otherwise emits
    // an unactionable warning. See RI bug 4751540.
    Logger loggerToMute = Logger.getLogger("java.util.prefs");
    boolean usedParentHandlers = loggerToMute.getUseParentHandlers();
    loggerToMute.setUseParentHandlers(false);
    try {
        // resetPreferences(Preferences.systemRoot());
        resetPreferences(Preferences.userRoot());
    } finally {
        loggerToMute.setUseParentHandlers(usedParentHandlers);
    }

    // HttpURLConnection
    Authenticator.setDefault(null);
    CookieHandler.setDefault(null);
    ResponseCache.setDefault(null);
    HttpsURLConnection.setDefaultHostnameVerifier(defaultHostnameVerifier);
    HttpsURLConnection.setDefaultSSLSocketFactory(defaultSSLSocketFactory);

    // Logging
    LogManager.getLogManager().reset();
    Logger.getLogger("").addHandler(new ConsoleHandler());

    // Cleanup to force CloseGuard warnings etc
    System.gc();
    System.runFinalization();
}
项目:openjdk-jdk10    文件:FileHandlerLongLimit.java   
static void setUp(TestCase test, Properties propertyFile) {
    switch (test) {
        case SECURE:
            if (policy == null && System.getSecurityManager() != null) {
                throw new IllegalStateException("SecurityManager already set");
            } else if (policy == null) {
                policy = new SimplePolicy(TestCase.SECURE, allowAll);
                Policy.setPolicy(policy);
                System.setSecurityManager(new SecurityManager());
            }
            if (System.getSecurityManager() == null) {
                throw new IllegalStateException("No SecurityManager.");
            }
            if (policy == null) {
                throw new IllegalStateException("policy not configured");
            }
            break;
        case UNSECURE:
            if (System.getSecurityManager() != null) {
                throw new IllegalStateException("SecurityManager already set");
            }
            break;
        default:
            new InternalError("No such testcase: " + test);
    }
    doPrivileged(() -> {
        try {
            ByteArrayOutputStream bytes = new ByteArrayOutputStream();
            propertyFile.store(bytes, propertyFile.getProperty("test.name"));
            ByteArrayInputStream bais = new ByteArrayInputStream(bytes.toByteArray());
            LogManager.getLogManager().readConfiguration(bais);
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        }
    });
}
项目:burstcoin    文件:Logger.java   
public static void logShutdownMessage(String message, Exception e) {
    if (LogManager.getLogManager() instanceof NxtLogManager) {
        logMessage(message, e);
    } else {
        System.out.println(message);
        System.out.println(e.toString());
    }
}
项目:asw    文件:AswLogger.java   
private AswLogger() {
    LogManager logManager = LogManager.getLogManager();
    try {
        logManager.readConfiguration(new FileInputStream(LOGGING_CONFIG_FILE));
    } catch (Exception e) {
        /* di solito l'eccezione si verifica perche' non trova il file logging.properties */
        /* Stampa il messaggio dell'eccezione */
        // System.err.println(e);
        /* definisce una configurazione alternativa */
        logManager.reset();
        Handler handler = new ConsoleHandler();
        handler.setFormatter( new TextFormatter() );
        Logger.getLogger("").addHandler( handler );
    }
}
项目:openjdk-jdk10    文件:SimpleUpdateConfigWithInputStreamTest.java   
static void updateConfigurationWith(Properties propertyFile,
        Function<String,BiFunction<String,String,String>> remapper) {
    try {
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        propertyFile.store(bytes, propertyFile.getProperty("test.name"));
        ByteArrayInputStream bais = new ByteArrayInputStream(bytes.toByteArray());
        LogManager.getLogManager().updateConfiguration(bais, remapper);
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    }
}
项目:APacheSynapseSimplePOC    文件:JBoss.java   
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);
    }
}
项目:pmTrans    文件:GlobalKeyListener.java   
public GlobalKeyListener() {
    LogManager.getLogManager().reset();

    // Get the logger for "org.jnativehook" and set the level to off.
    Logger logger = Logger.getLogger(GlobalScreen.class.getPackage()
            .getName());
    logger.setLevel(Level.OFF);
}
项目:openjdk-jdk10    文件:XMLFormatterDate.java   
/**
 * Before the fix, JDK8 prints: {@code
 * <record>
 *   <date>3913-11-18T17:35:40</date>
 *   <millis>1384792540403</millis>
 *   <sequence>0</sequence>
 *   <level>INFO</level>
 *   <thread>1</thread>
 *   <message>test</message>
 * </record>
 * }
 * After the fix, it should print: {@code
 * <record>
 *   <date>2013-11-18T17:35:40</date>
 *   <millis>1384792696519</millis>
 *   <sequence>0</sequence>
 *   <level>INFO</level>
 *   <thread>1</thread>
 *   <message>test</message>
 * </record>
 * }
 * @param args the command line arguments
 */
public static void main(String[] args) {
    Locale locale = Locale.getDefault();
    try {
        Locale.setDefault(Locale.ENGLISH);

        // Test with default format: by default date is in UTC.
        System.out.println("Testing with UTC");
        test(() -> new TimeStamp(ZoneOffset.UTC));

        // Change LogManager configuration so that new
        // XMLFormatter prints date in the pre Java 9 local zone format
        try {
            Properties props = new Properties();
            props.setProperty("java.util.logging.XMLFormatter.useInstant", "false");
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            props.store(baos, "");
            ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
            LogManager.getLogManager().updateConfiguration(bais, (k) -> (o,n) -> n!=null?n:o);
        } catch (IOException io) {
            throw new RuntimeException(io);
        }

        // re test with the old format: date will be in the local time zone.
        System.out.println("Testing with old format");
        test(() -> new TimeStamp(ZoneId.systemDefault()));

    } finally {
        Locale.setDefault(locale);
    }
}