Example usage for java.util.concurrent TimeUnit HOURS

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

Introduction

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

Prototype

TimeUnit HOURS

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

Click Source Link

Document

Time unit representing sixty minutes.

Usage

From source file:Main.java

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

    long time = System.currentTimeMillis();
    FileTime fileTime = FileTime.fromMillis(time);
    System.out.println(fileTime.to(TimeUnit.HOURS));

}

From source file:Main.java

public static void main(String[] args) throws java.lang.Exception {
    String[] StartTimes = { "10:00", "7:00" };
    String[] EndTimes = { "12:00", "14:56" };
    for (int i = 0; i < StartTimes.length; i++) {
        if (StartTimes != null && StartTimes.length > 0 && EndTimes != null && EndTimes.length > 0) {
            SimpleDateFormat format = new SimpleDateFormat("HH:mm");
            Date date1 = format.parse(StartTimes[i]);
            Date date2 = format.parse(EndTimes[i]);
            long millis = date2.getTime() - date1.getTime();

            String hourminute = String.format("%02d:%02d", TimeUnit.MILLISECONDS.toHours(millis),
                    TimeUnit.MILLISECONDS.toMinutes(millis)
                            - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)));
            System.out.println(hourminute);
        }/*from   w  w w .  ja v  a  2s . com*/
    }
}

From source file:com.github.fhuss.kafka.streams.cep.demo.CEPStockKStreamsDemo.java

public static void main(String[] args) {

    Properties props = new Properties();
    props.put(StreamsConfig.APPLICATION_ID_CONFIG, "streams-cep");
    props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
    props.put(StreamsConfig.ZOOKEEPER_CONNECT_CONFIG, "localhost:2181");
    props.put(StreamsConfig.KEY_SERDE_CLASS_CONFIG, StockEventSerDe.class);
    props.put(StreamsConfig.VALUE_SERDE_CLASS_CONFIG, StockEventSerDe.class);

    // setting offset reset to earliest so that we can re-run the demo code with the same pre-loaded data
    props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");

    // build query
    final Pattern<Object, StockEvent> pattern = new QueryBuilder<Object, StockEvent>().select()
            .where((k, v, ts, store) -> v.volume > 1000).<Long>fold("avg", (k, v, curr) -> v.price).then()
            .select().zeroOrMore().skipTillNextMatch()
            .where((k, v, ts, state) -> v.price > (long) state.get("avg"))
            .<Long>fold("avg", (k, v, curr) -> (curr + v.price) / 2)
            .<Long>fold("volume", (k, v, curr) -> v.volume).then().select().skipTillNextMatch()
            .where((k, v, ts, state) -> v.volume < 0.8 * state.getOrElse("volume", 0L))
            .within(1, TimeUnit.HOURS).build();

    KStreamBuilder builder = new KStreamBuilder();

    CEPStream<Object, StockEvent> stream = new CEPStream<>(builder.stream("StockEvents"));

    KStream<Object, Sequence<Object, StockEvent>> stocks = stream.query("Stocks", pattern);

    stocks.mapValues(seq -> {//from  w  w w .ja va2 s.  c  om
        JSONObject json = new JSONObject();
        seq.asMap().forEach((k, v) -> {
            JSONArray events = new JSONArray();
            json.put(k, events);
            List<String> collect = v.stream().map(e -> e.value.name).collect(Collectors.toList());
            Collections.reverse(collect);
            collect.forEach(e -> events.add(e));
        });
        return json.toJSONString();
    }).through(null, Serdes.String(), "Matches").print();

    //Use the topologyBuilder and streamingConfig to start the kafka streams process
    KafkaStreams streaming = new KafkaStreams(builder, props);
    //streaming.cleanUp();
    streaming.start();
}

From source file:org.apache.accumulo.server.test.QueryMetadataTable.java

public static void main(String[] args)
        throws AccumuloException, AccumuloSecurityException, TableNotFoundException {
    Option usernameOpt = new Option("username", "username", true, "username");
    Option passwordOpt = new Option("password", "password", true, "password");

    Options opts = new Options();

    opts.addOption(usernameOpt);/*w  w w  .ja  va 2  s .  co m*/
    opts.addOption(passwordOpt);

    Parser p = new BasicParser();
    CommandLine cl = null;
    try {
        cl = p.parse(opts, args);
    } catch (ParseException e1) {
        System.out.println("Parse Exception, exiting.");
        return;
    }

    if (cl.getArgs().length != 2) {
        HelpFormatter hf = new HelpFormatter();
        hf.printHelp("queryMetadataTable <numQueries> <numThreads> ", opts);
        return;
    }
    String[] rargs = cl.getArgs();

    int numQueries = Integer.parseInt(rargs[0]);
    int numThreads = Integer.parseInt(rargs[1]);
    credentials = new AuthInfo(cl.getOptionValue("username", "root"),
            ByteBuffer.wrap(cl.getOptionValue("password", "secret").getBytes()),
            HdfsZooInstance.getInstance().getInstanceID());

    Connector connector = HdfsZooInstance.getInstance().getConnector(credentials.user, credentials.password);
    Scanner scanner = connector.createScanner(Constants.METADATA_TABLE_NAME, Constants.NO_AUTHS);
    scanner.setBatchSize(20000);
    Text mdrow = new Text(KeyExtent.getMetadataEntry(new Text(Constants.METADATA_TABLE_ID), null));

    HashSet<Text> rowSet = new HashSet<Text>();

    int count = 0;

    for (Entry<Key, Value> entry : scanner) {
        System.out.print(".");
        if (count % 72 == 0) {
            System.out.printf(" %,d\n", count);
        }
        if (entry.getKey().compareRow(mdrow) == 0 && entry.getKey().getColumnFamily()
                .compareTo(Constants.METADATA_CURRENT_LOCATION_COLUMN_FAMILY) == 0) {
            System.out.println(entry.getKey() + " " + entry.getValue());
            location = entry.getValue().toString();
        }

        if (!entry.getKey().getRow().toString().startsWith(Constants.METADATA_TABLE_ID))
            rowSet.add(entry.getKey().getRow());
        count++;

    }

    System.out.printf(" %,d\n", count);

    ArrayList<Text> rows = new ArrayList<Text>(rowSet);

    Random r = new Random();

    ExecutorService tp = Executors.newFixedThreadPool(numThreads);

    long t1 = System.currentTimeMillis();

    for (int i = 0; i < numQueries; i++) {
        int index = r.nextInt(rows.size());
        MDTQuery mdtq = new MDTQuery(rows.get(index));
        tp.submit(mdtq);
    }

    tp.shutdown();

    try {
        tp.awaitTermination(1, TimeUnit.HOURS);
    } catch (InterruptedException e) {
        e.printStackTrace();
        throw new RuntimeException(e);
    }

    long t2 = System.currentTimeMillis();
    double delta = (t2 - t1) / 1000.0;
    System.out.println("time : " + delta + "  queries per sec : " + (numQueries / delta));
}

From source file:alluxio.cli.MiniBenchmark.java

/**
 * @param args there are no arguments needed
 * @throws Exception if error occurs during tests
 *///from  w  w  w .j  av a 2s. com
public static void main(String[] args) throws Exception {
    if (!parseInputArgs(args)) {
        usage();
        System.exit(-1);
    }
    if (sHelp) {
        usage();
        System.exit(0);
    }

    CommonUtils.warmUpLoop();

    for (int i = 0; i < sIterations; ++i) {
        final AtomicInteger count = new AtomicInteger(0);
        final CyclicBarrier barrier = new CyclicBarrier(sConcurrency);
        ExecutorService executorService = Executors.newFixedThreadPool(sConcurrency);
        final AtomicLong runtime = new AtomicLong(0);
        for (int j = 0; j < sConcurrency; ++j) {
            switch (sType) {
            case READ:
                executorService.submit(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            readFile(barrier, runtime, count.addAndGet(1));
                        } catch (Exception e) {
                            LOG.error("Failed to read file.", e);
                            System.exit(-1);
                        }
                    }
                });
                break;
            case WRITE:
                executorService.submit(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            writeFile(barrier, runtime, count.addAndGet(1));
                        } catch (Exception e) {
                            LOG.error("Failed to write file.", e);
                            System.exit(-1);
                        }
                    }
                });
                break;
            default:
                throw new RuntimeException("Unsupported type.");
            }
        }
        executorService.shutdown();
        Preconditions.checkState(executorService.awaitTermination(1, TimeUnit.HOURS));
        double time = runtime.get() * 1.0 / sConcurrency / Constants.SECOND_NANO;
        System.out.printf("Iteration: %d; Duration: %f seconds; Aggregated throughput: %f GB/second.%n", i,
                time, sConcurrency * 1.0 * sFileSize / time / Constants.GB);
    }
}

From source file:io.tempra.AppServer.java

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

    try {// w w w.j  a  v  a  2  s . co m
        // String dir = getProperty("storageLocal");//
        // System.getProperty("user.home");
        String arch = "Win" + System.getProperty("sun.arch.data.model");
        System.out.println("sun.arch.data.model " + arch);

        // Sample to force java load dll or so on a filesystem
        // InputStream in = AppServer.class.getResourceAsStream("/dll/" +
        // arch + "/RechargeRPC.dll");
        //
        // File jCliSiTefI = new File(dir + "/" + "RechargeRPC.dll");
        // System.out.println("Writing dll to: " +
        // jCliSiTefI.getAbsolutePath());
        // OutputStream os = new FileOutputStream(jCliSiTefI);
        // byte[] buffer = new byte[4096];
        // int length;
        // while ((length = in.read(buffer)) > 0) {
        // os.write(buffer, 0, length);
        // }
        // os.close();
        // in.close();
        // System.load(jCliSiTefI.toString());
        // addLibraryPath(dir);

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

    ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
    context.setContextPath("/");

    Server jettyServer = new Server(Integer.parseInt(getProperty("localport")));
    // security configuration
    // FilterHolder holder = new FilterHolder(CrossOriginFilter.class);
    // holder.setInitParameter(CrossOriginFilter.ALLOWED_ORIGINS_PARAM,
    // "*");
    // holder.setInitParameter("allowCredentials", "true");
    // holder.setInitParameter(
    // CrossOriginFilter.ACCESS_CONTROL_ALLOW_ORIGIN_HEADER, "*");
    // holder.setInitParameter(CrossOriginFilter.ALLOWED_METHODS_PARAM,
    // "GET,POST,HEAD");
    // holder.setInitParameter(CrossOriginFilter.ALLOWED_HEADERS_PARAM,
    // "X-Requested-With,Content-Type,Accept,Origin");
    // holder.setName("cross-origin");

    // context.addFilter(holder, fm);

    ResourceHandler resource_handler = new ResourceHandler();

    // add application on embedded server
    boolean servApp = true;
    boolean quioskMode = false;

    // if (System.getProperty("noServApp") != null )
    // if (System.getProperty("noServApp").equalsIgnoreCase("true"))
    // servApp = false;
    if (servApp) {
        //   ProtectionDomain domain = AppServer.class.getProtectionDomain();
        String webDir = AppServer.class.getResource("/webapp").toExternalForm();
        System.out.println("Jetty WEB DIR >>>>" + webDir);
        resource_handler.setDirectoriesListed(true);
        resource_handler.setWelcomeFiles(new String[] { "index.html" });
        resource_handler.setResourceBase(webDir); //
        // "C:/git/tsAgenciaVirtual/www/");
        // resource_handler.setResourceBase("C:/git/tsAgenciaVirtual/www/");

        // copyJarResourceToFolder((JarURLConnection) AppServer.class
        // .getResource("/app").openConnection(), createTempDir("app"));

        // resource_handler.setResourceBase(System
        // .getProperty("java.io.tmpdir") + "/app");
    }
    // sample to add rest services on container
    context.addServlet(FileUploadServlet.class, "/upload");
    ServletHolder jerseyServlet = context.addServlet(ServletContainer.class, "/services/*");
    jerseyServlet.setInitOrder(0);

    jerseyServlet.setInitParameter("jersey.config.server.provider.classnames",
            RestServices.class.getCanonicalName() + "," + RestServices.class.getCanonicalName());

    HandlerList handlers = new HandlerList();
    // context.addFilter(holder, "/*", EnumSet.of(DispatcherType.REQUEST));

    handlers.setHandlers(new Handler[] { resource_handler, context,

            // wscontext,
            new DefaultHandler() });
    jettyServer.setHandler(handlers);
    try {
        // Initialize javax.websocket layer
        ServerContainer wscontainer = WebSocketServerContainerInitializer.configureContext(context);
        wscontainer.setDefaultMaxSessionIdleTimeout(TimeUnit.HOURS.toMillis(1000));

        // Add WebSocket endpoint to javax.websocket layer
        wscontainer.addEndpoint(FileUpload.class);

    } catch (Throwable t) {
        t.printStackTrace(System.err);
    }

    // try {
    jettyServer.start();
    jettyServer.dump(System.err);

    if (servApp && quioskMode) {
        try {
            Process process = new ProcessBuilder(
                    "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe", "--kiosk",
                    "--kiosk-printing", "--auto", "--disable-pinch", "--incognito",
                    "--disable-session-crashed-bubble", "--overscroll-history-navigation=0",
                    "http://localhost:" + getProperty("localport")).start();
            // Process process =
            // Runtime.getRuntime().exec(" -kiosk http://localhost:8080");
            InputStream is = process.getInputStream();
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);
            String line;

            System.out.printf("Output of running %s is:", Arrays.toString(args));
            while ((line = br.readLine()) != null) {
                System.out.println(line);
            }
        }

        catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
    }
    // } finally {
    // jettyServer.destroy();
    // }//}

    jettyServer.join();
}

From source file:bes.injector.InjectorBurnTest.java

public static void main(String[] args) throws InterruptedException, ExecutionException, TimeoutException {
    // do longer test
    new InjectorBurnTest().testPromptnessOfExecution(TimeUnit.HOURS.toNanos(2L), 0.1f);
}

From source file:DIA_Umpire_Quant.DIA_Umpire_LCMSIDGen.java

/**
 * @param args the command line arguments
 *///from   w w  w. j a  va  2s .c  o m
public static void main(String[] args) throws FileNotFoundException, IOException, Exception {
    System.out.println(
            "=================================================================================================");
    System.out.println("DIA-Umpire LCMSID geneartor (version: " + UmpireInfo.GetInstance().Version + ")");
    if (args.length != 1) {
        System.out.println(
                "command format error, the correct format should be: java -jar -Xmx10G DIA_Umpire_LCMSIDGen.jar diaumpire_module.params");
        return;
    }
    try {
        ConsoleLogger.SetConsoleLogger(Level.INFO);
        ConsoleLogger.SetFileLogger(Level.DEBUG,
                FilenameUtils.getFullPath(args[0]) + "diaumpire_lcmsidgen.log");
    } catch (Exception e) {
    }

    Logger.getRootLogger().info("Version: " + UmpireInfo.GetInstance().Version);
    Logger.getRootLogger().info("Parameter file:" + args[0]);

    BufferedReader reader = new BufferedReader(new FileReader(args[0]));
    String line = "";
    String WorkFolder = "";
    int NoCPUs = 2;

    TandemParam tandemPara = new TandemParam(DBSearchParam.SearchInstrumentType.TOF5600);
    HashMap<String, File> AssignFiles = new HashMap<>();

    //<editor-fold defaultstate="collapsed" desc="Reading parameter file">
    while ((line = reader.readLine()) != null) {
        line = line.trim();
        Logger.getRootLogger().info(line);
        if (!"".equals(line) && !line.startsWith("#")) {
            //System.out.println(line);
            if (line.equals("==File list begin")) {
                do {
                    line = reader.readLine();
                    line = line.trim();
                    if (line.equals("==File list end")) {
                        continue;
                    } else if (!"".equals(line)) {
                        File newfile = new File(line);
                        if (newfile.exists()) {
                            AssignFiles.put(newfile.getAbsolutePath(), newfile);
                        } else {
                            Logger.getRootLogger().info("File: " + newfile + " does not exist.");
                        }
                    }
                } while (!line.equals("==File list end"));
            }
            if (line.split("=").length < 2) {
                continue;
            }
            String type = line.split("=")[0].trim();
            String value = line.split("=")[1].trim();
            switch (type) {
            case "Path": {
                WorkFolder = value;
                break;
            }
            case "path": {
                WorkFolder = value;
                break;
            }
            case "Thread": {
                NoCPUs = Integer.parseInt(value);
                break;
            }
            case "DecoyPrefix": {
                if (!"".equals(value)) {
                    tandemPara.DecoyPrefix = value;
                }
                break;
            }
            case "PeptideFDR": {
                tandemPara.PepFDR = Float.parseFloat(value);
                break;
            }
            }
        }
    }
    //</editor-fold>

    //Initialize PTM manager using compomics library
    PTMManager.GetInstance();

    //Generate DIA file list
    ArrayList<DIAPack> FileList = new ArrayList<>();

    File folder = new File(WorkFolder);
    if (!folder.exists()) {
        Logger.getRootLogger().info("The path : " + WorkFolder + " cannot be found.");
        System.exit(1);
    }
    for (final File fileEntry : folder.listFiles()) {
        if (fileEntry.isFile()
                && (fileEntry.getAbsolutePath().toLowerCase().endsWith(".mzxml")
                        | fileEntry.getAbsolutePath().toLowerCase().endsWith(".mzml"))
                && !fileEntry.getAbsolutePath().toLowerCase().endsWith("q1.mzxml")
                && !fileEntry.getAbsolutePath().toLowerCase().endsWith("q2.mzxml")
                && !fileEntry.getAbsolutePath().toLowerCase().endsWith("q3.mzxml")) {
            AssignFiles.put(fileEntry.getAbsolutePath(), fileEntry);
        }
        if (fileEntry.isDirectory()) {
            for (final File fileEntry2 : fileEntry.listFiles()) {
                if (fileEntry2.isFile()
                        && (fileEntry2.getAbsolutePath().toLowerCase().endsWith(".mzxml")
                                | fileEntry2.getAbsolutePath().toLowerCase().endsWith(".mzml"))
                        && !fileEntry2.getAbsolutePath().toLowerCase().endsWith("q1.mzxml")
                        && !fileEntry2.getAbsolutePath().toLowerCase().endsWith("q2.mzxml")
                        && !fileEntry2.getAbsolutePath().toLowerCase().endsWith("q3.mzxml")) {
                    AssignFiles.put(fileEntry2.getAbsolutePath(), fileEntry2);
                }
            }
        }
    }

    Logger.getRootLogger().info("No. of files assigned :" + AssignFiles.size());
    for (File fileEntry : AssignFiles.values()) {
        Logger.getRootLogger().info(fileEntry.getAbsolutePath());
    }

    //process each DIA file to genearate untargeted identifications
    for (File fileEntry : AssignFiles.values()) {
        String mzXMLFile = fileEntry.getAbsolutePath();
        if (mzXMLFile.toLowerCase().endsWith(".mzxml") | mzXMLFile.toLowerCase().endsWith(".mzml")) {
            long time = System.currentTimeMillis();

            DIAPack DiaFile = new DIAPack(mzXMLFile, NoCPUs);
            FileList.add(DiaFile);
            Logger.getRootLogger().info(
                    "=================================================================================================");
            Logger.getRootLogger().info("Processing " + mzXMLFile);
            if (!DiaFile.LoadDIASetting()) {
                Logger.getRootLogger().info("Loading DIA setting failed, job is incomplete");
                System.exit(1);
            }
            if (!DiaFile.LoadParams()) {
                Logger.getRootLogger().info("Loading parameters failed, job is incomplete");
                System.exit(1);
            }
            Logger.getRootLogger().info("Loading identification results " + mzXMLFile + "....");

            DiaFile.ParsePepXML(tandemPara, null);
            DiaFile.BuildStructure();
            if (!DiaFile.MS1FeatureMap.ReadPeakCluster()) {
                Logger.getRootLogger().info("Loading peak and structure failed, job is incomplete");
                System.exit(1);
            }
            DiaFile.MS1FeatureMap.ClearMonoisotopicPeakOfCluster();
            //Generate mapping between index of precursor feature and pseudo MS/MS scan index 
            DiaFile.GenerateClusterScanNomapping();
            //Doing quantification
            DiaFile.AssignQuant();
            DiaFile.ClearStructure();

            DiaFile.IDsummary.ReduceMemoryUsage();
            time = System.currentTimeMillis() - time;
            Logger.getRootLogger().info(mzXMLFile + " processed time:"
                    + String.format("%d hour, %d min, %d sec", TimeUnit.MILLISECONDS.toHours(time),
                            TimeUnit.MILLISECONDS.toMinutes(time)
                                    - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(time)),
                            TimeUnit.MILLISECONDS.toSeconds(time)
                                    - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(time))));
        }
        Logger.getRootLogger().info("Job done");
        Logger.getRootLogger().info(
                "=================================================================================================");
    }
}

From source file:Main.java

public static long minutesOfNight(long secondsOfLight) {
    long secondsInHour = TimeUnit.HOURS.toSeconds(1);
    long secondsInDay = secondsInHour * 24;

    // differenza + 2 ore: un ora accesa dopo alba un ora accesa prima del tramonto
    // rimangono i minuti in cui le tecnologie dovranno rimanere accese
    return (secondsInDay - secondsOfLight) + 120;

}

From source file:Main.java

/**
 @param time input in milliseconds TODO: covert to seconds
 */// www  .j  a v  a  2s .  co m
public static String formatTimeMinutes(long time) {
    return String.format("%02d:%02d", TimeUnit.MILLISECONDS.toHours(time), TimeUnit.MILLISECONDS.toMinutes(time)
            - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(time)));
}