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:fresto.datastore.EventLogWriter.java

public static void main(String[] args) throws Exception {
    if (args.length != 2) {
        LOGGER.severe("Argumests needed : <frontHost> <frontPort>");
        System.exit(1);//from   ww w.java  2  s. co m
    } else {
        frontHost = args[0];
        frontPort = args[1];
        LOGGER.info("Connecting... " + frontHost + ":" + frontPort + " with SUB");
    }

    final ZMQ.Context context = ZMQ.context(1);

    final FrestoEventQueue frestoEventQueue = new FrestoEventQueue();

    final Thread queueMonitorThread = new Thread() {
        Logger _LOGGER = Logger.getLogger("logWriteThread");

        @Override
        public void run() {
            while (work) {
                try {
                    _LOGGER.info("frestoEventQueue size = " + frestoEventQueue.size());
                    Thread.sleep(1000);
                } catch (InterruptedException ie) {
                }

            }
        }
    };

    final Thread logWriteThread = new Thread() {
        Logger _LOGGER = Logger.getLogger("logWriteThread");

        @Override
        public void run() {
            //FrestoStopWatch _watch = new FrestoStopWatch();
            //FrestoStopWatch _durationWatch = new FrestoStopWatch();

            EventLogWriter eventLogWriter = new EventLogWriter();

            // Open database
            //eventLogWriter.openTitanGraph();

            ZMQ.Socket receiver = null;
            //if("pull".equalsIgnoreCase(subOrPull)) {
            //   receiver = context.socket(ZMQ.PULL);
            //   receiver.connect("tcp://" + frontHost + ":" + frontPort);
            //} else if("sub".equalsIgnoreCase(subOrPull)) {
            receiver = context.socket(ZMQ.SUB);
            receiver.connect("tcp://" + frontHost + ":" + frontPort);
            receiver.subscribe("".getBytes());
            //} else {
            //   LOGGER.severe(subOrPull + " is not supported.");
            //   System.exit(1);
            //}

            //Consume socket data
            frestoEventQueue.setPullerSocket(receiver);
            frestoEventQueue.start();

            int waitingEventCount = 0;
            //int count = 0;
            //long elapsedTime = 0;
            //long duration = 0;

            //_durationWatch.start();

            while (work) {

                // To wait until at least one event in queue
                if (frestoEventQueue.isEmpty()) {
                    try {
                        //_LOGGER.info("FrestoEventQueue is empty. Waiting " + SLEEP_TIME + "ms...");
                        Thread.sleep(SLEEP_TIME);
                        continue;
                    } catch (InterruptedException ie) {
                    }
                }

                waitingEventCount = frestoEventQueue.size();

                for (int i = 0; i < waitingEventCount; i++) {
                    //_watch.start();
                    //count++;

                    FrestoEvent frestoEvent = frestoEventQueue.poll();

                    try {
                        eventLogWriter.writeEventData(frestoEvent.topic, frestoEvent.eventBytes);
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        //
                    }

                    //elapsedTime += _watch.stop();
                    //duration += _durationWatch.stop();

                    //if(count == maxCommitCount) {
                    //   eventLogWriter.commitGraph();
                    //   _LOGGER.info(count + " events processed for " + elapsedTime + " ms. (total time " + duration + " ms.) Remaining events " + frestoEventQueue.size());
                    //   
                    //   count = 0;
                    //   elapsedTime = 0;
                    //   duration = 0;
                    //   // Stop FOR clause
                    //}
                }

                //eventLogWriter.commitGraph();

                _LOGGER.info("Remaining events " + frestoEventQueue.size());

                //count = 0;
                //elapsedTime = 0;
                //duration = 0;
            }
            _LOGGER.info("Shutting down...");

            //if(g.isOpen()) {
            //   g.commit();
            //   g.shutdown();
            //}

            receiver.close();
            context.term();

            _LOGGER.info("Good bye.");
        }
    };

    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            System.out.println(" Interrupt received, killing logger");
            // To break while clause
            frestoEventQueue.stopWork();
            work = false;

            try {
                logWriteThread.join();
                frestoEventQueue.join();
                //queueMonitorThread.join();

            } catch (InterruptedException e) {
                //
            }
        }
    });

    //queueMonitorThread.start();
    logWriteThread.start();

}

From source file:com.amazon.kinesis.streaming.agent.Agent.java

public static void main(String[] args) throws Exception {
    AgentOptions opts = AgentOptions.parse(args);
    String configFile = opts.getConfigFile();
    AgentConfiguration config = tryReadConfigurationFile(Paths.get(opts.getConfigFile()));
    Path logFile = opts.getLogFile() != null ? Paths.get(opts.getLogFile())
            : (config != null ? config.logFile() : null);
    String logLevel = opts.getLogLevel() != null ? opts.getLogLevel()
            : (config != null ? config.logLevel() : null);
    int logMaxBackupFileIndex = (config != null ? config.logMaxBackupIndex() : -1);
    long logMaxFileSize = (config != null ? config.logMaxFileSize() : -1L);
    Logging.initialize(logFile, logLevel, logMaxBackupFileIndex, logMaxFileSize);
    final Logger logger = Logging.getLogger(Agent.class);

    // Install an unhandled exception hook
    Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
        @Override/*from  w w  w  .  ja  v a  2s . c o m*/
        public void uncaughtException(Thread t, Throwable e) {
            if (e instanceof OutOfMemoryError) {
                // This prevents the JVM from hanging in case of an OOME
                dontShutdownOnExit = true;
            }
            String msg = "FATAL: Thread " + t.getName() + " threw an unrecoverable error. Aborting application";
            try {
                try { // We don't know if logging is still working
                    logger.error(msg, e);
                } finally {
                    System.err.println(msg);
                    e.printStackTrace();
                }
            } finally {
                System.exit(1);
            }
        }
    });

    try {
        logger.info("Reading configuration from file: {}", configFile);
        if (config == null) {
            config = readConfigurationFile(Paths.get(opts.getConfigFile()));
        }
        // Initialize and start the agent
        AgentContext agentContext = new AgentContext(config);
        if (agentContext.flows().isEmpty()) {
            throw new ConfigurationException("There are no flows configured in configuration file.");
        }
        final Agent agent = new Agent(agentContext);

        // Make sure everything terminates cleanly when process is killed
        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                if (!dontShutdownOnExit && agent.isRunning()) {
                    agent.stopAsync();
                    agent.awaitTerminated();
                }
            }
        });

        agent.startAsync();
        agent.awaitRunning();
        agent.awaitTerminated();
    } catch (Exception e) {
        logger.error("Unhandled error.", e);
        System.err.println("Unhandled error.");
        e.printStackTrace();
        System.exit(1);
    }
}

From source file:fresto.datastore.titan.TitanEventWriter.java

public static void main(String[] args) throws Exception {
    if (args.length < 4) {
        LOGGER.error(//from   w  w  w.  j a  va  2 s  .co  m
                "Argumests needed : <streamer url> <storage backend> <storage hostname> <max commit count>");
        System.exit(1);
    } else {
        STREAMER_URL = args[0];
        STORAGE_BACKEND = args[1];
        STORAGE_HOSTNAME = args[2];
        try {
            MAX_COMMIT_COUNT = Integer.parseInt(args[3]);
        } catch (NumberFormatException e) {
            LOGGER.error("Commit count should be an integer");
        }
    }

    final ZMQ.Context context = ZMQ.context(1);

    final FrestoEventQueue frestoEventQueue = new FrestoEventQueue();

    final Thread queueMonitorThread = new Thread() {
        //Logger _LOGGER = Logger.getLogger("writerThread");
        @Override
        public void run() {
            while (work) {
                try {
                    LOGGER.info("frestoEventQueue size = " + frestoEventQueue.size());
                    Thread.sleep(1000);
                } catch (InterruptedException ie) {
                }

            }
        }
    };

    final Thread writerThread = new Thread() {
        //Logger _LOGGER = Logger.getLogger("writerThread");
        @Override
        public void run() {
            //StopWatch _watch = new JavaLogStopWatch(_LOGGER);
            FrestoStopWatch _watch = new FrestoStopWatch();
            FrestoStopWatch _durationWatch = new FrestoStopWatch();

            TitanEventWriter eventWriter = new TitanEventWriter();

            // Open database
            eventWriter.openTitanGraph();

            ZMQ.Socket puller = context.socket(ZMQ.PULL);
            //puller.connect("tcp://" + frontHost + ":" + frontPort);
            puller.connect(STREAMER_URL);

            //Consume socket data
            frestoEventQueue.setPullerSocket(puller);
            frestoEventQueue.start();

            int nextCommitCount = 0;
            int count = 0;
            long elapsedTime = 0;
            long duration = 0;

            _durationWatch.start();

            while (work) {

                // To wait until at least one event in queue
                if (frestoEventQueue.isEmpty()) {
                    try {
                        Thread.sleep(SLEEP_TIME);
                        continue;
                    } catch (InterruptedException ie) {
                    }
                }

                nextCommitCount = frestoEventQueue.size();

                for (int i = 0; i < nextCommitCount; i++) {
                    _watch.start();
                    count++;

                    FrestoEvent frestoEvent = frestoEventQueue.poll();

                    try {
                        eventWriter.writeEventData(frestoEvent.topic, frestoEvent.eventBytes);
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        //
                    }

                    elapsedTime += _watch.stop();
                    duration += _durationWatch.stop();

                    if (count == MAX_COMMIT_COUNT) {
                        eventWriter.commitGraph();
                        LOGGER.info(count + " events processed for " + elapsedTime + " ms. (total time "
                                + duration + " ms.) Remaining events " + frestoEventQueue.size());

                        count = 0;
                        elapsedTime = 0;
                        duration = 0;
                        // Stop FOR clause
                    }
                }

                eventWriter.commitGraph();

                LOGGER.info(count + " events processed for " + elapsedTime + " ms. (total time " + duration
                        + " ms.) Remaining events " + frestoEventQueue.size());

                count = 0;
                elapsedTime = 0;
                duration = 0;
            }
            LOGGER.info("Shutting down...");

            if (g.isOpen()) {
                g.commit();
                g.shutdown();
            }

            puller.close();
            context.term();

            LOGGER.info("Good bye.");
        }
    };

    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            System.out.println("Interrupt received, killing server");
            // To break while clause
            frestoEventQueue.stopWork();
            work = false;

            try {
                writerThread.join();
                frestoEventQueue.join();
                //queueMonitorThread.join();

            } catch (InterruptedException e) {
            }
        }
    });

    //queueMonitorThread.start();
    writerThread.start();

}

From source file:com.uber.stream.kafka.mirrormaker.manager.ManagerStarter.java

public static void main(String[] args) throws Exception {
    CommandLineParser parser = new DefaultParser();
    CommandLine cmd = parser.parse(ManagerConf.constructManagerOptions(), args);
    if (cmd.getOptions().length == 0 || cmd.hasOption("help")) {
        HelpFormatter f = new HelpFormatter();
        f.printHelp("OptionsTip", ManagerConf.constructManagerOptions());
        System.exit(0);/*from  w ww. j av  a  2 s. c  o  m*/
    }
    final ManagerStarter managerStarter = ManagerStarter.init(cmd);

    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {
            try {
                managerStarter.stop();
            } catch (Exception e) {
                LOGGER.error("Caught error during shutdown! ", e);
            }
        }
    });

    try {
        managerStarter.start();
    } catch (Exception e) {
        LOGGER.error("Cannot start uReplicator-Manager: ", e);
    }
}

From source file:de.uniwue.info6.database.SQLParserTest.java

public static void main(String[] args) throws Exception {
    String test = "Dies ist ein einfacher Test";
    System.out.println(StringTools.forgetOneWord(test));

    System.exit(0);/*from w ww .  j  av a 2 s  .  com*/
    // SimpleTupel<String, Integer> test1 =  new SimpleTupel<String, Integer>("test1", 1);
    // SimpleTupel<String, Integer> test2 =  new SimpleTupel<String, Integer>("test1", 12);

    // ArrayList<SimpleTupel<String, Integer>> test = new ArrayList<SimpleTupel<String, Integer>>();
    // test.add(test1);
    // System.out.println(test1.equals(test2));
    // System.exit(0);

    final boolean resetDb = true;
    // Falls nur nach einer bestimmten Aufgabe gesucht wird
    final Integer exerciseID = 39;
    final Integer scenarioID = null;
    final int threadSize = 1;

    final EquivalenceLock<Long[]> equivalenceLock = new EquivalenceLock<Long[]>();
    final Long[] performance = new Long[] { 0L, 0L };

    // ------------------------------------------------ //
    final ScenarioDao scenarioDao = new ScenarioDao();
    final ExerciseDao exerciseDao = new ExerciseDao();
    final ExerciseGroupDao groupDao = new ExerciseGroupDao();
    final UserDao userDao = new UserDao();
    final ArrayList<Thread> threads = new ArrayList<Thread>();

    // ------------------------------------------------ //
    try {
        ConnectionManager.offline_instance();
        if (resetDb) {
            Cfg.inst().setProp(MAIN_CONFIG, IMPORT_EXAMPLE_SCENARIO, true);
            Cfg.inst().setProp(MAIN_CONFIG, FORCE_RESET_DATABASE, true);
            new GenerateData().resetDB();
            ConnectionTools.inst().addSomeTestData();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    // ------------------------------------------------ //

    final List<Scenario> scenarios = scenarioDao.findAll();

    try {
        // ------------------------------------------------ //
        String userID;
        for (int i = 2; i < 100; i++) {
            userID = "user_" + i;
            User userToInsert = new User();
            userToInsert.setId(userID);
            userToInsert.setIsAdmin(false);
            userDao.insertNewInstance(userToInsert);
        }
        // ------------------------------------------------ //

        for (int i = 0; i < threadSize; i++) {
            Thread thread = new Thread() {

                public void run() {
                    // ------------------------------------------------ //
                    try {
                        Thread.sleep(new Random().nextInt(30));
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    // ------------------------------------------------ //

                    User user = userDao.getRandom();
                    Thread.currentThread().setName(user.getId());
                    System.err.println(
                            "\n\nINFO (ueps): Thread '" + Thread.currentThread().getName() + "' started\n");

                    // ------------------------------------------------ //

                    for (Scenario scenario : scenarios) {
                        if (scenarioID != null && !scenario.getId().equals(scenarioID)) {
                            continue;
                        }

                        System.out.println(StringUtils.repeat("#", 90));
                        System.out.println("SCENARIO: " + scenario.getId());

                        // ------------------------------------------------ //
                        for (ExerciseGroup group : groupDao.findByScenario(scenario)) {
                            System.out.println(StringUtils.repeat("#", 90));
                            System.out.println("GROUP: " + group.getId());
                            System.out.println(StringUtils.repeat("#", 90));
                            List<Exercise> exercises = exerciseDao.findByExGroup(group);

                            // ------------------------------------------------ //
                            for (Exercise exercise : exercises) {
                                if (exerciseID != null && !exercise.getId().equals(exerciseID)) {
                                    continue;
                                }
                                long startTime = System.currentTimeMillis();

                                for (int i = 0; i < 100; i++) {
                                    String userID = "user_" + new Random().nextInt(100000);
                                    User userToInsert = new User();
                                    userToInsert.setId(userID);
                                    userToInsert.setIsAdmin(false);
                                    userDao.insertNewInstance(userToInsert);
                                    user = userDao.getById(userID);

                                    List<SolutionQuery> solutions = new ExerciseDao().getSolutions(exercise);
                                    String solution = solutions.get(0).getQuery();
                                    ExerciseController exc = new ExerciseController().init_debug(scenario,
                                            exercise, user);
                                    exc.setUserString(solution);

                                    String fd = exc.getFeedbackList().get(0).getFeedback();
                                    System.out.println("Used Query: " + solution);
                                    if (fd.trim().toLowerCase().equals("bestanden")) {
                                        System.out.println(exercise.getId() + ": " + fd);
                                    } else {
                                        System.err.println(exercise.getId() + ": " + fd + "\n");
                                    }
                                    System.out.println(StringUtils.repeat("-", 90));
                                }

                                long elapsedTime = System.currentTimeMillis() - startTime;

                                // if (i > 5) {
                                //   try {
                                //     equivalenceLock.lock(performance);
                                //     performance[0] += elapsedTime;
                                //     performance[1]++;
                                //   } catch (Exception e) {
                                //   } finally {
                                //     equivalenceLock.release(performance);
                                //   }
                                // }
                            }
                        }
                    }

                    System.err
                            .println("INFO (ueps): Thread '" + Thread.currentThread().getName() + "' stopped");
                }
            };
            thread.start();
            threads.add(thread);
        }

        for (Thread thread : threads) {
            thread.join();
        }

        // try {
        //   equivalenceLock.lock(performance);

        //   long elapsedTime = (performance[0] / performance[1]);
        //   System.out.println("\n" + String.format("perf : %d.%03dsec", elapsedTime / 1000, elapsedTime % 1000));
        // } catch (Exception e) {
        // } finally {
        //   equivalenceLock.release(performance);
        // }

    } finally {
    }
}

From source file:it.geosolutions.sfs.web.Start.java

public static void main(String[] args) {
    final Server jettyServer = new Server();

    try {// w  w  w .  j a  va2 s  . com
        SocketConnector conn = new SocketConnector();
        String portVariable = System.getProperty("jetty.port");
        int port = parsePort(portVariable);
        if (port <= 0)
            port = 8082;
        conn.setPort(port);
        conn.setAcceptQueueSize(100);
        conn.setMaxIdleTime(1000 * 60 * 60);
        conn.setSoLingerTime(-1);

        // Use this to set a limit on the number of threads used to respond requests
        // BoundedThreadPool tp = new BoundedThreadPool();
        // tp.setMinThreads(8);
        // tp.setMaxThreads(8);
        // conn.setThreadPool(tp);

        // SSL host name given ?
        String sslHost = System.getProperty("ssl.hostname");
        SslSocketConnector sslConn = null;
        //            if (sslHost!=null && sslHost.length()>0) {   
        //                Security.addProvider(new BouncyCastleProvider());
        //                sslConn = getSslSocketConnector(sslHost);
        //            }

        if (sslConn == null) {
            jettyServer.setConnectors(new Connector[] { conn });
        } else {
            conn.setConfidentialPort(sslConn.getPort());
            jettyServer.setConnectors(new Connector[] { conn, sslConn });
        }

        /*Constraint constraint = new Constraint();
        constraint.setName(Constraint.__BASIC_AUTH);;
        constraint.setRoles(new String[]{"user","admin","moderator"});
        constraint.setAuthenticate(true);
                 
        ConstraintMapping cm = new ConstraintMapping();
        cm.setConstraint(constraint);
        cm.setPathSpec("/*");
                
        SecurityHandler sh = new SecurityHandler();
        sh.setUserRealm(new HashUserRealm("MyRealm","/Users/jdeolive/realm.properties"));
        sh.setConstraintMappings(new ConstraintMapping[]{cm});
                
        WebAppContext wah = new WebAppContext(sh, null, null, null);*/
        WebAppContext wah = new WebAppContext();
        wah.setContextPath("/sfs");
        wah.setWar("src/main/webapp");

        jettyServer.setHandler(wah);
        wah.setTempDirectory(new File("target/work"));
        //this allows to send large SLD's from the styles form
        wah.getServletContext().getContextHandler().setMaxFormContentSize(1024 * 1024 * 2);

        String jettyConfigFile = System.getProperty("jetty.config.file");
        if (jettyConfigFile != null) {
            //                log.info("Loading Jetty config from file: " + jettyConfigFile);
            (new XmlConfiguration(new FileInputStream(jettyConfigFile))).configure(jettyServer);
        }

        jettyServer.start();

        /*
         * Reads from System.in looking for the string "stop\n" in order to gracefully terminate
         * the jetty server and shut down the JVM. This way we can invoke the shutdown hooks
         * while debugging in eclipse. Can't catch CTRL-C to emulate SIGINT as the eclipse
         * console is not propagating that event
         */
        Thread stopThread = new Thread() {
            @Override
            public void run() {
                BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
                String line;
                try {
                    while (true) {
                        line = reader.readLine();
                        if ("stop".equals(line)) {
                            jettyServer.stop();
                            System.exit(0);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    System.exit(1);
                }
            }
        };
        stopThread.setDaemon(true);
        stopThread.run();

        // use this to test normal stop behaviour, that is, to check stuff that
        // need to be done on container shutdown (and yes, this will make 
        // jetty stop just after you started it...)
        // jettyServer.stop(); 
    } catch (Exception e) {
        //            log.log(Level.SEVERE, "Could not start the Jetty server: " + e.getMessage(), e);

        if (jettyServer != null) {
            try {
                jettyServer.stop();
            } catch (Exception e1) {
                //                    log.log(Level.SEVERE,
                //                        "Unable to stop the " + "Jetty server:" + e1.getMessage(), e1);
            }
        }
    }
}

From source file:com.ingby.socbox.bischeck.Execute.java

public static void main(String[] args) {

    // create the command line parser
    CommandLineParser parser = new GnuParser();
    CommandLine line = null;//  w  w  w.j  av a 2  s . com

    // create the Options
    Options options = new Options();
    options.addOption("u", "usage", false, "show usage.");
    options.addOption("d", "deamon", false, "start as a deamon");

    try {
        // parse the command line arguments
        line = parser.parse(options, args);

    } catch (org.apache.commons.cli.ParseException e) {
        System.out.println("Command parse error:" + e.getMessage());
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("Bischeck", options);
        Util.ShellExit(Util.FAILED);
    }

    if (line.hasOption("usage")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("Bischeck", options);
        Util.ShellExit(Util.OKAY);
    }

    dumpthread = new Thread() {
        public void run() {
            try {
                CacheFactory.destroy();
            } catch (CacheException e) {
                LOGGER.warn("Cache could not be destoryed", e);
            }
        }
    };

    dumpthread.setName("dumpcache");

    int retStat = Util.OKAY;
    do {
        try {
            if (line.hasOption("deamon")) {
                ConfigurationManager.init();
            } else {
                ConfigurationManager.initonce();
            }
        } catch (Exception e) {
            LOGGER.error("Creating bischeck Configuration Manager failed with: {}", e.getMessage(), e);
            Util.ShellExit(Util.FAILED);
        }

        retStat = Execute.getInstance().deamon();
        LOGGER.debug("Method Execute returned {}", retStat);
    } while (retStat == RESTART);

    dumpthread.start();

    LOGGER.info("******************* Shutdown ********************");

    Util.ShellExit(retStat);
}

From source file:com.francetelecom.rd.dashboard.pc.DashboardPC.java

/**
 * Launch the application./*from   w  ww  .  j  a va2s  .  c  o m*/
 */
public static void main(String[] args) {
    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {
            try {
                logger.info("Application close, will unpublish node!");
                myNode.unPublishFromHomeBus();
            } catch (HomeBusException e) {
                logger.error("Application close, could not unpublish node : " + e.getMessage());
                e.printStackTrace();
            }
        }
    });

    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {

                DashboardPC frame = new DashboardPC();

                String nodeId = frame.getIdForType(ID_type_Node);
                frame.busFactory = new HomeBusFactory(nodeId);
                try {
                    // temporary solution
                    // fake solution
                    // must remove this sleep after sds will no longer need it
                    Thread.sleep(1000);
                } catch (Exception e) {
                    logger.error("Error while sleep before node publish! \n" + e.getMessage());
                }

                frame.initNode(nodeId);
                frame.initDashboardWithRules();

                frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

From source file:io.kodokojo.monitor.Launcher.java

public static void main(String[] args) {

    Injector propertyInjector = Guice.createInjector(new CommonsPropertyModule(args), new PropertyModule());
    MicroServiceConfig microServiceConfig = propertyInjector.getInstance(MicroServiceConfig.class);
    LOGGER.info("Starting Kodo Kojo {}.", microServiceConfig.name());
    Injector commonsServicesInjector = propertyInjector.createChildInjector(new UtilityServiceModule(),
            new EventBusModule(), new DatabaseModule(), new SecurityModule(), new CommonsHealthCheckModule());

    Injector marathonInjector = null;// w w  w  .j  a  va 2s .c  o  m
    OrchestratorConfig orchestratorConfig = propertyInjector.getInstance(OrchestratorConfig.class);
    if (MOCK.equals(orchestratorConfig.orchestrator())) {
        marathonInjector = commonsServicesInjector.createChildInjector(new AbstractModule() {
            @Override
            protected void configure() {
                //
            }

            @Singleton
            @Provides
            BrickStateLookup provideBrickStateLookup() {
                return new BrickStateLookup() {

                    private int cpt = 0;

                    @Override
                    public Set<BrickStateEvent> lookup() {
                        return Collections.singleton(generateBrickStateEvent());
                    }

                    public BrickStateEvent generateBrickStateEvent() {
                        BrickStateEvent.State[] states = BrickStateEvent.State.values();
                        int index = RandomUtils.nextInt(states.length);
                        BrickStateEvent.State state = states[index];

                        return new BrickStateEvent("1234", "build-A", BrickType.CI.name(), "jenkins", state,
                                "1.65Z3.1");
                    }
                };
            }
        });
    } else {
        marathonInjector = commonsServicesInjector.createChildInjector(new AbstractModule() {
            @Override
            protected void configure() {
                //
            }

            @Singleton
            @Provides
            BrickStateLookup provideBrickStateLookup(MarathonConfig marathonConfig,
                    ProjectFetcher projectFectcher, BrickFactory brickFactory, BrickUrlFactory brickUrlFactory,
                    OkHttpClient httpClient) {
                return new MarathonBrickStateLookup(marathonConfig, projectFectcher, brickFactory,
                        brickUrlFactory, httpClient);
            }

        });
    }

    Injector servicesInjector = marathonInjector.createChildInjector(new ServiceModule());

    ApplicationLifeCycleManager applicationLifeCycleManager = servicesInjector
            .getInstance(ApplicationLifeCycleManager.class);
    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            super.run();
            LOGGER.info("Stopping services.");
            applicationLifeCycleManager.stop();
            LOGGER.info("All services stopped.");
        }
    });

    EventBus eventBus = servicesInjector.getInstance(EventBus.class);
    eventBus.connect();
    //  Init repository.
    BrickStateLookup brickStateLookup = servicesInjector.getInstance(BrickStateLookup.class);
    BrickStateEventRepository repository = servicesInjector.getInstance(BrickStateEventRepository.class);
    Set<BrickStateEvent> brickStateEvents = brickStateLookup.lookup();
    repository.compareAndUpdate(brickStateEvents);

    HttpHealthCheckEndpoint httpHealthCheckEndpoint = servicesInjector
            .getInstance(HttpHealthCheckEndpoint.class);
    httpHealthCheckEndpoint.start();

    ActorSystem actorSystem = servicesInjector.getInstance(ActorSystem.class);
    ActorRef actorRef = servicesInjector.getInstance(ActorRef.class);
    actorSystem.scheduler().schedule(Duration.Zero(), Duration.create(1, TimeUnit.MINUTES), actorRef, "Tick",
            actorSystem.dispatcher(), ActorRef.noSender());
    LOGGER.info("Kodo Kojo {} started.", microServiceConfig.name());

}

From source file:fi.helsinki.cs.iot.kahvihub.KahviHub.java

public static void main(String[] args) throws InterruptedException {
    // create Options object
    Options options = new Options();
    // add conf file option
    options.addOption("c", true, "config file");
    CommandLineParser parser = new BasicParser();
    CommandLine cmd;// w  w w.ja  v a2 s . c  o  m
    try {
        cmd = parser.parse(options, args);
        String configFile = cmd.getOptionValue("c");
        if (configFile == null) {
            Log.e(TAG, "The config file option was not provided");
            // automatically generate the help statement
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("d", options);
            System.exit(-1);
        } else {
            try {
                HubConfig hubConfig = ConfigurationFileParser.parseConfigurationFile(configFile);
                Path libdir = Paths.get(hubConfig.getLibdir());
                if (hubConfig.isDebugMode()) {
                    File dir = libdir.toFile();
                    if (dir.exists() && dir.isDirectory())
                        for (File file : dir.listFiles())
                            file.delete();
                }
                final IotHubHTTPD server = new IotHubHTTPD(hubConfig.getPort(), libdir, hubConfig.getHost());
                init(hubConfig);
                try {
                    server.start();
                } catch (IOException ioe) {
                    Log.e(TAG, "Couldn't start server:\n" + ioe);
                    System.exit(-1);
                }
                Runtime.getRuntime().addShutdownHook(new Thread() {
                    @Override
                    public void run() {
                        server.stop();
                        Log.i(TAG, "Server stopped");
                    }
                });

                while (true) {
                    Thread.sleep(1000);
                }
            } catch (ConfigurationParsingException | IOException e) {
                System.out.println("1:" + e.getMessage());
                Log.e(TAG, e.getMessage());
                System.exit(-1);
            }
        }

    } catch (ParseException e) {
        System.out.println(e.getMessage());
        Log.e(TAG, e.getMessage());
        System.exit(-1);
    }
}