Example usage for java.lang Thread Thread

List of usage examples for java.lang Thread Thread

Introduction

In this page you can find the example usage for java.lang Thread Thread.

Prototype

public Thread() 

Source Link

Document

Allocates a new Thread object.

Usage

From source file:com.github.brandtg.switchboard.FileLogAggregator.java

/** Main. */
public static void main(String[] args) throws Exception {
    Options opts = new Options();
    opts.addOption("h", "help", false, "Prints help message");
    opts.addOption("f", "file", true, "File to output aggregated logs to");
    opts.addOption("s", "separator", true, "Line separator in log");
    CommandLine cli = new GnuParser().parse(opts, args);

    if (cli.getArgs().length == 0 || cli.hasOption("help")) {
        new HelpFormatter().printHelp("usage: [opts] sourceHost:port ...", opts);
        System.exit(1);//ww  w .  j  av a2s .  co  m
    }

    // Parse sources
    Set<InetSocketAddress> sources = new HashSet<>();
    for (int i = 0; i < cli.getArgs().length; i++) {
        String[] tokens = cli.getArgs()[i].split(":");
        sources.add(new InetSocketAddress(tokens[0], Integer.valueOf(tokens[1])));
    }

    // Parse output stream
    OutputStream outputStream;
    if (cli.hasOption("file")) {
        outputStream = new FileOutputStream(cli.getOptionValue("file"));
    } else {
        outputStream = System.out;
    }

    // Separator
    String separator = cli.getOptionValue("separator", "\n");
    if (separator.length() != 1) {
        throw new IllegalArgumentException("Separator must only be 1 character");
    }

    final FileLogAggregator fileLogAggregator = new FileLogAggregator(sources, separator.charAt(0),
            outputStream);

    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            try {
                fileLogAggregator.stop();
            } catch (Exception e) {
                LOG.error("Error when stopping log aggregator", e);
            }
        }
    });

    fileLogAggregator.start();
}

From source file:com.splout.db.dnode.DNode.java

public static void main(String[] args) throws Exception {
    SploutConfiguration config;//from www. j a v  a 2  s .co  m
    if (args.length == 1) {
        // config root
        config = SploutConfiguration.get(args[0]);
    } else {
        config = SploutConfiguration.get();
    }
    final DNode dnode = new DNode(config, new DNodeHandler());
    // Add shutdown hook
    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            try {
                log.info("Shutdown hook called - trying to gently stop DNode ...");
                dnode.stop();
            } catch (Throwable e) {
                log.error("Error in ShutdownHook", e);
            }
        }
    });
    dnode.init();
}

From source file:com.mgmtp.perfload.perfmon.PerfMon.java

public static void main(final String[] args) {
    CommandLine cmd = parseArgs(args);//  ww w. jav  a2s.com

    if (cmd != null) {
        final Sigar sigar = new Sigar();
        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                sigar.close();
            }
        });

        if (cmd.hasOption('s')) {
            shutdown(sigar);
            return;
        }

        long interval = Long.parseLong(cmd.getOptionValue('i', "5"));
        String fileName = cmd.getOptionValue('f');
        boolean java = cmd.hasOption('j');
        boolean tcp = cmd.hasOption('t');
        boolean netstat = cmd.hasOption('n');

        OutputHandler outputHandler = fileName != null ? new FileOutputHandler(fileName)
                : new ConsoleOutputHandler();
        try {
            outputHandler.open();

            // Initialize Sigar libraries in order to fail fast.
            // Lazy initialization would cause perfMon to keep running logging errors all the time.
            // See https://github.com/mgm-tp/perfload/issues/3
            Sigar.load();

            SigarProxy sigarProxy = SigarProxyCache.newInstance(sigar);
            List<BasePerfMonCommand> commands = createCommandsList(java, tcp, netstat);
            final PerfMon perfMon = new PerfMon(sigarProxy, interval, commands, outputHandler);

            Runtime.getRuntime().addShutdownHook(new Thread() {
                @Override
                public void run() {
                    perfMon.runShutdownHook();
                }
            });

            perfMon.writeHeader();
            perfMon.scheduleInformationGathering();
        } catch (IOException ex) {
            LOG.error("Error opening output file: " + fileName, ex);
        } catch (SigarException ex) {
            LOG.error(ex.getMessage(), ex);
        }
    }
}

From source file:jackrabbit.app.App.java

public static void main(String[] args) {
    if (args.length == 0 || args.length == 1 && args[0].equals("-h")) {
        System.out.println("Usage: java -jar ackrabbit-migration-query-tool-" + VERSION
                + "-jar-with-dependencies.jar "
                + "--src src --src-conf conf [--src-repo-path path] [--src-user src_user] [--src-passwd src_pw] "
                + "[--dest-user dest_user] [--dest-passwd dest_pw] [--dest dest] [--dest-conf conf] [--dest-repo-path path] "
                + "[--cnd cnd] [--node-limit limit] " + "[--query-type type] [--query query]");
        System.out.println("\t --src source repository directory");
        System.out.println("\t --src-conf source repository configuration file");
        System.out.println("\t --src-repo-path path to source node to copy from; default is \"/\"");
        System.out.println("\t --src-user source repository login");
        System.out.println("\t --src-passwd source repository password");
        System.out.println("\t --dest destination repository directory");
        System.out.println("\t --dest-conf destination repository configuration file");
        System.out.println("\t --dest-repo-path path to destination node to copy to; default is \"/\"");
        System.out.println("\t --dest-user destination repository login");
        System.out.println("\t --dest-passwd destination repository password");
        System.out.println(/*  ww  w  . j a  v a2s.  c o  m*/
                "\t --node-limit size to partition nodes with before copying. If it is not supplied, no partitioning is performed");
        System.out.println("\t --cnd common node type definition file");
        System.out.println(
                "\t --query query to run in src. If --query is specified, then --dest, --dest-conf, --dest-repo-path and --cnd will be ignored.");
        System.out.println("\t --query-type query type (sql, xpath, JCR-SQL2); default is JCR-SQL2");
        return;
    }
    for (int i = 0; i < args.length; i = i + 2) {
        if (args[i].equals("--src") && i + 1 < args.length) {
            srcRepoDir = args[i + 1];
        } else if (args[i].equals("--dest") && i + 1 < args.length) {
            destRepoDir = args[i + 1];
        } else if (args[i].equals("--src-conf") && i + 1 < args.length) {
            srcConf = args[i + 1];
        } else if (args[i].equals("--dest-conf") && i + 1 < args.length) {
            destConf = args[i + 1];
        } else if (args[i].equals("--src-repo-path") && i + 1 < args.length) {
            srcRepoPath = args[i + 1];
        } else if (args[i].equals("--dest-repo-path") && i + 1 < args.length) {
            destRepoPath = args[i + 1];
        } else if (args[i].equals("--src-user") && i + 1 < args.length) {
            srcUser = args[i + 1];
        } else if (args[i].equals("--src-passwd") && i + 1 < args.length) {
            srcPasswd = args[i + 1];
        } else if (args[i].equals("--dest-user") && i + 1 < args.length) {
            destUser = args[i + 1];
        } else if (args[i].equals("--dest-passwd") && i + 1 < args.length) {
            destPasswd = args[i + 1];
        } else if (args[i].equals("--node-limit") && i + 1 < args.length) {
            nodeLimit = Long.parseLong(args[i + 1]);
        } else if (args[i].equals("--cnd") && i + 1 < args.length) {
            cndPath = args[i + 1];
        } else if (args[i].equals("--query") && i + 1 < args.length) {
            query = args[i + 1];
        } else if (args[i].equals("--query-type") && i + 1 < args.length) {
            queryType = args[i + 1];
        }
    }
    boolean missingArgs = false;

    if (srcRepoDir.isEmpty()) {
        missingArgs = true;
        log.error("Please specify the --src option.");
    }
    if (destRepoDir.isEmpty() && !destConf.isEmpty()) {
        missingArgs = true;
        log.error("Please specify the --dest option.");
    }
    if (srcConf.isEmpty()) {
        missingArgs = true;
        log.error("Please specify the --src-conf option.");
    }
    if (destConf.isEmpty() && !destRepoDir.isEmpty()) {
        missingArgs = true;
        log.error("Please specify the --dest-conf option.");
    }

    if (missingArgs)
        return;

    SimpleCredentials credentials = new SimpleCredentials(srcUser, srcPasswd.toCharArray());
    SimpleCredentials destCredentials = new SimpleCredentials(destUser, destPasswd.toCharArray());

    JackrabbitRepository dest = null;
    RepositoryFactory destRf = null;
    RepositoryFactory srcRf = new RepositoryFactoryImpl(srcConf, srcRepoDir);
    if (!destConf.isEmpty()) {
        destRf = new RepositoryFactoryImpl(destConf, destRepoDir);
    }

    try {
        final JackrabbitRepository src = srcRf.getRepository();
        SessionFactory srcSf = new SessionFactoryImpl(src, credentials);
        final Session srcSession = srcSf.getSession();
        Runtime.getRuntime().addShutdownHook(new Thread() {
            public void run() {
                srcSession.logout();
                src.shutdown();
            }
        });
        if (destConf.isEmpty()) {//query mode
            BufferedReader in = new BufferedReader(new InputStreamReader(System.in, "UTF-8"));
            if (query.isEmpty()) {
                while (true) {
                    System.out.print(">");
                    String line = in.readLine();
                    if (line == null || line.isEmpty() || line.equalsIgnoreCase("quit")
                            || line.equalsIgnoreCase("exit")) {
                        break;
                    }
                    try {
                        runQuery(srcSession, line, queryType);
                    } catch (RepositoryException e) {
                        log.error(e.getMessage(), e);
                    }
                }
            } else {
                try {
                    runQuery(srcSession, query, queryType);
                } catch (RepositoryException e) {
                    log.error(e.getMessage(), e);
                }
            }
            return;
        }

        dest = destRf.getRepository();
        SessionFactory destSf = new SessionFactoryImpl(dest, destCredentials);
        Session destSession = destSf.getSession();

        try {
            RepositoryManager.registerCustomNodeTypes(destSession, cndPath);
            if (nodeLimit == 0)
                NodeCopier.copy(srcSession, destSession, srcRepoPath, destRepoPath, true);
            else
                NodeCopier.copy(srcSession, destSession, srcRepoPath, destRepoPath, nodeLimit, true);
            log.info("Copying " + srcSession.getWorkspace().getName() + " to "
                    + destSession.getWorkspace().getName() + " for " + srcRepoDir + " done.");
        } catch (ParseException e) {
            log.error(e.getMessage(), e);
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        } catch (PathNotFoundException e) {
            log.error(e.getMessage(), e);
        } catch (RepositoryException e) {
            log.error(e.getMessage(), e);
        }

        List<String> destWkspaces = RepositoryManager.getDestinationWorkspaces(srcSession, destSession);

        for (String workspace : destWkspaces) {
            Session wsSession = srcSf.getSession(workspace);
            Session wsDestSession = destSf.getSession(workspace);
            try {
                RepositoryManager.registerCustomNodeTypes(wsDestSession, cndPath);
                if (nodeLimit == 0)
                    NodeCopier.copy(wsSession, wsDestSession, srcRepoPath, destRepoPath, true);
                else {
                    NodeCopier.copy(wsSession, wsDestSession, srcRepoPath, destRepoPath, nodeLimit, true);
                }
                log.info("Copying " + wsSession.getWorkspace().getName() + " to "
                        + wsDestSession.getWorkspace().getName() + " for " + srcRepoDir + " done.");
            } catch (IOException e) {
                log.error(e.getMessage(), e);
            } catch (ParseException e) {
                log.error(e.getMessage(), e);
            } catch (PathNotFoundException e) {
                log.error(e.getMessage(), e);
            } catch (RepositoryException e) {
                log.error(e.getMessage(), e);
            } finally {
                wsSession.logout();
                wsDestSession.logout();
            }
        }
    } catch (IOException e) {
        log.error(e.getMessage(), e);
    } catch (PathNotFoundException e) {
        log.error(e.getMessage(), e);
    } catch (RepositoryException e) {
        log.error(e.getMessage(), e);
    } finally {
        if (dest != null)
            dest.shutdown();
    }
}

From source file:fr.iphc.grid.jobmanager.JobManager.java

/**
 * @param args/*from   ww w . j  a  v a2 s  .c  o  m*/
 */
public static void main(String[] args) throws Exception {
    JobManager command = new JobManager();
    CommandLine line = command.parse(args);
    ArrayList<File> JdlList = new ArrayList<File>();
    Global.getOutputexecutor = Executors.newFixedThreadPool(10);
    Initialize init = new Initialize();
    String SetupFile = "setup_vigrid.xml";

    if (line.hasOption(OPT_SETUP)) {
        SetupFile = line.getOptionValue(OPT_SETUP);
    }
    if ((new File(SetupFile).isFile())) {
        init.GlobalSetup(SetupFile);
    }
    // Init Job
    if (line.hasOption(OPT_JOB)) {
        File file = new File(line.getOptionValue(OPT_JOB));
        if ((file.isFile())) {
            JdlList.add(file);
        } else {
            System.err.println("The file " + file + " doesn't exist");
            System.exit(-1);
        }
    } else {
        File file = new File(line.getOptionValue(OPT_FILEJOB));
        if ((file.isFile())) {
            JdlList = init.InitJdl(file);
        } else {
            System.err.println("The file " + file + " doesn't exist");
            System.exit(-1);
        }
    }
    if (line.hasOption(OPT_WAIT)) {
        Global.TIMEOUTWAIT = Integer.parseInt(line.getOptionValue(OPT_WAIT));
    }
    if (line.hasOption(OPT_RUN)) {
        Global.TIMEOUTRUN = Integer.parseInt(line.getOptionValue(OPT_RUN));
    }
    if (line.hasOption(OPT_END)) {
        Global.TIMEOUTEND = Integer.parseInt(line.getOptionValue(OPT_END));
    }
    if (line.hasOption(OPT_LOGDISPLAY)) {
        Global.SEUILDISPLAYLOG = Float.parseFloat(line.getOptionValue(OPT_LOGDISPLAY));
    }
    init.InitJob(JdlList);
    // Init Url Ce
    if (line.hasOption(OPT_QUEUE)) {
        Global.file = new File(line.getOptionValue(OPT_QUEUE));
    }
    if (line.hasOption(OPT_BAD)) {
        Global.BadCe = new File(line.getOptionValue(OPT_BAD));
    }
    if (line.hasOption(OPT_OPTIMIZETIMEOUTRUN)) {
        Global.OPTTIMEOUTRUN = false;
    }
    if (line.hasOption(OPT_CWD)) {
        File theDir = new File(line.getOptionValue(OPT_CWD));
        if (!theDir.exists()) {
            if (!theDir.mkdirs()) {
                System.err.println("Working directory create failed: " + line.getOptionValue(OPT_CWD));
                System.exit(-1);
            }
        }
        Global.Cwd = line.getOptionValue(OPT_CWD);
    } else {
        Global.Cwd = System.getProperty("user.dir");
    }
    if (!(new File(Global.Cwd)).canWrite()) {
        System.err.println(" Write permission denied : " + Global.Cwd);
        System.exit(-1);
    }
    System.out.println("Current working directory : " + Global.Cwd);
    Date start = new Date();
    init.PrintGlobalSetup();
    init.InitUrl(Global.file);
    init.InitSosCe();
    init.rmLoadFailed(Global.Cwd + "/loadFailed.txt");
    System.out.println("CE: " + Global.ListUrl.size() + " Nb JOB: " + Global.ListJob.size() + " " + new Date());
    if (Global.ListJob.size() < 6) { // pour obtenir rapport de 0.8
        Global.OPTTIMEOUTRUN = false;
    }
    // check if we can connect to the grid
    try {
        SessionFactory.createSession(true);
    } catch (NoSuccessException e) {
        System.err.println("Could not connect to the grid at all (" + e.getMessage() + ")");
        System.err.println("Aborting");
        System.exit(0);

    }
    // Launch Tread Job
    JobThread st = new JobThread(Global.ListJob, Global.ListUrl);
    st.start();
    LoggingThread logst = new LoggingThread(Global.ListJob, Global.ListUrl, Global.SEUILDISPLAYLOG);
    logst.start();
    // create Thread Hook intercept kill +CNTL+C
    Thread hook = new Thread() {
        public void run() {
            try {
                for (Jdl job : Global.ListJob) {
                    if (job.getJobId() != null) {
                        JobThread.jobCancel(job.getJobId());
                    }
                }
            } catch (Exception e) {
                System.err.println("Thread Hook:\n" + e.getMessage());
            }
            // give it a change to display final job state
            try {
                sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    };
    Runtime.getRuntime().addShutdownHook(hook);

    //      Integer timer = 180 * 60 * 1000;
    Date now = new Date();

    //      Boolean Fin = false;
    while ((!Global.END) && ((now.getTime() - start.getTime()) < Global.TIMEOUTEND * 60 * 1000)) { // TOEND
        // en
        // minutes
        now = new Date();
        // int mb = 1024*1024;
        // Getting the runtime reference from system
        // Runtime runtime = Runtime.getRuntime();
        // System.out.println("##### Heap utilization statistics [MB]
        // #####");
        // Print used memory
        // System.out.println("Used Memory:"
        // + (runtime.totalMemory() - runtime.freeMemory()) / mb);

        // Print free memory
        // System.out.println("Free Memory:"
        // + runtime.freeMemory() / mb);

        // Print total available memory
        // System.out.println("Total Memory:" + runtime.totalMemory() / mb);

        // Print Maximum available memory
        // System.out.println("Max Memory:" + runtime.maxMemory() / mb);
        // // System.out.println("NB: "+nb_end);
        // if ((float)(runtime.totalMemory() -
        // runtime.freeMemory())/(float)runtime.maxMemory() > (float)0.3){
        // System.out.println ("GC: "+(float)(runtime.totalMemory() -
        // runtime.freeMemory())/runtime.maxMemory());
        // System.gc();
        // };
        sleep(15 * 1000); // in ms

        // System.gc();
        // Fin=true;
        // for (Jdl job : Global.ListJob) {
        // if (job.getJob() != null) {
        // System.out.println("JOB: "+job.getId()+"\t"+job.getStatus());
        // if (job.getStatus().compareTo("END")==0){
        // ((JobImpl) job.getJob()).postStagingAndCleanup();
        // System.out.println("END JOB: "+job.getId());
        // job.setStatus("END");
        // }
        // if (job.getStatus().compareTo("END")!=0){
        // Fin=false;
        // }
        // System.out.println("JOB: "+job.getId()+"\t"+job.getStatus() +
        // "\t"+job.getFail()+"\t"+job.getNodeCe());
        // }
        // }
        // while ((Global.END==0) && ((new
        // Date().getTime()-start.getTime())<timer)){
    }
    // Boolean end_load=false;
    // while (!end_load){
    // end_load=true;
    // for(Jdl job:Global.ListJob){
    // if (job.getStatus().equals("LOAD")){
    // end_load=false;
    // }
    // }
    // }
    System.out.println("END JOB: " + now);
    st.halt();
    logst.halt();
    Iterator<Url> k = Global.ListUrl.iterator();
    while (k.hasNext()) {
        Url url = k.next();
        System.out.println("URL: " + url.getUrl());
    }
    Iterator<Jdl> m = Global.ListJob.iterator();
    while (m.hasNext()) {
        Jdl job = m.next();
        System.out.println(
                "JOB: " + job.getId() + "\t" + job.getFail() + "\t" + job.getStatus() + "\t" + job.getNodeCe());
    }
    System.out.println(start + " " + new Date());
    System.exit(0);
}

From source file:MiniCluster.java

/**
 * Runs the {@link MiniAccumuloCluster} given a -p argument with a property file. Establishes a shutdown port for asynchronous operation.
 * //from  w w  w  .  j a  v  a  2s.co  m
 * @param args
 *          An optional -p argument can be specified with the path to a valid properties file.
 */
public static void main(String[] args) throws Exception {
    Opts opts = new Opts();
    opts.parseArgs(MiniCluster.class.getName(), args);

    if (opts.printProps) {
        printProperties();
        System.exit(0);
    }

    int shutdownPort = 4445;

    final File miniDir;

    if (opts.prop.containsKey(DIRECTORY_PROP))
        miniDir = new File(opts.prop.getProperty(DIRECTORY_PROP));
    else
        miniDir = Files.createTempDir();

    String rootPass = opts.prop.containsKey(ROOT_PASSWORD_PROP) ? opts.prop.getProperty(ROOT_PASSWORD_PROP)
            : "secret";
    String instanceName = opts.prop.containsKey(INSTANCE_NAME_PROP) ? opts.prop.getProperty(INSTANCE_NAME_PROP)
            : "accumulo";
    MiniAccumuloConfig config = new MiniAccumuloConfig(miniDir, instanceName, rootPass);

    if (opts.prop.containsKey(NUM_T_SERVERS_PROP))
        config.setNumTservers(Integer.parseInt(opts.prop.getProperty(NUM_T_SERVERS_PROP)));
    if (opts.prop.containsKey(ZOO_KEEPER_PORT_PROP))
        config.setZooKeeperPort(Integer.parseInt(opts.prop.getProperty(ZOO_KEEPER_PORT_PROP)));
    //    if (opts.prop.containsKey(JDWP_ENABLED_PROP))
    //      config.setJDWPEnabled(Boolean.parseBoolean(opts.prop.getProperty(JDWP_ENABLED_PROP)));
    //    if (opts.prop.containsKey(ZOO_KEEPER_MEMORY_PROP))
    //      setMemoryOnConfig(config, opts.prop.getProperty(ZOO_KEEPER_MEMORY_PROP), ServerType.ZOOKEEPER);
    //    if (opts.prop.containsKey(TSERVER_MEMORY_PROP))
    //      setMemoryOnConfig(config, opts.prop.getProperty(TSERVER_MEMORY_PROP), ServerType.TABLET_SERVER);
    //    if (opts.prop.containsKey(MASTER_MEMORY_PROP))
    //      setMemoryOnConfig(config, opts.prop.getProperty(MASTER_MEMORY_PROP), ServerType.MASTER);
    //    if (opts.prop.containsKey(DEFAULT_MEMORY_PROP))
    //      setMemoryOnConfig(config, opts.prop.getProperty(DEFAULT_MEMORY_PROP));
    //    if (opts.prop.containsKey(SHUTDOWN_PORT_PROP))
    //      shutdownPort = Integer.parseInt(opts.prop.getProperty(SHUTDOWN_PORT_PROP));

    Map<String, String> siteConfig = new HashMap<String, String>();
    for (Map.Entry<Object, Object> entry : opts.prop.entrySet()) {
        String key = (String) entry.getKey();
        if (key.startsWith("site."))
            siteConfig.put(key.replaceFirst("site.", ""), (String) entry.getValue());
    }

    config.setSiteConfig(siteConfig);

    final MiniAccumuloCluster accumulo = new MiniAccumuloCluster(config);

    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            try {
                accumulo.stop();
                FileUtils.deleteDirectory(miniDir);
                System.out.println("\nShut down gracefully on " + new Date());
            } catch (IOException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    });

    accumulo.start();

    printInfo(accumulo, shutdownPort);

    // start a socket on the shutdown port and block- anything connected to this port will activate the shutdown
    ServerSocket shutdownServer = new ServerSocket(shutdownPort);
    shutdownServer.accept();

    System.exit(0);
}

From source file:net.paissad.waqtsalat.utils.DownloadHelper.java

@Deprecated
public static void main(String[] args) throws HttpException, IOException, InterruptedException {

    final String url = "http://sourceforge.net/projects/mod-security/files/modsecurity-apache/2.6.1/modsecurity-apache_2.6.1.tar.gz/download";
    final File file = new File("test.tar.gz");

    final DownloadHelper downloader = new DownloadHelper();
    Thread t = new Thread() {
        @Override/*from  w  ww.  j ava 2s. c  om*/
        public void run() {
            try {
                downloader.download(url, file);
            } catch (Exception e) {
                logger.error("Download failed ... ", e);
            }
        }
    };
    t.start();
    // Waits 3 seconds and then cancels the download.
    Thread.sleep(3 * 1000L);
    downloader.cancel();
}

From source file:com.clustercontrol.HinemosManagerMain.java

/**
 * Hinemos Manager?main<br/>//from  w ww. ja v  a 2 s  .c  om
 * @param args
 * @throws Exception
 */
public static void main(String args[]) {

    try {
        try {
            if (System.getProperty("systime.iso") != null) {
                String oldVmName = System.getProperty("java.vm.name");

                //System?mock?????HotSpot??????????
                System.setProperty("java.vm.name", "HotSpot 64-Bit Server VM");

                Class.forName("com.clustercontrol.util.SystemTimeShifter");

                System.setProperty("java.vm.name", oldVmName);
            }
        } catch (Exception e) {
            log.error(e);
        } catch (Error e) {
            log.error(e);
        }

        long bootTime = System.currentTimeMillis();
        log.info("Hinemos Manager is starting." + " (startupMode=" + _startupMode + ", clustered="
                + _isClustered + ", locale=" + Locale.getDefault() + ")");

        // Hinemos(??????)???????
        // (???????????????????????)
        long offset = HinemosPropertyUtil.getHinemosPropertyNum("common.time.offset", Long.valueOf(0));
        HinemosTime.setTimeOffsetMillis(offset);

        // Hinemos?(UTC??)??/(??)
        int timeZoneOffset = HinemosPropertyUtil
                .getHinemosPropertyNum("common.timezone", Long.valueOf(TimeZone.getDefault().getRawOffset()))
                .intValue();
        HinemosTime.setTimeZoneOffset(timeZoneOffset);

        // ???HinemosPlugin??(create)?
        HinemosPluginService.getInstance().create();

        // ???HinemosPlugin?(activate)?
        HinemosPluginService.getInstance().activate();

        // Hinemos Manger????
        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                log.info("shutdown hook called.");
                synchronized (shutdownLock) {
                    // Hinemos Manager???
                    String[] msgArgsShutdown = { _hostname };
                    AplLogger.put(PriorityConstant.TYPE_INFO, HinemosModuleConstant.HINEMOS_MANAGER_MONITOR,
                            MessageConstant.MESSAGE_SYS_002_MNG, msgArgsShutdown);

                    // ???HinemosPlugin??(deactivate)?
                    HinemosPluginService.getInstance().deactivate();

                    // ???HinemosPlugin?(destroy)?
                    HinemosPluginService.getInstance().destroy();

                    log.info("Hinemos Manager is stopped.");

                    shutdown = true;
                    shutdownLock.notify();
                }
            }
        });

        // ??
        long startupTime = System.currentTimeMillis();
        long initializeSec = (startupTime - bootTime) / 1000;
        long initializeMSec = (startupTime - bootTime) % 1000;
        log.info("Hinemos Manager Started in " + initializeSec + "s:" + initializeMSec + "ms");

        // Hinemos Manager??
        String[] msgArgsStart = { _hostname };
        AplLogger.put(PriorityConstant.TYPE_INFO, HinemosModuleConstant.HINEMOS_MANAGER_MONITOR,
                MessageConstant.MESSAGE_SYS_001_MNG, msgArgsStart);

        // Hinemos Manager???????
        synchronized (shutdownLock) {
            while (!shutdown) {
                try {
                    shutdownLock.wait();
                } catch (InterruptedException e) {
                    log.warn("shutdown lock interrupted.", e);
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException sleepE) {
                    }
                    ;
                }
            }
        }

        System.exit(0);

    } catch (Throwable e) {
        log.error("unknown error occured.", e);
    }
}

From source file:com.maxpowered.amazon.advertising.api.app.App.java

public static void main(final String... args)
        throws FileNotFoundException, IOException, JAXBException, XMLStreamException, InterruptedException {
    try (ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("application-context.xml")) {
        /*/*from  w ww  .ja v  a 2 s . c  o  m*/
         * Get default options based on spring configs
         */
        final String inputDefault = getOptionDefaultBasedOnSpringProperty(ctx, PROPERTY_APP_INPUT, STD_IN_STR);
        final String processedDefault = inputDefault.equals(STD_IN_STR) ? DEFAULT_PROCESSED_FILE_BASE
                : inputDefault + PROCESSED_EXT;
        final String outputDefault = getOptionDefaultBasedOnSpringProperty(ctx, PROPERTY_APP_OUTPUT,
                STD_OUT_STR);
        int throttleDefault = Integer.valueOf(getOptionDefaultBasedOnSpringProperty(ctx, PROPERTY_APP_THROTTLE,
                String.valueOf(DEFAULT_APP_THROTTLE)));
        // Maximum of 25000 requests per hour
        throttleDefault = Math.min(throttleDefault, MAX_APP_THROTTLE);

        /*
         * Get options from the CLI args
         */
        final Options options = new Options();

        options.addOption("h", false, "Display this help.");
        options.addOption("i", true, "Set the file to read ASINs from. " + DEFAULT_STR + inputDefault);
        options.addOption("p", true, "Set the file to store processed ASINs in. " + DEFAULT_STR
                + processedDefault + " or '" + PROCESSED_EXT + "' appended to the input file name.");
        // Add a note that the output depends on the configured processors. If none are configured, it defaults to a
        // std.out processor
        options.addOption("o", true,
                "Set the file to write fetched info xml to via FileProcessor. " + DEFAULT_STR + outputDefault);
        options.addOption("1", false, "Override output file and always output fetched info xml to std.out.");
        options.addOption("t", true, "Set the requests per hour throttle (max of " + MAX_APP_THROTTLE + "). "
                + DEFAULT_STR + throttleDefault);

        final CommandLineParser parser = new DefaultParser();
        CommandLine cmd = null;
        boolean needsHelp = false;

        try {
            cmd = parser.parse(options, args);
        } catch (final ParseException e) {
            needsHelp = true;
        }

        if (cmd.hasOption("h") || needsHelp) {
            final HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("App", options);
            return;
        }

        // Get throttle rate
        final int throttle = Math.min(
                cmd.hasOption("t") ? Integer.valueOf(cmd.getOptionValue("t")) : throttleDefault,
                MAX_APP_THROTTLE);
        LOG.debug("Throttle (default {}) is {} requests per hour", throttleDefault, throttle);
        // We don't want to hit our limit, just under an hour worth of milliseconds
        final int requestWait = 3540000 / throttle;

        // Get input stream
        String input;
        if (cmd.hasOption("i")) {
            input = cmd.getOptionValue("i");
        } else {
            input = inputDefault;
        }
        LOG.debug("Input name (default {}) is {}", inputDefault, input);

        // Get processed file
        String processed;
        if (cmd.hasOption("p")) {
            processed = cmd.getOptionValue("p");
        } else {
            processed = input + PROCESSED_EXT;
        }
        LOG.debug("Processed file name (default {}) is {}", processedDefault, processed);
        final File processedFile = new File(processed);
        processedFile.createNewFile();

        try (final InputStream inputStream = getInputStream(input)) {

            // Get output stream
            String output;
            if (cmd.hasOption("o")) {
                output = cmd.getOptionValue("o");
            } else {
                output = outputDefault;
            }
            if (cmd.hasOption("1")) {
                output = STD_OUT_STR;
            }
            LOG.debug("Output (default {}) name is {}", outputDefault, output);
            // Special logic to set the FileProcessor output
            if (output.equals(STD_OUT_STR)) {
                final FileProcessor fileProcessor = ctx.getBeanFactory().getBean(FileProcessor.class);
                fileProcessor.setOutputStream(System.out);
            } else if (!output.equals(outputDefault)) {
                final FileProcessor fileProcessor = ctx.getBeanFactory().getBean(FileProcessor.class);
                fileProcessor.setOutputFile(output);
            }

            // This could be easily configured through CLI or properties
            final List<String> responseGroups = Lists.newArrayList();
            for (final ResponseGroup responseGroup : new ResponseGroup[] { ResponseGroup.IMAGES,
                    ResponseGroup.ITEM_ATTRIBUTES }) {
                responseGroups.add(responseGroup.getResponseGroupName());
            }
            final String responseGroupString = Joiner.on(",").join(responseGroups);

            // Search the list of remaining ASINs
            final ProductFetcher fetcher = ctx.getBeanFactory().getBean(ProductFetcher.class);
            fetcher.setProcessedFile(processedFile);
            fetcher.setRequestWait(requestWait);
            fetcher.setInputStream(inputStream);
            fetcher.setResponseGroups(responseGroupString);

            // This ensures that statistics of processed asins should almost always get printed at the end
            Runtime.getRuntime().addShutdownHook(new Thread() {
                @Override
                public void run() {
                    fetcher.logStatistics();
                }
            });

            fetcher.fetchProductInformation();
        }
    }
}

From source file:com.willwinder.universalgcodesender.ExperimentalWindow.java

/**
 * @param args the command line arguments
 *//*from www. ja va 2  s  .  c om*/
public static void main(String args[]) {

    /* Set the Nimbus look and feel */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
    /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
     */
    try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (ClassNotFoundException ex) {
        java.util.logging.Logger.getLogger(ExperimentalWindow.class.getName())
                .log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(ExperimentalWindow.class.getName())
                .log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(ExperimentalWindow.class.getName())
                .log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(ExperimentalWindow.class.getName())
                .log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>

    // Fix look and feel to use CMD+C/X/V/A instead of CTRL
    if (SystemUtils.IS_OS_MAC) {
        Collection<InputMap> ims = new ArrayList<>();
        ims.add((InputMap) UIManager.get("TextField.focusInputMap"));
        ims.add((InputMap) UIManager.get("TextArea.focusInputMap"));
        ims.add((InputMap) UIManager.get("EditorPane.focusInputMap"));
        ims.add((InputMap) UIManager.get("FormattedTextField.focusInputMap"));
        ims.add((InputMap) UIManager.get("PasswordField.focusInputMap"));
        ims.add((InputMap) UIManager.get("TextPane.focusInputMap"));

        int c = KeyEvent.VK_C;
        int v = KeyEvent.VK_V;
        int x = KeyEvent.VK_X;
        int a = KeyEvent.VK_A;
        int meta = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();

        for (InputMap im : ims) {
            im.put(KeyStroke.getKeyStroke(c, meta), DefaultEditorKit.copyAction);
            im.put(KeyStroke.getKeyStroke(v, meta), DefaultEditorKit.pasteAction);
            im.put(KeyStroke.getKeyStroke(x, meta), DefaultEditorKit.cutAction);
            im.put(KeyStroke.getKeyStroke(a, meta), DefaultEditorKit.selectAllAction);
        }
    }

    /* Create the form */
    //        GUIBackend backend = new GUIBackend();
    final ExperimentalWindow mw = new ExperimentalWindow();

    /* Apply the settings to the ExperimentalWindow bofore showing it */

    mw.setSize(mw.backend.getSettings().getMainWindowSettings().width,
            mw.backend.getSettings().getMainWindowSettings().height);
    mw.setLocation(mw.backend.getSettings().getMainWindowSettings().xLocation,
            mw.backend.getSettings().getMainWindowSettings().yLocation);

    mw.addComponentListener(new ComponentListener() {
        @Override
        public void componentResized(ComponentEvent ce) {
            mw.backend.getSettings().getMainWindowSettings().height = ce.getComponent().getSize().height;
            mw.backend.getSettings().getMainWindowSettings().width = ce.getComponent().getSize().width;
        }

        @Override
        public void componentMoved(ComponentEvent ce) {
            mw.backend.getSettings().getMainWindowSettings().xLocation = ce.getComponent().getLocation().x;
            mw.backend.getSettings().getMainWindowSettings().yLocation = ce.getComponent().getLocation().y;
        }

        @Override
        public void componentShown(ComponentEvent ce) {
        }

        @Override
        public void componentHidden(ComponentEvent ce) {
        }
    });

    /* Display the form */
    java.awt.EventQueue.invokeLater(new Runnable() {

        @Override
        public void run() {
            mw.setVisible(true);
        }
    });

    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            mw.connectionPanel.saveSettings();
            mw.commandPanel.saveSettings();

            if (mw.pendantUI != null) {
                mw.pendantUI.stop();
            }
        }
    });
}