Example usage for java.util.logging Level OFF

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

Introduction

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

Prototype

Level OFF

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

Click Source Link

Document

OFF is a special level that can be used to turn off logging.

Usage

From source file:com.biggerbytes.scheduleupdates.Main.java

/**
 * //from   w w  w.ja  v  a 2 s  . co  m
 * @param args
 * @throws IOException 
 */
public static void main(String[] args) throws IOException {
    java.util.logging.Logger.getLogger("com.gargoylesoftware").setLevel(Level.OFF); // In order to remove all the log warnings, THANK GOD IT IS THAT SIMPLE
    final int PORT = 25565;
    ServerSocket serverSocket = null;

    // Logger initialization 
    if (LOG) {
        fh = new FileHandler("serv_log.log", true); //It will create a new file everytime we start the server because the previous log is locked, I am not really sure where to close the handler.
        logger.addHandler(fh);
        SimpleFormatter formatter = new SimpleFormatter();
        fh.setFormatter(formatter);
    }
    //        /* Dummy Test */
    //        List<Byte> command = new ArrayList<>();
    //        command.add(CommandConstants.SCEHDULES_HEADER);
    //        command.add(CommandConstants.ADD_SUB_DUMMY);
    //        command.add((byte) 24);
    //        command.addAll(Arrays.asList(ArrayUtils.toObject("05".getBytes())));
    //        command.addAll(Arrays.asList(ArrayUtils.toObject("20.03.2016".getBytes())));
    //        command.addAll(Arrays.asList(ArrayUtils.toObject(" ".getBytes())));
    //        System.out.println("Size is " + command.size());
    //        byte[] commandArr = new byte[command.size()];
    //        for (int i = 0; i < commandArr.length; ++i)
    //            commandArr[i] = command.get(i);
    //        CommandProcessor.executeCommand(commandArr);
    /* Dummy Test End - TESTED, IT WORKS*/

    /* Dummy removal */
    //        byte[] remvCommand = new byte[3];
    //        remvCommand[0] = CommandConstants.SCEHDULES_HEADER;
    //        remvCommand[1] = CommandConstants.REMOVE_ALL_DUMMIES_FROM_ID;
    //        remvCommand[2] = (byte) 24;
    //        
    //        CommandProcessor.executeCommand(remvCommand);
    //        /* Dummy removal end - TESTED, WORKS*/

    try {
        serverSocket = new ServerSocket(PORT);
        initDataRefreshThread();
        infoReadThread.start();
    } catch (Exception e) {
        if (LOG)
            logger.info("Couldn't listen on port " + PORT);
        System.exit(-1);
    }

    new CreateClientThread().start(); //Setup thread for creating threads for clients

    while (true) {
        System.out.println("waiting");
        if (LOG)
            logger.info("Waiting for a client."); //TODO wait for the server to finish loading data then start waiting for a client
        Socket clientSocket = serverSocket.accept();
        clientsQ.add(clientSocket);
    }
}

From source file:com.github.thesmartenergy.sparql.generate.generator.CMDGenerator.java

public static void main(String[] args) {

    List<String> formats = Arrays.asList("TTL", "TURTLE", "NTRIPLES", "TRIG", "RDFXML", "JSONLD");

    try {/*w w  w. j  a va  2  s  . co m*/
        CommandLine cl = CMDConfigurations.parseArguments(args);

        String query = "";
        String outputFormat = "TTL";

        if (cl.getArgList().size() == 0) {
            CMDConfigurations.displayHelp();
            return;
        }

        fileManager = FileManager.makeGlobal();
        if (cl.hasOption('l')) {
            Enumeration<String> loggers = LogManager.getLogManager().getLoggerNames();
            while (loggers.hasMoreElements()) {
                java.util.logging.Logger element = LogManager.getLogManager().getLogger(loggers.nextElement());
                element.setLevel(Level.OFF);
            }
            Logger.getRootLogger().setLevel(org.apache.log4j.Level.OFF);

        }
        LOG = Logger.getLogger(CMDGenerator.class);

        //get query file path
        //check if the file exists
        if (cl.hasOption("qf")) {
            String file_path = cl.getOptionValue("qf");
            File f = new File(file_path);
            if (f.exists() && !f.isDirectory()) {
                FileInputStream fisTargetFile = new FileInputStream(f);
                query = IOUtils.toString(fisTargetFile, "UTF-8");
                LOG.debug("\n\nRead SPARQL-Generate Query ..\n" + query + "\n\n");
            } else {
                LOG.error("File " + file_path + " not found.");
            }
        }

        //get query string
        if (cl.hasOption("qs")) {
            query = cl.getOptionValue("qs");
        }
        System.out.println("Query:" + query);

        //get and validate the output format
        if (cl.hasOption("f")) {
            String format = cl.getOptionValue("f");
            if (formats.contains(format)) {
                outputFormat = format;
            } else {
                LOG.error("Invalid output format," + cl.getOptionProperties("f").getProperty("description"));
                return;
            }
        }

        Model configurationModel = null;
        String conf = "";
        if (cl.hasOption("c")) {
            conf = cl.getOptionValue("c");
            configurationModel = ProcessQuery.generateConfiguration(conf);
        }

        String output = ProcessQuery.process(query, conf, outputFormat);
        System.out.println(output);

    } catch (org.apache.commons.cli.ParseException ex) {
        LOG.error(ex);
    } catch (FileNotFoundException ex) {
        LOG.error(ex);
    } catch (IOException ex) {
        LOG.error(ex);
    }

}

From source file:de.burlov.amazon.s3.dirsync.CLI.java

/**
 * @param args//w  ww. j a  v a2s  .  c  om
 */
@SuppressWarnings("static-access")
public static void main(String[] args) {
    Logger.getLogger("").setLevel(Level.OFF);
    Logger deLogger = Logger.getLogger("de");
    deLogger.setLevel(Level.INFO);
    Handler handler = new ConsoleHandler();
    handler.setFormatter(new VerySimpleFormatter());
    deLogger.addHandler(handler);
    deLogger.setUseParentHandlers(false);
    //      if (true)
    //      {
    //         LogFactory.getLog(CLI.class).error("test msg", new Exception("test extception"));
    //         return;
    //      }
    Options opts = new Options();
    OptionGroup gr = new OptionGroup();

    /*
     * Befehlsgruppe initialisieren
     */
    gr = new OptionGroup();
    gr.setRequired(true);
    gr.addOption(OptionBuilder.withArgName("up|down").hasArg()
            .withDescription("Upload/Download changed or new files").create(CMD_UPDATE));
    gr.addOption(OptionBuilder.withArgName("up|down").hasArg()
            .withDescription("Upload/Download directory snapshot").create(CMD_SNAPSHOT));
    gr.addOption(OptionBuilder.withDescription("Delete remote folder").create(CMD_DELETE_DIR));
    gr.addOption(OptionBuilder.withDescription("Delete a bucket").create(CMD_DELETE_BUCKET));
    gr.addOption(OptionBuilder.create(CMD_HELP));
    gr.addOption(OptionBuilder.create(CMD_VERSION));
    gr.addOption(OptionBuilder.withDescription("Prints summary for stored data").create(CMD_SUMMARY));
    gr.addOption(OptionBuilder.withDescription("Clean up orphaned objekts").create(CMD_CLEANUP));
    gr.addOption(OptionBuilder.withDescription("Changes encryption password").withArgName("new password")
            .hasArg().create(CMD_CHANGE_PASSWORD));
    gr.addOption(OptionBuilder.withDescription("Lists all buckets").create(CMD_LIST_BUCKETS));
    gr.addOption(OptionBuilder.withDescription("Lists raw objects in a bucket").create(CMD_LIST_BUCKET));
    gr.addOption(OptionBuilder.withDescription("Lists files in remote folder").create(CMD_LIST_DIR));
    opts.addOptionGroup(gr);
    /*
     * Parametergruppe initialisieren
     */
    opts.addOption(OptionBuilder.withArgName("key").isRequired(false).hasArg().withDescription("S3 access key")
            .create(OPT_S3S_KEY));
    opts.addOption(OptionBuilder.withArgName("secret").isRequired(false).hasArg()
            .withDescription("Secret key for S3 account").create(OPT_S3S_SECRET));
    opts.addOption(OptionBuilder.withArgName("bucket").isRequired(false).hasArg().withDescription(
            "Optional bucket name for storage. If not specified then an unique bucket name will be generated")
            .create(OPT_BUCKET));
    // opts.addOption(OptionBuilder.withArgName("US|EU").hasArg().
    // withDescription(
    // "Where the new bucket should be created. Default US").create(
    // OPT_LOCATION));
    opts.addOption(OptionBuilder.withArgName("path").isRequired(false).hasArg()
            .withDescription("Local directory path").create(OPT_LOCAL_DIR));
    opts.addOption(OptionBuilder.withArgName("name").isRequired(false).hasArg()
            .withDescription("Remote directory name").create(OPT_REMOTE_DIR));
    opts.addOption(OptionBuilder.withArgName("password").isRequired(false).hasArg()
            .withDescription("Encryption password").create(OPT_ENC_PASSWORD));
    opts.addOption(OptionBuilder.withArgName("patterns").hasArgs()
            .withDescription("Comma separated exclude file patterns like '*.tmp,*/dir/*.tmp'")
            .create(OPT_EXCLUDE_PATTERNS));
    opts.addOption(OptionBuilder.withArgName("patterns").hasArgs().withDescription(
            "Comma separated include patterns like '*.java'. If not specified, then all files in specified local directory will be included")
            .create(OPT_INCLUDE_PATTERNS));

    if (args.length == 0) {
        printUsage(opts);
        return;
    }

    CommandLine cmd = null;
    try {
        cmd = new GnuParser().parse(opts, args);
        if (cmd.hasOption(CMD_HELP)) {
            printUsage(opts);
            return;
        }
        if (cmd.hasOption(CMD_VERSION)) {
            System.out.println("s3dirsync version " + Version.CURRENT_VERSION);
            return;
        }
        String awsKey = cmd.getOptionValue(OPT_S3S_KEY);
        String awsSecret = cmd.getOptionValue(OPT_S3S_SECRET);
        String bucket = cmd.getOptionValue(OPT_BUCKET);
        String bucketLocation = cmd.getOptionValue(OPT_LOCATION);
        String localDir = cmd.getOptionValue(OPT_LOCAL_DIR);
        String remoteDir = cmd.getOptionValue(OPT_REMOTE_DIR);
        String password = cmd.getOptionValue(OPT_ENC_PASSWORD);
        String exclude = cmd.getOptionValue(OPT_EXCLUDE_PATTERNS);
        String include = cmd.getOptionValue(OPT_INCLUDE_PATTERNS);

        if (StringUtils.isBlank(awsKey) || StringUtils.isBlank(awsSecret)) {
            System.out.println("S3 account data required");
            return;
        }

        if (StringUtils.isBlank(bucket)) {
            bucket = awsKey + ".dirsync";
        }

        if (cmd.hasOption(CMD_DELETE_BUCKET)) {
            if (StringUtils.isBlank(bucket)) {
                System.out.println("Bucket name required");
                return;
            }
            int deleted = S3Utils.deleteBucket(awsKey, awsSecret, bucket);
            System.out.println("Deleted objects: " + deleted);
            return;
        }
        if (cmd.hasOption(CMD_LIST_BUCKETS)) {
            for (String str : S3Utils.listBuckets(awsKey, awsSecret)) {
                System.out.println(str);
            }
            return;
        }
        if (cmd.hasOption(CMD_LIST_BUCKET)) {
            if (StringUtils.isBlank(bucket)) {
                System.out.println("Bucket name required");
                return;
            }
            for (String str : S3Utils.listObjects(awsKey, awsSecret, bucket)) {
                System.out.println(str);
            }
            return;
        }
        if (StringUtils.isBlank(password)) {
            System.out.println("Encryption password required");
            return;
        }
        char[] psw = password.toCharArray();
        DirSync ds = new DirSync(awsKey, awsSecret, bucket, bucketLocation, psw);
        ds.setExcludePatterns(parseSubargumenths(exclude));
        ds.setIncludePatterns(parseSubargumenths(include));
        if (cmd.hasOption(CMD_SUMMARY)) {
            ds.printStorageSummary();
            return;
        }
        if (StringUtils.isBlank(remoteDir)) {
            System.out.println("Remote directory name required");
            return;
        }
        if (cmd.hasOption(CMD_DELETE_DIR)) {
            ds.deleteFolder(remoteDir);
            return;
        }
        if (cmd.hasOption(CMD_LIST_DIR)) {
            Folder folder = ds.getFolder(remoteDir);
            if (folder == null) {
                System.out.println("No such folder found: " + remoteDir);
                return;
            }
            for (Map.Entry<String, FileInfo> entry : folder.getIndexData().entrySet()) {
                System.out.println(entry.getKey() + " ("
                        + FileUtils.byteCountToDisplaySize(entry.getValue().getLength()) + ")");
            }
            return;
        }
        if (cmd.hasOption(CMD_CLEANUP)) {
            ds.cleanUp();
            return;
        }
        if (cmd.hasOption(CMD_CHANGE_PASSWORD)) {
            String newPassword = cmd.getOptionValue(CMD_CHANGE_PASSWORD);
            if (StringUtils.isBlank(newPassword)) {
                System.out.println("new password required");
                return;
            }
            char[] chars = newPassword.toCharArray();
            ds.changePassword(chars);
            newPassword = null;
            Arrays.fill(chars, ' ');
            return;
        }
        if (StringUtils.isBlank(localDir)) {
            System.out.println(OPT_LOCAL_DIR + " argument required");
            return;
        }
        String direction = "";
        boolean up = false;
        boolean snapshot = false;
        if (StringUtils.isNotBlank(cmd.getOptionValue(CMD_UPDATE))) {
            direction = cmd.getOptionValue(CMD_UPDATE);
        } else if (StringUtils.isNotBlank(cmd.getOptionValue(CMD_SNAPSHOT))) {
            direction = cmd.getOptionValue(CMD_SNAPSHOT);
            snapshot = true;
        }
        if (StringUtils.isBlank(direction)) {
            System.out.println("Operation direction required");
            return;
        }
        up = StringUtils.equalsIgnoreCase(OPT_UP, direction);
        File baseDir = new File(localDir);
        if (!baseDir.exists() && !baseDir.mkdirs()) {
            System.out.println("Invalid local directory: " + baseDir.getAbsolutePath());
            return;
        }
        ds.syncFolder(baseDir, remoteDir, up, snapshot);

    } catch (DirSyncException e) {
        System.out.println(e.getMessage());
        e.printStackTrace();
    } catch (ParseException e) {
        System.out.println(e.getMessage());
        printUsage(opts);

    } catch (Exception e) {
        e.printStackTrace(System.err);
    }
}

From source file:de.pniehus.odal.App.java

public static void main(String[] args) throws IOException {
    List<Filter> filters = new ArrayList<Filter>();
    filters.add(new RegexFilter());
    filters.add(new FileTypeFilter());
    filters.add(new KeywordFilter());
    filters.add(new BlacklistFilter());
    Profile p = parseArgs(args, filters);

    String fileName = "log-" + new Date().toString().replace(":", "-") + ".txt";
    fileName = fileName.replace(" ", "-");
    File logPath = new File(p.getLogDirectory() + fileName);

    if (!logPath.getParentFile().isDirectory() && !logPath.getParentFile().mkdirs()) {
        logPath = new File(fileName);
    }// w w w .  j ava  2  s.c om

    if (logPath.getParentFile().canWrite() || logPath.getParentFile().setWritable(true)) {
        SimpleLoggingSetup.configureRootLogger(logPath.getAbsolutePath(), p.getLogLevel(), !p.isSilent());
    } else {
        Logger root = Logger.getLogger("");

        for (Handler h : root.getHandlers()) { // Removing default console handlers
            if (h instanceof ConsoleHandler) {
                root.removeHandler(h);
            }
        }

        ConsolePrintLogHandler cplh = new ConsolePrintLogHandler();
        cplh.setFormatter(new ScribblerLogFormat(SimpleLoggingSetup.DEFAULT_DATE_FORMAT));
        root.addHandler(cplh);

        System.out.println("Unable to create log: insufficient permissions!");

    }

    Logger.getLogger("").setLevel(p.getLogLevel());
    mainLogger = Logger.getLogger(App.class.getCanonicalName());
    untrustedSSLSetup();
    mainLogger.info("Successfully intitialized ODAL");
    if (!p.isLogging())
        mainLogger.setLevel(Level.OFF);
    if (p.isWindowsConsoleMode() && !p.isLogging()) {
        Logger root = Logger.getLogger("");
        for (Handler h : root.getHandlers()) {
            if (h instanceof FileHandler) {
                root.removeHandler(h); // Removes FileHandler to allow console output through logging
            }
        }
    }
    OdalGui ogui = new OdalGui(p, filters);
}

From source file:io.mesosphere.mesos.frameworks.cassandra.framework.Main.java

public static void main(final String[] args) {
    int status;//from   w  w w. ja  va  2 s . c  o  m
    try {
        final Handler[] handlers = LogManager.getLogManager().getLogger("").getHandlers();
        for (final Handler handler : handlers) {
            handler.setLevel(Level.OFF);
        }
        org.slf4j.LoggerFactory.getLogger("slf4j-logging").debug("Installing SLF4JLogging");
        SLF4JBridgeHandler.install();
        status = _main();
    } catch (final SystemExitException e) {
        LOGGER.error(e.getMessage());
        status = e.status;
    } catch (final UnknownHostException e) {
        LOGGER.error("Unable to resolve local interface for http server");
        status = 6;
    } catch (final Throwable e) {
        LOGGER.error("Unhandled fatal exception", e);
        status = 10;
    }

    System.exit(status);
}

From source file:com.guye.baffle.obfuscate.Main.java

public static void main(String[] args) throws IOException, BaffleException {
    Options opt = new Options();

    opt.addOption("c", "config", true, "config file path,keep or mapping");

    opt.addOption("o", "output", true, "output mapping writer file");

    opt.addOption("v", "verbose", false, "explain what is being done.");

    opt.addOption("h", "help", false, "print help for the command.");

    opt.getOption("c").setArgName("file list");

    opt.getOption("o").setArgName("file path");

    String formatstr = "baffle [-c/--config filepaths list ][-o/--output filepath][-h/--help] ApkFile TargetApkFile";

    HelpFormatter formatter = new HelpFormatter();
    CommandLineParser parser = new PosixParser();
    CommandLine cl = null;/*from ww  w . j a  va 2s  .  co  m*/
    try {
        // ?Options?
        cl = parser.parse(opt, args);

    } catch (ParseException e) {
        formatter.printHelp(formatstr, opt); // ???
        return;
    }

    if (cl == null || cl.getArgs() == null || cl.getArgs().length == 0) {
        formatter.printHelp(formatstr, opt);
        return;
    }

    // ?-h--help??
    if (cl.hasOption("h")) {
        HelpFormatter hf = new HelpFormatter();
        hf.printHelp(formatstr, "", opt, "");
        return;
    }

    // ???DirectoryName
    String[] str = cl.getArgs();
    if (str == null || str.length != 2) {
        HelpFormatter hf = new HelpFormatter();
        hf.printHelp("not specify apk file or taget apk file", opt);
        return;
    }

    if (str[1].equals(str[0])) {
        HelpFormatter hf = new HelpFormatter();
        hf.printHelp("apk file can not rewrite , please specify new target file", opt);
        return;
    }
    File apkFile = new File(str[0]);
    if (!apkFile.exists()) {
        HelpFormatter hf = new HelpFormatter();
        hf.printHelp("apk file not exists", opt);
        return;
    }

    File[] configs = null;
    if (cl.hasOption("c")) {
        String cfg = cl.getOptionValue("c");
        String[] fs = cfg.split(",");
        int len = fs.length;
        configs = new File[fs.length];
        for (int i = 0; i < len; i++) {
            configs[i] = new File(fs[i]);
            if (!configs[i].exists()) {
                HelpFormatter hf = new HelpFormatter();
                hf.printHelp("config file " + fs[i] + " not exists", opt);
                return;
            }
        }
    }

    File mappingfile = null;
    if (cl.hasOption("o")) {
        String mfile = cl.getOptionValue("o");
        mappingfile = new File(mfile);

        if (mappingfile.getParentFile() != null) {
            mappingfile.getParentFile().mkdirs();
        }

    }

    if (cl.hasOption('v')) {
        Logger.getLogger(Obfuscater.LOG_NAME).setLevel(Level.CONFIG);
    } else {
        Logger.getLogger(Obfuscater.LOG_NAME).setLevel(Level.OFF);
    }

    Logger.getLogger(Obfuscater.LOG_NAME).addHandler(new ConsoleHandler());

    Obfuscater obfuscater = new Obfuscater(configs, mappingfile, apkFile, str[1]);

    obfuscater.obfuscate();
}

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

public static void main(String[] args) {
    // load language
    try {/* w  w  w  . j  a va2 s  .  com*/
        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:pt.ua.tm.neji.web.cli.WebMain.java

public static void main(String[] args) {

    // Set JSP to use Standard JavaC always
    System.setProperty("org.apache.jasper.compiler.disablejsr199", "false");

    CommandLineParser parser = new GnuParser();
    Options options = new Options();

    options.addOption("h", "help", false, "Print this usage information.");
    options.addOption("v", "verbose", false, "Verbose mode.");
    options.addOption("d", "dictionaires", true, "Folder that contains the dictionaries.");
    options.addOption("m", "models", true, "Folder that contains the ML models.");

    options.addOption("port", "port", true, "Server port.");
    options.addOption("c", "configuration", true, "Configuration properties file.");

    options.addOption("t", "threads", true,
            "Number of threads. By default, if more than one core is available, it is the number of cores minus 1.");

    CommandLine commandLine;/*from  w  w w  . j  a va 2  s  .c o  m*/
    try {
        // Parse the program arguments
        commandLine = parser.parse(options, args);
    } catch (ParseException ex) {
        logger.error("There was a problem processing the input arguments.", ex);
        return;
    }

    // Show help text
    if (commandLine.hasOption('h')) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(150, "./nejiWeb.sh " + USAGE, HEADER, options, FOOTER);
        return;
    }

    // Get threads
    int numThreads = Runtime.getRuntime().availableProcessors() - 1;
    numThreads = numThreads > 0 ? numThreads : 1;
    if (commandLine.hasOption('t')) {
        String threadsText = commandLine.getOptionValue('t');
        numThreads = Integer.parseInt(threadsText);
        if (numThreads <= 0 || numThreads > 32) {
            logger.error("Illegal number of threads. Must be between 1 and 32.");
            return;
        }
    }

    // Get port
    int port = 8010;
    if (commandLine.hasOption("port")) {
        String portString = commandLine.getOptionValue("port");
        port = Integer.parseInt(portString);
    }

    // Get configuration
    String configurationFile = null;
    Properties configurationProperties = null;
    if (commandLine.hasOption("configuration")) {
        configurationFile = commandLine.getOptionValue("configuration");
        try {
            configurationProperties = new Properties();
            configurationProperties.load(new FileInputStream(configurationFile));
        } catch (IOException e) {
            configurationProperties = null;
        }
    }
    if (configurationProperties != null && !configurationProperties.isEmpty()) {
        ServerConfiguration.initialize(configurationProperties);
    } else {
        ServerConfiguration.initialize();
    }

    // Set system proxy
    if (!ServerConfiguration.getInstance().getProxyURL().isEmpty()
            && !ServerConfiguration.getInstance().getProxyPort().isEmpty()) {
        System.setProperty("https.proxyHost", ServerConfiguration.getInstance().getProxyURL());
        System.setProperty("https.proxyPort", ServerConfiguration.getInstance().getProxyPort());
        System.setProperty("http.proxyHost", ServerConfiguration.getInstance().getProxyURL());
        System.setProperty("http.proxyPort", ServerConfiguration.getInstance().getProxyPort());

        if (!ServerConfiguration.getInstance().getProxyUsername().isEmpty()) {
            final String proxyUser = ServerConfiguration.getInstance().getProxyUsername();
            final String proxyPassword = ServerConfiguration.getInstance().getProxyPassword();
            System.setProperty("https.proxyUser", proxyUser);
            System.setProperty("https.proxyPassword", proxyPassword);
            System.setProperty("http.proxyUser", proxyUser);
            System.setProperty("http.proxyPassword", proxyPassword);
            Authenticator.setDefault(new Authenticator() {
                @Override
                public PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(proxyUser, proxyPassword.toCharArray());
                }
            });
        }
    }

    // Get verbose mode
    boolean verbose = commandLine.hasOption('v');
    Constants.verbose = verbose;

    if (Constants.verbose) {
        MalletLogger.getGlobal().setLevel(Level.INFO);
        // Redirect sout
        LoggingOutputStream los = new LoggingOutputStream(LoggerFactory.getLogger("stdout"), false);
        System.setOut(new PrintStream(los, true));

        // Redirect serr
        los = new LoggingOutputStream(LoggerFactory.getLogger("sterr"), true);
        System.setErr(new PrintStream(los, true));
    } else {
        MalletLogger.getGlobal().setLevel(Level.OFF);
    }

    // Get dictionaries folder
    String dictionariesFolder = null;
    if (commandLine.hasOption('d')) {
        dictionariesFolder = commandLine.getOptionValue('d');

        File test = new File(dictionariesFolder);
        if (!test.isDirectory() || !test.canRead()) {
            logger.error("The specified dictionaries path is not a folder or is not readable.");
            return;
        }
        dictionariesFolder = test.getAbsolutePath();
        dictionariesFolder += File.separator;
    }

    // Get models folder
    String modelsFolder = null;
    if (commandLine.hasOption('m')) {
        modelsFolder = commandLine.getOptionValue('m');

        File test = new File(modelsFolder);
        if (!test.isDirectory() || !test.canRead()) {
            logger.error("The specified models path is not a folder or is not readable.");
            return;
        }
        modelsFolder = test.getAbsolutePath();
        modelsFolder += File.separator;
    }

    // Redirect JUL to SLF4
    SLF4JBridgeHandler.removeHandlersForRootLogger();
    SLF4JBridgeHandler.install();

    // Output formats (All)
    List<OutputFormat> outputFormats = new ArrayList<>();
    outputFormats.add(OutputFormat.A1);
    outputFormats.add(OutputFormat.B64);
    outputFormats.add(OutputFormat.BC2);
    outputFormats.add(OutputFormat.BIOC);
    outputFormats.add(OutputFormat.CONLL);
    outputFormats.add(OutputFormat.JSON);
    outputFormats.add(OutputFormat.NEJI);
    outputFormats.add(OutputFormat.PIPE);
    outputFormats.add(OutputFormat.PIPEXT);
    outputFormats.add(OutputFormat.XML);

    // Context is built through a descriptor first, so that the pipeline can be validated before any processing
    ContextConfiguration descriptor = null;
    try {
        descriptor = new ContextConfiguration.Builder().withInputFormat(InputFormat.RAW) // HARDCODED
                .withOutputFormats(outputFormats).withParserTool(ParserTool.GDEP)
                .withParserLanguage(ParserLanguage.ENGLISH).withParserLevel(ParserLevel.CHUNKING).build();

    } catch (NejiException ex) {
        ex.printStackTrace();
        System.exit(1);
    }

    // Create resources dirs if they don't exist
    try {
        File dictionariesDir = new File(DICTIONARIES_PATH);
        File modelsDir = new File(MODELS_PATH);
        if (!dictionariesDir.exists()) {
            dictionariesDir.mkdirs();
            (new File(dictionariesDir, "_priority")).createNewFile();
        }
        if (!modelsDir.exists()) {
            modelsDir.mkdirs();
            (new File(modelsDir, "_priority")).createNewFile();
        }
    } catch (IOException ex) {
        ex.printStackTrace();
        System.exit(1);
    }

    // Contenxt
    Context context = new Context(descriptor, MODELS_PATH, DICTIONARIES_PATH);

    // Start server
    try {
        Server server = Server.getInstance();
        server.initialize(context, port, numThreads);

        server.start();
        logger.info("Server started at localhost:{}", port);
        logger.info("Press Cmd-C / Ctrl+C to shutdown the server...");

        server.join();

    } catch (Exception ex) {
        ex.printStackTrace();
        logger.info("Shutting down the server...");
    }
}

From source file:com.punyal.medusaserver.californiumServer.core.MedusaValidation.java

public static Client check(String medusaServerAddress, String myTicket, String ticket) {
    CoapClient coapClient = new CoapClient();
    Logger.getLogger("org.eclipse.californium.core.network.CoAPEndpoint").setLevel(Level.OFF);
    Logger.getLogger("org.eclipse.californium.core.network.EndpointManager").setLevel(Level.OFF);
    Logger.getLogger("org.eclipse.californium.core.network.stack.ReliabilityLayer").setLevel(Level.OFF);

    CoapResponse response;// www  . ja  va 2 s. c om

    coapClient.setURI(medusaServerAddress + "/" + MEDUSA_SERVER_VALIDATION_SERVICE_NAME);
    JSONObject json = new JSONObject();
    json.put(JSON_MY_TICKET, myTicket);
    json.put(JSON_TICKET, ticket);
    response = coapClient.put(json.toString(), 0);

    if (response != null) {
        //System.out.println(response.getResponseText());

        try {
            json.clear();
            json = (JSONObject) JSONValue.parse(response.getResponseText());
            long expireTime = (Long) json.get(JSON_TIME_TO_EXPIRE) + (new Date()).getTime();
            String userName = json.get(JSON_USER_NAME).toString();
            String[] temp = json.get(JSON_ADDRESS).toString().split("/");
            String address;
            if (temp[1] != null)
                address = temp[1];
            else
                address = "0.0.0.0";
            Client client = new Client(InetAddress.getByName(address), userName, null,
                    UnitConversion.hexStringToByteArray(ticket), expireTime);
            return client;
        } catch (Exception e) {
        }

    } else {
        // TODO: take 
    }
    return null;
}

From source file:com.wegas.app.IntegrationTest.java

@BeforeClass
public static void setUpClass() throws Exception {
    BootstrapProperties bootstrapProperties = new BootstrapProperties();
    //bootstrapProperties.setInstallRoot("./src/test/glassfish");           // Only for glassfish-embedded-staticshell

    GlassFishProperties glassfishProperties = new GlassFishProperties();
    glassfishProperties.setPort("https-listener", 5353);
    glassfishProperties.setPort("http-listener", 5454);
    //glassfishProperties.setInstanceRoot("./src/test/glassfish/domains/domain1");
    glassfishProperties.setConfigFileURI(
            (new File("./src/test/glassfish/domains/domain1/config/domain.xml")).toURI().toString());
    //glassfishProperties.setConfigFileReadOnly(false);
    TestHelper.resetTestDB();//  www  .  ja v  a 2  s.  co m
    glassfish = GlassFishRuntime.bootstrap(bootstrapProperties).newGlassFish(glassfishProperties);
    Logger.getLogger("javax.enterprise.system.tools.deployment").setLevel(Level.OFF);
    Logger.getLogger("javax.enterprise.system").setLevel(Level.OFF);
    glassfish.start();

    //File war = new File("./target/Wegas.war");
    //appName = glassfish.getDeployer().deploy(war, "--name=Wegas", "--contextroot=Wegas", "--force=true");
    // deployer.deploy(war);
    ScatteredArchive archive = new ScatteredArchive("Wegas", ScatteredArchive.Type.WAR,
            new File("./target/embed-war/"));
    archive.addClassPath(new File("./target/classes/")); // target/classes directory contains complied servlets
    archive.addClassPath(new File("../wegas-core/target/classes")); // wegas-core dependency
    //archive.addClassPath(new File("../wegas-core/target/wegas-core_1.0-SNAPSHOT.jar"));// wegas-core dependency
    //archive.addMetadata(new File("./src/main/webapp/WEB-INF", "web.xml"));// resources/sun-web.xml is the WEB-INF/sun-web.xml
    //archive.addMetadata(new File("./src/main/webapp/test", "web.xml"));   // resources/web.xml is the WEB-INF/web.xml
    appName = glassfish.getDeployer().deploy(archive.toURI(), "--contextroot=Wegas"); // Deploy the scattered web archive.

    setBaseUrl("http://localhost:5454/Wegas");
}