Example usage for java.util.concurrent TimeUnit SECONDS

List of usage examples for java.util.concurrent TimeUnit SECONDS

Introduction

In this page you can find the example usage for java.util.concurrent TimeUnit SECONDS.

Prototype

TimeUnit SECONDS

To view the source code for java.util.concurrent TimeUnit SECONDS.

Click Source Link

Document

Time unit representing one second.

Usage

From source file:com.github.joshelser.dropwizard.metrics.hadoop.StandaloneExample.java

public static void main(String[] args) throws Exception {
    final MetricRegistry metrics = new MetricRegistry();

    final HadoopMetrics2Reporter metrics2Reporter = HadoopMetrics2Reporter.forRegistry(metrics).build(
            DefaultMetricsSystem.initialize("StandaloneTest"), // The application-level name
            "Test", // Component name
            "Test", // Component description
            "Test"); // Name for each metric record
    final ConsoleReporter consoleReporter = ConsoleReporter.forRegistry(metrics).build();

    MetricsSystem metrics2 = DefaultMetricsSystem.instance();
    // Writes to stdout without a filename configuration
    // Will be invoked every 10seconds by default
    FileSink sink = new FileSink();
    metrics2.register("filesink", "filesink", sink);
    sink.init(new SubsetConfiguration(null, null) {
        public String getString(String key) {
            if (key.equals("filename")) {
                return null;
            }//from   w  ww  .  j a v  a 2  s  .  c  o m
            return super.getString(key);
        }
    });

    // How often should the dropwizard reporter be invoked
    metrics2Reporter.start(500, TimeUnit.MILLISECONDS);
    // How often will the dropwziard metrics be logged to the console
    consoleReporter.start(2, TimeUnit.SECONDS);

    generateMetrics(metrics, 5000, 25, TimeUnit.MILLISECONDS, metrics2Reporter, 10);
}

From source file:com.wso2.rfid.Main.java

public static void main(String[] args) throws IOException {
    Properties configs = new Properties();
    configs.load(//from   ww  w .j  a  va2 s.  co m
            new FileInputStream(System.getProperty("rpi.agent.home") + File.separator + "config.properties"));

    Server server = new Server(InetSocketAddress.createUnresolved("127.0.0.1", 8084));
    ServletHandler handler = new ServletHandler();
    server.setHandler(handler);
    handler.addServletWithMapping(RFIDReaderServlet.class, "/rfid");
    String controlCenterURL = configs.getProperty("control.center.url");
    System.out.println("Using RPi Control Center: " + controlCenterURL);
    String tokenEndpoint = configs.getProperty("token.endpoint");
    System.out.println("Using token endpoint: " + tokenEndpoint);
    APICall.setTokenEndpoint(tokenEndpoint);
    String primaryNwInterface = configs.getProperty("primary.nw.interface");
    String userRegEndpoint = configs.getProperty("user.registration.endpoint");
    System.out.println("Using user registration endpoint: " + userRegEndpoint);
    APICall.setUserRegistrationEndpoint(userRegEndpoint);
    scheduler.scheduleWithFixedDelay(new MonitoringTask(controlCenterURL, primaryNwInterface), 0, 10,
            TimeUnit.SECONDS);

    try {
        server.start();
        server.join();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.yufei.dataget.dataretriver.HttpDataRetriverUsingFirefoxDriver.java

public static void main(String[] args) throws Exception {

    final long startTime = System.currentTimeMillis();
    mLog.info("calling runWithTimeout!");
    HttpDataRetriverUsingFirefoxDriver hdrufd = new HttpDataRetriverUsingFirefoxDriver(null);

    try {/*from  w  w  w . jav  a 2s  . c o m*/
        String htmlContent = TimeOutUtils.runWithTimeout(new Callable<String>() {

            @Override
            public String call() throws Exception {
                String url = "http://www.baidu.com/tools?url=http%3A%2F%2Fwww.baidu.com%2Flink%3Furl%3DO0urTq_fyCkG3Rd2veZDQm7TLJ50XyUOeeoybddPUG6zBjpgh37XHtMM_oXKe4nQxM-q5IEVjldslw0tbkMfvK&jump=http%3A%2F%2Fkoubei.baidu.com%2Fwomc%2Fp%2Fsentry%3Ftitle%3D%012014%01-%012015%01%E5%B9%B4%E5%BA%A6%01QS%01%E4%B8%96%E7%95%8C%01%E6%8E%92%E5%90%8D%01%3A%01%E6%BE%B3%E5%A4%A7%E5%88%A9%E4%BA%9A%01%E5%A4%A7%E5%AD%A6%0123%01%E6%89%80%01%E9%AB%98%E6%A0%A1%01%E8%BF%9B%E5%85%A5%02TOP%01500%03-%01%E7%95%99%E5%AD%A6%01-%01...%26q%3Dtop%20500%20university&key=surl";
                hdrufd.setUrl(new URL(url));
                hdrufd.connect();

                System.out.print(hdrufd.getHtmlContent());
                return hdrufd.getHtmlContent();

            }
        }, 10, TimeUnit.SECONDS);
    } catch (TimeoutException e) {
        mLog.info("got timeout!");
    } finally {
        hdrufd.disconnect();

    }
    mLog.info("end of main method!");

}

From source file:io.rhiot.spec.IoTSpec.java

public static void main(String[] args) throws Exception {

    CommandLineParser parser = new DefaultParser();

    Options options = new Options();
    options.addOption(Option.builder("c").longOpt(CONFIG).desc(
            "Location of the test configuration file. A default value is 'src/main/resources/test.yaml' for easy IDE testing")
            .hasArg().build());/*w w w. ja v a2  s  . c  o m*/

    options.addOption(Option.builder("i").longOpt(INSTANCE).desc("Instance of the test; A default value is 1")
            .hasArg().build());

    options.addOption(Option.builder("r").longOpt(REPORT)
            .desc("Location of the test report. A default value is 'target/report.csv'").hasArg().build());

    CommandLine line = parser.parse(options, args);
    ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
    TestProfile test = mapper.readValue(new File(line.getOptionValue(CONFIG, "src/main/resources/test.yaml")),
            TestProfile.class);
    int instance = Integer.valueOf(line.getOptionValue(INSTANCE, "1"));
    test.setInstance(instance);
    String report = line.getOptionValue(REPORT, "target/report.csv");
    test.setReport(new CSVReport(report));

    LOG.info("Test '" + test.getName() + "' instance " + instance + " started");
    final List<Driver> drivers = test.getDrivers();
    ExecutorService executorService = Executors.newFixedThreadPool(drivers.size());
    List<Future<Void>> results = executorService.invokeAll(drivers, test.getDuration(), TimeUnit.MILLISECONDS);
    executorService.shutdownNow();
    executorService.awaitTermination(5, TimeUnit.SECONDS);

    results.forEach(result -> {
        try {
            result.get();
        } catch (ExecutionException execution) {
            LOG.warn("Exception running driver", execution);
        } catch (Exception interrupted) {
        }
    });

    drivers.forEach(driver -> {
        driver.stop();

        try {
            test.getReport().print(driver);
        } catch (Exception e) {
            LOG.warn("Failed to write reports for the driver " + driver);
        }
        LOG.debug("Driver " + driver);
        LOG.debug("\t " + driver.getResult());
    });
    test.getReport().close();

    LOG.info("Test '" + test.getName() + "' instance " + instance + " finished");

}

From source file:example.tempdest.ProducerRequestReply.java

public static void main(String[] args) {
    String url = BROKER_URL;
    if (args.length > 0) {
        url = args[0].trim();// w  w w . j  a  v a  2  s .  com
    }
    ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("admin", "password", url);
    Connection connection = null;

    try {

        connection = connectionFactory.createConnection();
        connection.start();

        Session session = connection.createSession(NON_TRANSACTED, Session.AUTO_ACKNOWLEDGE);
        Destination destination = session.createQueue("test-queue");
        MessageProducer producer = session.createProducer(destination);
        Destination replyDest = session.createTemporaryQueue();

        // set up the consumer to handle the reply
        MessageConsumer replyConsumer = session.createConsumer(replyDest);
        replyConsumer.setMessageListener(new MessageListener() {
            @Override
            public void onMessage(Message message) {
                System.out.println("*** REPLY *** ");
                System.out.println(message.toString());
            }
        });

        TextMessage message = session.createTextMessage("I need a response for this, please");
        message.setJMSReplyTo(replyDest);

        producer.send(message);

        // wait for a response
        TimeUnit.SECONDS.sleep(2);
        producer.close();
        session.close();

    } catch (Exception e) {
        System.out.println("Caught exception!");
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (JMSException e) {
                System.out.println("Could not close an open connection...");
            }
        }
    }
}

From source file:org.sourcepit.consul.forwarder.Main.java

public static void main(String[] args) {

    final String dockerUri = "http://192.168.56.101:2375";
    final String consulUri = "http://192.168.56.101:8500";

    final int fetchConsulStateInterval = 30;
    final int fetchDockerStateInterval = 30;
    final int dispatchItemsInterval = 2;
    final int requestDockerStateDelay = 5;

    PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
    connManager.setDefaultMaxPerRoute(10);
    final HttpClient httpClient = HttpClients.createMinimal(connManager);

    final BlockingQueue<JsonObject> queue = new LinkedBlockingQueue<>();

    final FetchConsulStateCmd fetchConsulStateCmd = new FetchConsulStateCmd(httpClient, consulUri) {
        @Override//from  w  w  w .  j av a2  s .  com
        protected void doHandle(JsonObject consulState) {
            final JsonObject item = createItem("ConsulState", consulState);
            LOG.debug(item.toString());
            queue.add(item);
        }

    };

    final FetchDockerStateCmd fetchDockerStateCmd = new FetchDockerStateCmd(httpClient, dockerUri) {
        @Override
        protected void doHandle(JsonArray dockerState) {
            final JsonObject item = createItem("DockerState", dockerState);
            LOG.debug(item.toString());
            queue.add(item);
        }
    };

    final ConsulForwarderState forwarderState = new ConsulForwarderState();

    final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
    scheduler.scheduleAtFixedRate(fetchConsulStateCmd, 0, fetchConsulStateInterval, TimeUnit.SECONDS);
    scheduler.scheduleAtFixedRate(fetchDockerStateCmd, 0, fetchDockerStateInterval, TimeUnit.SECONDS);
    scheduler.scheduleAtFixedRate(new DispatchItemsCmd(queue) {
        @Override
        protected void handleDockerState(JsonArray dockerState) {
            forwarderState.applyDockerState(dockerState);
        }

        @Override
        protected void handleDockerEvents(JsonArray dockerEvents) {
            // trigger docker state update
            scheduler.schedule(fetchDockerStateCmd, requestDockerStateDelay, TimeUnit.SECONDS);
        }

        @Override
        protected void handleConsulState(JsonObject consulState) {
            forwarderState.applyConsulState(consulState);
        }
    }, 0, dispatchItemsInterval, TimeUnit.SECONDS);

    final DockerEventObserver eventObserver = new DockerEventObserver(httpClient, dockerUri) {
        @Override
        protected void handle(JsonObject event) {
            queue.add(createItem("DockerEvent", event));
        }
    };

    final Thread eventObserverThread = new Thread(eventObserver, "Docker Event Observer") {
        @Override
        public void interrupt() {
            eventObserver.die();
            super.interrupt();
        }
    };
    eventObserverThread.start();
}

From source file:async.nio2.Main.java

public static void main(String[] args) throws IOException, InterruptedException, ExecutionException {

    if (args.length == 3) {
        PORT = Integer.valueOf(args[0]);
        NO_CLIENTS = Integer.valueOf(args[1]);
        NO_SAMPLES = Integer.valueOf(args[2]);
    }/*from   ww w.  j  a  va  2  s  . co  m*/

    if (PORT < 0) {
        System.err.println("Error: port < 0");
        System.exit(1);
    }

    if (NO_CLIENTS < 1) {
        System.err.println("Error: #clients < 1");
        System.exit(1);
    }

    if (NO_SAMPLES < 1) {
        System.err.println("Error: #samples < 1");
        System.exit(1);
    }

    AsynchronousChannelGroup groupServer = AsynchronousChannelGroup
            .withThreadPool(Executors.newFixedThreadPool(1));
    AsynchronousChannelGroup groupClient = AsynchronousChannelGroup
            .withThreadPool(Executors.newFixedThreadPool(1));

    Server server = Server.newInstance(new InetSocketAddress("localhost", PORT), groupServer);
    InetSocketAddress localAddress = server.getLocalAddress();
    String hostname = localAddress.getHostName();
    int port = localAddress.getPort();

    ExecutorService es = Executors.newFixedThreadPool(2);

    System.out.printf("%03d clients on %s:%d, %03d runs each. All times in s.%n", NO_CLIENTS, hostname, port,
            NO_SAMPLES);
    range(0, NO_CLIENTS).unordered().parallel()
            .mapToObj(i -> CompletableFuture.supplyAsync(newClient(localAddress, groupClient), es).join())
            .map(array -> Arrays.stream(array).reduce(new DescriptiveStatistics(), Main::accumulate,
                    Main::combine))
            .map(Main::toEvaluationString).forEach(System.out::println);

    es.shutdown();
    es.awaitTermination(5, TimeUnit.SECONDS);

    groupClient.shutdown();
    groupClient.awaitTermination(5, TimeUnit.SECONDS);

    server.close();
    groupServer.shutdown();
    groupServer.awaitTermination(5, TimeUnit.SECONDS);
}

From source file:com.turbospaces.api.EmbeddedJSpaceRunner.java

/**
 * launcher method/*w w  w.jav a2 s .c  o m*/
 * 
 * @param args
 *            [1 argument = application context path]
 * @throws Exception
 *             re-throw execution errors if any
 */
public static void main(final String... args) throws Exception {
    JVMUtil.gcOnExit();
    String appContextPath = args[0];
    if (System.getProperty(Global.IPv4) == null && System.getProperty(Global.IPv6) == null)
        System.setProperty(Global.IPv4, Boolean.TRUE.toString());
    System.setProperty(Global.CUSTOM_LOG_FACTORY, JGroupsCustomLoggerFactory.class.getName());

    LOGGER.info("Welcome to turbospaces:version = {}, build date = {}", SpaceUtility.projectVersion(),
            SpaceUtility.projecBuildTimestamp());
    LOGGER.info("{}: launching configuration {}", EmbeddedJSpaceRunner.class.getSimpleName(), appContextPath);
    AbstractXmlApplicationContext c = appContextPath.startsWith("file")
            ? new FileSystemXmlApplicationContext(appContextPath)
            : new ClassPathXmlApplicationContext(appContextPath);
    c.getBeansOfType(JSpace.class);
    c.registerShutdownHook();
    Collection<SpaceConfiguration> configurations = c.getBeansOfType(SpaceConfiguration.class).values();
    for (SpaceConfiguration spaceConfiguration : configurations)
        spaceConfiguration.joinNetwork();
    LOGGER.info("all jspaces joined network, notifying waiting threads...");
    synchronized (joinNetworkMonitor) {
        joinNetworkMonitor.notifyAll();
    }

    while (!Thread.currentThread().isInterrupted())
        synchronized (c) {
            try {
                c.wait(TimeUnit.SECONDS.toMillis(1));
            } catch (InterruptedException e) {
                LOGGER.info("got interruption signal, terminating jspaces... stack_trace = {}",
                        Throwables.getStackTraceAsString(e));
                Thread.currentThread().interrupt();
                Util.printThreads();
            }
        }

    c.destroy();
}

From source file:edu.mit.lib.mama.Mama.java

public static void main(String[] args) {

    Properties props = findConfig(args);
    DBI dbi = new DBI(props.getProperty("dburl"), props);
    // Advanced instrumentation/metrics if requested
    if (System.getenv("MAMA_DB_METRICS") != null) {
        dbi.setTimingCollector(new InstrumentedTimingCollector(metrics));
    }//from w w w  .j ava2s.com
    // reassign default port 4567
    if (System.getenv("MAMA_SVC_PORT") != null) {
        port(Integer.valueOf(System.getenv("MAMA_SVC_PORT")));
    }
    // if API key given, use exception monitoring service
    if (System.getenv("HONEYBADGER_API_KEY") != null) {
        reporter = new HoneybadgerReporter();
    }

    get("/ping", (req, res) -> {
        res.type("text/plain");
        res.header("Cache-Control", "must-revalidate,no-cache,no-store");
        return "pong";
    });

    get("/metrics", (req, res) -> {
        res.type("application/json");
        res.header("Cache-Control", "must-revalidate,no-cache,no-store");
        ObjectMapper objectMapper = new ObjectMapper()
                .registerModule(new MetricsModule(TimeUnit.SECONDS, TimeUnit.MILLISECONDS, true));
        try (ServletOutputStream outputStream = res.raw().getOutputStream()) {
            objectMapper.writer().withDefaultPrettyPrinter().writeValue(outputStream, metrics);
        }
        return "";
    });

    get("/shutdown", (req, res) -> {
        boolean auth = false;
        try {
            if (!isNullOrEmpty(System.getenv("MAMA_SHUTDOWN_KEY")) && !isNullOrEmpty(req.queryParams("key"))
                    && System.getenv("MAMA_SHUTDOWN_KEY").equals(req.queryParams("key"))) {
                auth = true;
                return "Shutting down";
            } else {
                res.status(401);
                return "Not authorized";
            }
        } finally {
            if (auth) {
                stop();
            }
        }
    });

    get("/item", (req, res) -> {
        if (isNullOrEmpty(req.queryParams("qf")) || isNullOrEmpty(req.queryParams("qv"))) {
            halt(400, "Must supply field and value query parameters 'qf' and 'qv'");
        }
        itemReqs.mark();
        Timer.Context context = respTime.time();
        try (Handle hdl = dbi.open()) {
            if (findFieldId(hdl, req.queryParams("qf")) != -1) {
                List<String> results = findItems(hdl, req.queryParams("qf"), req.queryParams("qv"),
                        req.queryParamsValues("rf"));
                if (results.size() > 0) {
                    res.type("application/json");
                    return "{ " + jsonValue("field", req.queryParams("qf"), true) + ",\n"
                            + jsonValue("value", req.queryParams("qv"), true) + ",\n" + jsonValue("items",
                                    results.stream().collect(Collectors.joining(",", "[", "]")), false)
                            + "\n" + " }";
                } else {
                    res.status(404);
                    return "No items found for: " + req.queryParams("qf") + "::" + req.queryParams("qv");
                }
            } else {
                res.status(404);
                return "No such field: " + req.queryParams("qf");
            }
        } catch (Exception e) {
            if (null != reporter)
                reporter.reportError(e);
            res.status(500);
            return "Internal system error: " + e.getMessage();
        } finally {
            context.stop();
        }
    });

    awaitInitialization();
}

From source file:io.kahu.hawaii.util.call.example.Example1.java

public static final void main(String[] args) throws Exception {
    DOMConfigurator.configure(Example1.class.getResource("/log4j.xml").getFile());

    RestServer server = null;/*from   w  w w .jav a2 s.  c o  m*/
    ExecutorRepository executorRepository = null;
    try {
        /*
         * Create our rest server with a 'ClientResource'.
         */
        server = new RestServer(SERVER_PORT);
        server.addResource(ClientResource.class);
        server.start();

        /*
         * Dispatcher Framework setup
         */
        // Create a log manager (purpose and explanation out of scope for this example).
        LogManager logManager = new DefaultLogManager(new LogManagerConfiguration(new LoggingConfiguration()));

        // Create an executor, with a thread pool of core size 1 and max size 2 and with a queue of size 4.
        // Threads 'outside the core pool' that are still active after one minute will get cleaned up.
        HawaiiExecutorImpl executor = new HawaiiExecutorImpl(ExecutorRepository.DEFAULT_EXECUTOR_NAME, 1, 2, 4,
                new TimeOut(1, TimeUnit.MINUTES), logManager);

        // Create the repository that holds all executors
        executorRepository = new ExecutorRepository(logManager);
        executorRepository.add(executor);

        // Create a new request dispatcher.
        RequestDispatcher requestDispatcher = new RequestDispatcher(executorRepository, logManager);

        /*
         * Setup the request (builder).
         */
        HttpRequestContext<Person> context = new HttpRequestContext<>(HttpMethod.GET,
                "http://localhost:" + SERVER_PORT, "/customer/{customer-id}", "crm", "get_customer_by_id",
                new TimeOut(2, TimeUnit.SECONDS));
        CallLogger callLogger = new CallLoggerImpl<>(logManager, new HttpRequestLogger(),
                new JsonPayloadResponseLogger<Person>());
        RequestPrototype<HttpResponse, Person> prototype = new RequestPrototype(requestDispatcher, context,
                new GetCustomerByIdResponseHandler(), callLogger);
        HttpRequestBuilder<Person> getCustomerByIdRequest = new HttpRequestBuilder<>(prototype);

        /*
         * Use the request (builder).
         */
        Request<Person> request = getCustomerByIdRequest.newInstance().withPathVariables("10").build();
        Person person = request.execute().get();

        System.err
                .println("CLIENT - Got customer '" + person.getName() + "' with id '" + person.getId() + "'.");

    } finally {
        server.stop();
        if (executorRepository != null) {
            executorRepository.stop();
        }
    }

}