Example usage for java.util.logging Level WARNING

List of usage examples for java.util.logging Level WARNING

Introduction

In this page you can find the example usage for java.util.logging Level WARNING.

Prototype

Level WARNING

To view the source code for java.util.logging Level WARNING.

Click Source Link

Document

WARNING is a message level indicating a potential problem.

Usage

From source file:MailHandlerDemo.java

/**
 * Runs the demo.//from   w  ww  . jav  a  2  s .c o m
 *
 * @param args the command line arguments
 * @throws IOException if there is a problem.
 */
public static void main(String[] args) throws IOException {
    List<String> l = Arrays.asList(args);
    if (l.contains("/?") || l.contains("-?") || l.contains("-help")) {
        LOGGER.info("Usage: java MailHandlerDemo " + "[[-all] | [-body] | [-custom] | [-debug] | [-low] "
                + "| [-simple] | [-pushlevel] | [-pushfilter] " + "| [-pushnormal] | [-pushonly]] " + "\n\n"
                + "-all\t\t: Execute all demos.\n" + "-body\t\t: An email with all records and only a body.\n"
                + "-custom\t\t: An email with attachments and dynamic names.\n"
                + "-debug\t\t: Output basic debug information about the JVM " + "and log configuration.\n"
                + "-low\t\t: Generates multiple emails due to low capacity." + "\n"
                + "-simple\t\t: An email with all records with body and " + "an attachment.\n"
                + "-pushlevel\t: Generates high priority emails when the"
                + " push level is triggered and normal priority when " + "flushed.\n"
                + "-pushFilter\t: Generates high priority emails when the "
                + "push level and the push filter is triggered and normal " + "priority emails when flushed.\n"
                + "-pushnormal\t: Generates multiple emails when the "
                + "MemoryHandler push level is triggered.  All generated "
                + "email are sent as normal priority.\n" + "-pushonly\t: Generates multiple emails when the "
                + "MemoryHandler push level is triggered.  Generates high "
                + "priority emails when the push level is triggered and " + "normal priority when flushed.\n");
    } else {
        final boolean debug = init(l); //may create log messages.
        try {
            LOGGER.log(Level.FINEST, "This is the finest part of the demo.",
                    new MessagingException("Fake JavaMail issue."));
            LOGGER.log(Level.FINER, "This is the finer part of the demo.",
                    new NullPointerException("Fake bug."));
            LOGGER.log(Level.FINE, "This is the fine part of the demo.");
            LOGGER.log(Level.CONFIG, "Logging config file is {0}.", getConfigLocation());
            LOGGER.log(Level.INFO, "Your temp directory is {0}, " + "please wait...", getTempDir());

            try { //Waste some time for the custom formatter.
                Thread.sleep(3L * 1000L);
            } catch (InterruptedException ex) {
                Thread.currentThread().interrupt();
            }

            LOGGER.log(Level.WARNING, "This is a warning.",
                    new FileNotFoundException("Fake file chooser issue."));
            LOGGER.log(Level.SEVERE, "The end of the demo.", new IOException("Fake access denied issue."));
        } finally {
            closeHandlers();
        }

        //Force parse errors.  This does have side effects.
        if (debug && getConfigLocation() != null) {
            LogManager.getLogManager().readConfiguration();
        }
    }
}

From source file:com.frostvoid.trekwar.server.TrekwarServer.java

public static void main(String[] args) {
    // load language
    try {/*from   w  ww . j  a v a 2  s . c  om*/
        lang = new Language(Language.ENGLISH);
    } catch (IOException ioe) {
        System.err.println("FATAL ERROR: Unable to load language file!");
        System.exit(1);
    }

    System.out.println(lang.get("trekwar_server") + " " + VERSION);
    System.out.println("==============================================".substring(0,
            lang.get("trekwar_server").length() + 1 + VERSION.length()));

    // Handle parameters
    Options options = new Options();
    options.addOption(OptionBuilder.withArgName("file").withLongOpt("galaxy").hasArg()
            .withDescription("the galaxy file to load").create("g")); //"g", "galaxy", true, "the galaxy file to load");
    options.addOption(OptionBuilder.withArgName("port number").withLongOpt("port").hasArg()
            .withDescription("the port number to bind to (default 8472)").create("p"));
    options.addOption(OptionBuilder.withArgName("number").withLongOpt("save-interval").hasArg()
            .withDescription("how often (in turns) to save the galaxy to disk (default: 5)").create("s"));
    options.addOption(OptionBuilder.withArgName("log level").withLongOpt("log").hasArg()
            .withDescription("sets the log level: ALL, FINEST, FINER, FINE, CONFIG, INFO, WARNING, SEVERE, OFF")
            .create("l"));
    options.addOption("h", "help", false, "prints this help message");

    CommandLineParser cliParser = new BasicParser();

    try {
        CommandLine cmd = cliParser.parse(options, args);
        String portStr = cmd.getOptionValue("p");
        String galaxyFileStr = cmd.getOptionValue("g");
        String saveIntervalStr = cmd.getOptionValue("s");
        String logLevelStr = cmd.getOptionValue("l");

        if (cmd.hasOption("h")) {
            HelpFormatter help = new HelpFormatter();
            help.printHelp("TrekwarServer", options);
            System.exit(0);
        }

        if (cmd.hasOption("g") && galaxyFileStr != null) {
            galaxyFileName = galaxyFileStr;
        } else {
            throw new ParseException("galaxy file not specified");
        }

        if (cmd.hasOption("p") && portStr != null) {
            port = Integer.parseInt(portStr);
            if (port < 1 || port > 65535) {
                throw new NumberFormatException(lang.get("port_number_out_of_range"));
            }
        } else {
            port = 8472;
        }

        if (cmd.hasOption("s") && saveIntervalStr != null) {
            saveInterval = Integer.parseInt(saveIntervalStr);
            if (saveInterval < 1 || saveInterval > 100) {
                throw new NumberFormatException("Save Interval out of range (1-100)");
            }
        } else {
            saveInterval = 5;
        }

        if (cmd.hasOption("l") && logLevelStr != null) {
            if (logLevelStr.equalsIgnoreCase("finest")) {
                LOG.setLevel(Level.FINEST);
            } else if (logLevelStr.equalsIgnoreCase("finer")) {
                LOG.setLevel(Level.FINER);
            } else if (logLevelStr.equalsIgnoreCase("fine")) {
                LOG.setLevel(Level.FINE);
            } else if (logLevelStr.equalsIgnoreCase("config")) {
                LOG.setLevel(Level.CONFIG);
            } else if (logLevelStr.equalsIgnoreCase("info")) {
                LOG.setLevel(Level.INFO);
            } else if (logLevelStr.equalsIgnoreCase("warning")) {
                LOG.setLevel(Level.WARNING);
            } else if (logLevelStr.equalsIgnoreCase("severe")) {
                LOG.setLevel(Level.SEVERE);
            } else if (logLevelStr.equalsIgnoreCase("off")) {
                LOG.setLevel(Level.OFF);
            } else if (logLevelStr.equalsIgnoreCase("all")) {
                LOG.setLevel(Level.ALL);
            } else {
                System.err.println("ERROR: invalid log level: " + logLevelStr);
                System.err.println("Run again with -h flag to see valid log level values");
                System.exit(1);
            }
        } else {
            LOG.setLevel(Level.INFO);
        }
        // INIT LOGGING
        try {
            LOG.setUseParentHandlers(false);
            initLogging();
        } catch (IOException ex) {
            System.err.println("Unable to initialize logging to file");
            System.err.println(ex);
            System.exit(1);
        }

    } catch (Exception ex) {
        System.err.println("ERROR: " + ex.getMessage());
        System.err.println("use -h for help");
        System.exit(1);
    }

    LOG.log(Level.INFO, "Trekwar2 server " + VERSION + " starting up");

    // LOAD GALAXY
    File galaxyFile = new File(galaxyFileName);
    if (galaxyFile.exists()) {
        try {
            long timer = System.currentTimeMillis();
            LOG.log(Level.INFO, "Loading galaxy file {0}", galaxyFileName);
            ObjectInputStream ois = new ObjectInputStream(new FileInputStream(galaxyFile));
            galaxy = (Galaxy) ois.readObject();
            timer = System.currentTimeMillis() - timer;
            LOG.log(Level.INFO, "Galaxy file loaded in {0} ms", timer);
            ois.close();
        } catch (IOException ioe) {
            LOG.log(Level.SEVERE, "IO error while trying to load galaxy file", ioe);
        } catch (ClassNotFoundException cnfe) {
            LOG.log(Level.SEVERE, "Unable to find class while loading galaxy", cnfe);
        }
    } else {
        System.err.println("Error: file " + galaxyFileName + " not found");
        System.exit(1);
    }

    // if turn == 0 (start of game), execute first turn to update fog of war.
    if (galaxy.getCurrentTurn() == 0) {
        TurnExecutor.executeTurn(galaxy);
    }

    LOG.log(Level.INFO, "Current turn  : {0}", galaxy.getCurrentTurn());
    LOG.log(Level.INFO, "Turn speed    : {0} seconds", galaxy.getTurnSpeed() / 1000);
    LOG.log(Level.INFO, "Save Interval : {0}", saveInterval);
    LOG.log(Level.INFO, "Users / max   : {0} / {1}",
            new Object[] { galaxy.getUserCount(), galaxy.getMaxUsers() });

    // START SERVER
    try {
        server = new ServerSocket(port);
        LOG.log(Level.INFO, "Server listening on port {0}", port);
    } catch (BindException be) {
        LOG.log(Level.SEVERE, "Error: Unable to bind to port {0}", port);
        System.err.println(be);
        System.exit(1);
    } catch (IOException ioe) {
        LOG.log(Level.SEVERE, "Error: IO error while binding to port {0}", port);
        System.err.println(ioe);
        System.exit(1);
    }

    galaxy.startup();

    Thread timerThread = new Thread(new Runnable() {

        @Override
        @SuppressWarnings("SleepWhileInLoop")
        public void run() {
            while (true) {
                try {
                    Thread.sleep(1000);
                    // && galaxy.getLoggedInUsers().size() > 0 will make server pause when nobody is logged in (TESTING)
                    if (System.currentTimeMillis() > galaxy.nextTurnDate) {
                        StringBuffer loggedInUsers = new StringBuffer();
                        for (User u : galaxy.getLoggedInUsers()) {
                            loggedInUsers.append(u.getUsername()).append(", ");
                        }

                        long time = TurnExecutor.executeTurn(galaxy);
                        LOG.log(Level.INFO, "Turn {0} executed in {1} ms",
                                new Object[] { galaxy.getCurrentTurn(), time });
                        LOG.log(Level.INFO, "Logged in users: " + loggedInUsers.toString());
                        LOG.log(Level.INFO,
                                "====================================================================================");

                        if (galaxy.getCurrentTurn() % saveInterval == 0) {
                            saveGalaxy();
                        }

                        galaxy.lastTurnDate = System.currentTimeMillis();
                        galaxy.nextTurnDate = galaxy.lastTurnDate + galaxy.turnSpeed;
                    }

                } catch (InterruptedException e) {
                    LOG.log(Level.SEVERE, "Error in main server loop, interrupted", e);
                }
            }
        }
    });
    timerThread.start();

    // ACCEPT CONNECTIONS AND DELEGATE TO CLIENT SESSIONS
    while (true) {
        Socket clientConnection;
        try {
            clientConnection = server.accept();
            ClientSession c = new ClientSession(clientConnection, galaxy);
            Thread t = new Thread(c);
            t.start();
        } catch (IOException ex) {
            LOG.log(Level.SEVERE, "IO Exception while trying to handle incoming client connection", ex);
        }
    }
}

From source file:mecard.BImportCustomerLoader.java

/**
 * Runs the entire process of loading customer bimport files as a timed 
 * process such as cron or Windows scheduler.
 * @param args // w w  w .j a  v a 2 s .  c  o m
 */
public static void main(String args[]) {
    // First get the valid options
    Options options = new Options();
    // add t option c to config directory true=arg required.
    options.addOption("c", true,
            "Configuration file directory path, include all sys dependant dir seperators like '/'.");
    // add v option v for server version.
    options.addOption("v", false, "Metro server version information.");
    options.addOption("d", false, "Outputs debug information about the customer load.");
    options.addOption("U", false,
            "Execute upload of customer accounts, otherwise just cleans up the directory.");
    options.addOption("p", true,
            "Path to PID file. If present back off and wait for reschedule customer load.");
    options.addOption("a", false, "Maximum age of PID file before warning (in minutes).");
    try {
        // parse the command line.
        CommandLineParser parser = new BasicParser();
        CommandLine cmd;
        cmd = parser.parse(options, args);
        if (cmd.hasOption("v")) {
            System.out.println("Metro (MeCard) server version " + PropertyReader.VERSION);
            return; // don't run if user just wants version.
        }
        if (cmd.hasOption("U")) {
            uploadCustomers = true;
        }
        if (cmd.hasOption("p")) // location of the pidFile, default is current directory (relative to jar location).
        {
            pidDir = cmd.getOptionValue("p");
            if (pidDir.endsWith(File.separator) == false) {
                pidDir += File.separator;
            }
        }
        if (cmd.hasOption("d")) // debug.
        {
            debug = true;
        }
        if (cmd.hasOption("a")) {
            try {
                maxPIDAge = Integer.parseInt(cmd.getOptionValue("a"));
            } catch (NumberFormatException e) {
                System.out.println("*Warning: the value used on the '-a' flag, '" + cmd.getOptionValue("a")
                        + "' cannot be " + "converted to an integer and is therefore an illegal value for "
                        + "maximum PID file age. Maximum PID age set to: " + maxPIDAge + " minutes.");
            }
        }
        // get c option value
        String configDirectory = cmd.getOptionValue("c");
        PropertyReader.setConfigDirectory(configDirectory);
        BImportCustomerLoader loader = new BImportCustomerLoader();
        loader.run();
    } catch (ParseException ex) {
        String msg = new Date()
                + "Unable to parse command line option. Please check your service configuration.";
        if (debug) {
            System.out.println("DEBUG: request for invalid command line option.");
        }
        Logger.getLogger(MetroService.class.getName()).log(Level.SEVERE, msg, ex);
        System.exit(899); // 799 for mecard
    } catch (NumberFormatException ex) {
        String msg = new Date() + "Request for invalid -a command line option.";
        if (debug) {
            System.out.println("DEBUG: request for invalid -a command line option.");
            System.out.println("DEBUG: value set to " + maxPIDAge);
        }
        Logger.getLogger(MetroService.class.getName()).log(Level.WARNING, msg, ex);
    }
    System.exit(0);
}

From source file:DaytimeServer.java

public static void main(String args[]) {
    try { // Handle startup exceptions at the end of this block
        // Get an encoder for converting strings to bytes
        CharsetEncoder encoder = Charset.forName("US-ASCII").newEncoder();

        // Allow an alternative port for testing with non-root accounts
        int port = 13; // RFC867 specifies this port.
        if (args.length > 0)
            port = Integer.parseInt(args[0]);

        // The port we'll listen on
        SocketAddress localport = new InetSocketAddress(port);

        // Create and bind a tcp channel to listen for connections on.
        ServerSocketChannel tcpserver = ServerSocketChannel.open();
        tcpserver.socket().bind(localport);

        // Also create and bind a DatagramChannel to listen on.
        DatagramChannel udpserver = DatagramChannel.open();
        udpserver.socket().bind(localport);

        // Specify non-blocking mode for both channels, since our
        // Selector object will be doing the blocking for us.
        tcpserver.configureBlocking(false);
        udpserver.configureBlocking(false);

        // The Selector object is what allows us to block while waiting
        // for activity on either of the two channels.
        Selector selector = Selector.open();

        // Register the channels with the selector, and specify what
        // conditions (a connection ready to accept, a datagram ready
        // to read) we'd like the Selector to wake up for.
        // These methods return SelectionKey objects, which we don't
        // need to retain in this example.
        tcpserver.register(selector, SelectionKey.OP_ACCEPT);
        udpserver.register(selector, SelectionKey.OP_READ);

        // This is an empty byte buffer to receive emtpy datagrams with.
        // If a datagram overflows the receive buffer size, the extra bytes
        // are automatically discarded, so we don't have to worry about
        // buffer overflow attacks here.
        ByteBuffer receiveBuffer = ByteBuffer.allocate(0);

        // Now loop forever, processing client connections
        for (;;) {
            try { // Handle per-connection problems below
                // Wait for a client to connect
                selector.select();//w  w w.  ja v  a2 s .c  om

                // If we get here, a client has probably connected, so
                // put our response into a ByteBuffer.
                String date = new java.util.Date().toString() + "\r\n";
                ByteBuffer response = encoder.encode(CharBuffer.wrap(date));

                // Get the SelectionKey objects for the channels that have
                // activity on them. These are the keys returned by the
                // register() methods above. They are returned in a
                // java.util.Set.
                Set keys = selector.selectedKeys();

                // Iterate through the Set of keys.
                for (Iterator i = keys.iterator(); i.hasNext();) {
                    // Get a key from the set, and remove it from the set
                    SelectionKey key = (SelectionKey) i.next();
                    i.remove();

                    // Get the channel associated with the key
                    Channel c = (Channel) key.channel();

                    // Now test the key and the channel to find out
                    // whether something happend on the TCP or UDP channel
                    if (key.isAcceptable() && c == tcpserver) {
                        // A client has attempted to connect via TCP.
                        // Accept the connection now.
                        SocketChannel client = tcpserver.accept();
                        // If we accepted the connection successfully,
                        // the send our respone back to the client.
                        if (client != null) {
                            client.write(response); // send respone
                            client.close(); // close connection
                        }
                    } else if (key.isReadable() && c == udpserver) {
                        // A UDP datagram is waiting. Receive it now,
                        // noting the address it was sent from.
                        SocketAddress clientAddress = udpserver.receive(receiveBuffer);
                        // If we got the datagram successfully, send
                        // the date and time in a response packet.
                        if (clientAddress != null)
                            udpserver.send(response, clientAddress);
                    }
                }
            } catch (java.io.IOException e) {
                // This is a (hopefully transient) problem with a single
                // connection: we log the error, but continue running.
                // We use our classname for the logger so that a sysadmin
                // can configure logging for this server independently
                // of other programs.
                Logger l = Logger.getLogger(DaytimeServer.class.getName());
                l.log(Level.WARNING, "IOException in DaytimeServer", e);
            } catch (Throwable t) {
                // If anything else goes wrong (out of memory, for example)
                // then log the problem and exit.
                Logger l = Logger.getLogger(DaytimeServer.class.getName());
                l.log(Level.SEVERE, "FATAL error in DaytimeServer", t);
                System.exit(1);
            }
        }
    } catch (Exception e) {
        // This is a startup error: there is no need to log it;
        // just print a message and exit
        System.err.println(e);
        System.exit(1);
    }
}

From source file:puma.central.pdp.CentralPUMAPDP.java

public static void main(String[] args) {
    // initialize log4j
    BasicConfigurator.configure();//from   w w  w  .  j av a  2s . co m

    CommandLineParser parser = new BasicParser();
    Options options = new Options();
    options.addOption("ph", "policy-home", true,
            "The folder where to find the policy file given with the given policy id. "
                    + "For default operation, this folder should contain the central PUMA policy (called "
                    + CENTRAL_PUMA_POLICY_FILENAME + ")");
    options.addOption("pid", "policy-id", true,
            "The id of the policy to be evaluated on decision requests. Default value: " + GLOBAL_PUMA_POLICY_ID
                    + ")");
    options.addOption("s", "log-disabled", true, "Verbose mode (true/false)");
    String policyHome = "";
    String policyId = "";

    // read command line
    try {
        CommandLine line = parser.parse(options, args);
        if (line.hasOption("help")) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("Simple PDP Test", options);
            return;
        }
        if (line.hasOption("policy-home")) {
            policyHome = line.getOptionValue("policy-home");
        } else {
            logger.log(Level.WARNING, "Incorrect arguments given.");
            return;
        }
        if (line.hasOption("log-disabled") && Boolean.parseBoolean(line.getOptionValue("log-disabled"))) {
            logger.log(Level.INFO, "Now switching to silent mode");
            LogManager.getLogManager().getLogger("").setLevel(Level.WARNING);
            //LogManager.getLogManager().reset();
        }
        if (line.hasOption("policy-id")) {
            policyId = line.getOptionValue("policy-id");
        } else {
            logger.log(Level.INFO, "Using default policy id: " + GLOBAL_PUMA_POLICY_ID);
            policyId = GLOBAL_PUMA_POLICY_ID;
        }
    } catch (ParseException e) {
        logger.log(Level.WARNING, "Incorrect arguments given.", e);
        return;
    }

    //
    // STARTUP THE RMI SERVER
    //      
    // if (System.getSecurityManager() == null) {
    // System.setSecurityManager(new SecurityManager());
    // }
    final CentralPUMAPDP pdp;
    try {
        pdp = new CentralPUMAPDP(policyHome, policyId);
    } catch (IOException e) {
        logger.log(Level.SEVERE, "FAILED to set up the CentralPUMAPDP. Quitting.", e);
        return;
    }

    try {
        Registry registry;
        try {
            registry = LocateRegistry.createRegistry(RMI_REGISITRY_PORT);
            logger.info("Created new RMI registry");
        } catch (RemoteException e) {
            // MDC: I hope this means the registry already existed.
            registry = LocateRegistry.getRegistry(RMI_REGISITRY_PORT);
            logger.info("Reusing existing RMI registry");
        }
        CentralPUMAPDPRemote stub = (CentralPUMAPDPRemote) UnicastRemoteObject.exportObject(pdp, 0);
        registry.bind(CENTRAL_PUMA_PDP_RMI_NAME, stub);
        logger.info(
                "Central PUMA PDP up and running (available using RMI with name \"central-puma-pdp\" on RMI registry port "
                        + RMI_REGISITRY_PORT + ")");
        Thread.sleep(100); // MDC: vroeger eindigde de Thread om n of andere reden, dit lijkt te werken...
    } catch (Exception e) {
        logger.log(Level.SEVERE, "FAILED to set up PDP as RMI server", e);
    }

    //
    // STARTUP THE THRIFT PEP SERVER
    //
    //logger.log(Level.INFO, "Not setting up the Thrift server");

    // set up server
    //      PEPServer handler = new PEPServer(new CentralPUMAPEP(pdp));
    //      RemotePEPService.Processor<PEPServer> processor = new RemotePEPService.Processor<PEPServer>(handler);
    //      TServerTransport serverTransport;
    //      try {
    //         serverTransport = new TServerSocket(THRIFT_PEP_PORT);
    //      } catch (TTransportException e) {
    //         e.printStackTrace();
    //         return;
    //      }
    //      TServer server = new TSimpleServer(new TServer.Args(serverTransport).processor(processor));
    //      System.out.println("Setting up the Thrift PEP server on port " + THRIFT_PEP_PORT);
    //      server.serve();
    //
    // STARTUP THE THRIFT PEP SERVER
    //
    //logger.log(Level.INFO, "Not setting up the Thrift server");

    // set up server
    // do this in another thread not to block the main thread
    new Thread(new Runnable() {
        @Override
        public void run() {
            RemotePDPService.Processor<CentralPUMAPDP> pdpProcessor = new RemotePDPService.Processor<CentralPUMAPDP>(
                    pdp);
            TServerTransport pdpServerTransport;
            try {
                pdpServerTransport = new TServerSocket(THRIFT_PDP_PORT);
            } catch (TTransportException e) {
                e.printStackTrace();
                return;
            }
            TServer pdpServer = new TThreadPoolServer(
                    new TThreadPoolServer.Args(pdpServerTransport).processor(pdpProcessor));
            logger.info("Setting up the Thrift PDP server on port " + THRIFT_PDP_PORT);
            pdpServer.serve();
        }
    }).start();
}

From source file:com.bluemarsh.jswat.console.Main.java

/**
 * Kicks off the application./*from  w w w.j a  v  a2 s  .c  o  m*/
 *
 * @param  args  the command line arguments.
 */
public static void main(String[] args) {
    //
    // An attempt was made early on to use the Console class in java.io,
    // but that is not designed to handle asynchronous output from
    // multiple threads, so we just use the usual System.out for output
    // and System.in for input. Note that automatic flushing is used to
    // ensure output is shown in a timely fashion.
    //

    //
    // Where console mode seems to work:
    // - bash
    // - emacs
    //
    // Where console mode does not seem to work:
    // - NetBeans: output from event listeners is never shown and the
    //   cursor sometimes lags behind the output
    //

    // Turn on flushing so printing the prompt will flush
    // all buffered output generated from other threads.
    PrintWriter output = new PrintWriter(System.out, true);

    // Make sure we have the JPDA classes.
    try {
        Bootstrap.virtualMachineManager();
    } catch (NoClassDefFoundError ncdfe) {
        output.println(NbBundle.getMessage(Main.class, "MSG_Main_NoJPDA"));
        System.exit(1);
    }

    // Ensure we can create the user directory by requesting the
    // platform service. Simply asking for it has the desired effect.
    PlatformProvider.getPlatformService();

    // Define the logging configuration.
    LogManager manager = LogManager.getLogManager();
    InputStream is = Main.class.getResourceAsStream("logging.properties");
    try {
        manager.readConfiguration(is);
    } catch (IOException ioe) {
        ioe.printStackTrace();
        System.exit(1);
    }

    // Print out some useful debugging information.
    logSystemDetails();

    // Add a shutdown hook to make sure we exit cleanly.
    Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {

        @Override
        public void run() {
            // Save the command aliases.
            CommandParser parser = CommandProvider.getCommandParser();
            parser.saveSettings();
            // Save the runtimes to persistent storage.
            RuntimeManager rm = RuntimeProvider.getRuntimeManager();
            rm.saveRuntimes();
            // Save the sessions to persistent storage and have them
            // close down in preparation to exit.
            SessionManager sm = SessionProvider.getSessionManager();
            sm.saveSessions(true);
        }
    }));

    // Initialize the command parser and load the aliases.
    CommandParser parser = CommandProvider.getCommandParser();
    parser.loadSettings();
    parser.setOutput(output);

    // Create an OutputAdapter to display debuggee output.
    OutputAdapter adapter = new OutputAdapter(output);
    SessionManager sessionMgr = SessionProvider.getSessionManager();
    sessionMgr.addSessionManagerListener(adapter);
    // Create a SessionWatcher to monitor the session status.
    SessionWatcher swatcher = new SessionWatcher();
    sessionMgr.addSessionManagerListener(swatcher);
    // Create a BreakpointWatcher to monitor the breakpoints.
    BreakpointWatcher bwatcher = new BreakpointWatcher();
    sessionMgr.addSessionManagerListener(bwatcher);

    // Add the watchers and adapters to the open sessions.
    Iterator<Session> iter = sessionMgr.iterateSessions();
    while (iter.hasNext()) {
        Session s = iter.next();
        s.addSessionListener(adapter);
        s.addSessionListener(swatcher);
    }

    // Find and run the RC file.
    try {
        runStartupFile(parser, output);
    } catch (IOException ioe) {
        logger.log(Level.SEVERE, null, ioe);
    }

    // Process command line arguments.
    try {
        processArguments(args);
    } catch (ParseException pe) {
        // Report the problem and keep going.
        System.err.println("Option parsing failed: " + pe.getMessage());
        logger.log(Level.SEVERE, null, pe);
    }

    // Display a helpful greeting.
    output.println(NbBundle.getMessage(Main.class, "MSG_Main_Welcome"));
    if (jdbEmulationMode) {
        output.println(NbBundle.getMessage(Main.class, "MSG_Main_Jdb_Emulation"));
    }

    // Enter the main loop of processing user input.
    BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
    while (true) {
        // Keep the prompt format identical to jdb for compatibility
        // with emacs and other possible wrappers.
        output.print("> ");
        output.flush();
        try {
            String command = input.readLine();
            // A null value indicates end of stream.
            if (command != null) {
                performCommand(output, parser, command);
            }
            // Sleep briefly to give the event processing threads,
            // and the automatic output flushing, a chance to catch
            // up before printing the input prompt again.
            Thread.sleep(250);
        } catch (InterruptedException ie) {
            logger.log(Level.WARNING, null, ie);
        } catch (IOException ioe) {
            logger.log(Level.SEVERE, null, ioe);
            output.println(NbBundle.getMessage(Main.class, "ERR_Main_IOError", ioe));
        } catch (Exception x) {
            // Don't ever let an internal bug (e.g. in the command parser)
            // hork the console, as it really irritates people.
            logger.log(Level.SEVERE, null, x);
            output.println(NbBundle.getMessage(Main.class, "ERR_Main_Exception", x));
        }
    }
}

From source file:Main.java

static void sendLogMessages() {
    logger.log(Level.WARNING, "message 1!", new A());
    logger.log(Level.WARNING, "message 2!", new B());
}

From source file:SimpleFilter.java

static void sendLogMessages() {
    logger.log(Level.WARNING, "A duck in the house!", new Duck());
    logger.log(Level.WARNING, "A Wombat at large!", new Wombat());
}

From source file:com.clank.launcher.Launcher.java

/**
 * Bootstrap./*from   ww  w  . j a v a  2s .c  o m*/
 *
 * @param args args
 */
public static void main(String[] args) {
    SimpleLogFormatter.configureGlobalLogger();

    LauncherArguments options = new LauncherArguments();
    try {
        new JCommander(options, args);
    } catch (ParameterException e) {
        System.err.print(e.getMessage());
        System.exit(1);
        return;
    }

    Integer bsVersion = options.getBootstrapVersion();
    log.info(bsVersion != null ? "Bootstrap version " + bsVersion + " detected" : "Not bootstrapped");

    File dir = options.getDir();
    if (dir != null) {
        log.info("Using given base directory " + dir.getAbsolutePath());
    } else {
        dir = new File(".");
        log.info("Using current directory " + dir.getAbsolutePath());
    }

    final File baseDir = dir;

    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            try {
                UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                UIManager.getDefaults().put("SplitPane.border", BorderFactory.createEmptyBorder());
                Launcher launcher = new Launcher(baseDir);
                new LauncherFrame(launcher).setVisible(true);
            } catch (Throwable t) {
                log.log(Level.WARNING, "Load failure", t);
                SwingHelper.showErrorDialog(null,
                        "Uh oh! The updater couldn't be opened because a " + "problem was encountered.",
                        "Launcher error", t);
            }
        }
    });

}

From source file:com.ontologycentral.ldspider.LDSpider_LogUtil.java

public static void setDefaultLogging() {
    Logger.getLogger("").setLevel(Level.WARNING);
    // Suppress silly cookie warnings.
    Logger.getLogger("org.apache.commons.httpclient").setLevel(Level.SEVERE);
    Logger.getLogger("").getHandlers()[0].setLevel(Level.ALL);
}