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:dentex.youtube.downloader.utils.Utils.java

public static int getTotSeconds(Matcher timeMatcher) {
    int h = Integer.parseInt(timeMatcher.group(1));
    int m = Integer.parseInt(timeMatcher.group(2));
    int s = Integer.parseInt(timeMatcher.group(3));
    int f = Integer.parseInt(timeMatcher.group(4));

    long hToSec = TimeUnit.HOURS.toSeconds(h);
    long mToSec = TimeUnit.MINUTES.toSeconds(m);

    int tot = (int) (hToSec + mToSec + s);
    if (f > 50)
        tot = tot + 1;//w  w w. j a  v  a  2  s .c  o m

    //logger("v", "h=" + h + " m=" + m + " s=" + s + "." + f + " -> tot=" + tot,   DEBUG_TAG);
    return tot;
}

From source file:org.apache.pulsar.compaction.CompactionTest.java

@Test
public void testEmptyPayloadDeletesWhenCompressed() throws Exception {
    String topic = "persistent://my-property/use/my-ns/my-topic1";

    // subscribe before sending anything, so that we get all messages
    pulsarClient.newConsumer().topic(topic).subscriptionName("sub1").readCompacted(true).subscribe().close();

    try (Producer<byte[]> producerNormal = pulsarClient.newProducer().topic(topic).enableBatching(false)
            .compressionType(CompressionType.LZ4).create();
            Producer<byte[]> producerBatch = pulsarClient.newProducer().topic(topic).maxPendingMessages(3)
                    .enableBatching(true).compressionType(CompressionType.LZ4).batchingMaxMessages(3)
                    .batchingMaxPublishDelay(1, TimeUnit.HOURS).create()) {

        // key0 persists through it all
        producerNormal.newMessage().key("key0").value("my-message-0".getBytes()).send();

        // key1 is added but then deleted
        producerNormal.newMessage().key("key1").value("my-message-1".getBytes()).send();

        producerNormal.newMessage().key("key1").send();

        // key2 is added but deleted in same batch
        producerBatch.newMessage().key("key2").value("my-message-2".getBytes()).sendAsync();
        producerBatch.newMessage().key("key3").value("my-message-3".getBytes()).sendAsync();
        producerBatch.newMessage().key("key2").send();

        // key3 is added in previous batch, deleted in this batch
        producerBatch.newMessage().key("key3").sendAsync();
        producerBatch.newMessage().key("key4").value("my-message-3".getBytes()).sendAsync();
        producerBatch.newMessage().key("key4").send();

        // key4 is added, deleted, then resurrected
        producerNormal.newMessage().key("key4").value("my-message-4".getBytes()).send();
    }//  ww  w  . ja v  a 2s. co m

    // compact the topic
    Compactor compactor = new TwoPhaseCompactor(conf, pulsarClient, bk, compactionScheduler);
    compactor.compact(topic).get();

    try (Consumer<byte[]> consumer = pulsarClient.newConsumer().topic(topic).subscriptionName("sub1")
            .readCompacted(true).subscribe()) {
        Message<byte[]> message1 = consumer.receive();
        Assert.assertEquals(message1.getKey(), "key0");
        Assert.assertEquals(new String(message1.getData()), "my-message-0");

        Message<byte[]> message2 = consumer.receive();
        Assert.assertEquals(message2.getKey(), "key4");
        Assert.assertEquals(new String(message2.getData()), "my-message-4");
    }
}

From source file:la2launcher.MainFrame.java

private void jButton9ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton9ActionPerformed
    final long initTime = new Date().getTime();
    ReentrantLock lock = new ReentrantLock();
    final String patcherUrl = "http://" + updateHost + "/hf//updater.lst.la2";//new ArrayBlockingQueue<Runnable>(10000)
    final ThreadPoolExecutor tpe = new ThreadPoolExecutor(5, 5, 1, TimeUnit.HOURS,
            new ArrayBlockingQueue<Runnable>(10000));
    filesProcessed = 0;//from w  w w.ja  va2 s .com
    tpe.execute(new Runnable() {
        @Override
        public void run() {
            jTextArea2.setText("");
            DefaultTableModel model = (DefaultTableModel) jTable2.getModel();
            jProgressBar1.setMinimum(0);
            jProgressBar1.setMaximum(model.getRowCount());
            jProgressBar1.setValue(0);
            jLabel4.setText("0/" + model.getRowCount());
            for (int i = 0; i < model.getRowCount(); i++) {
                boolean checked = (Boolean) model.getValueAt(i, 1);
                String fileName = (String) model.getValueAt(i, 0);
                if (checked) {
                    tpe.execute(new Runnable() {
                        @Override
                        public void run() {

                            final String fileUrl = "http://" + updateHost + "/hf/" + fileName.replace("\\", "/")
                                    + ".la2";
                            try {
                                printMsg("  " + fileUrl);
                                File file = new File(gamePath + fileName + ".rar");
                                File fileExt = new File(gamePath + fileName);

                                file.getParentFile().mkdirs();
                                FileOutputStream fos = new FileOutputStream(file);
                                CloseableHttpClient httpclient = HttpClients.createDefault();
                                HttpGet httpGet = new HttpGet(fileUrl);
                                CloseableHttpResponse response1 = httpclient.execute(httpGet);

                                HttpEntity entity1 = response1.getEntity();
                                copyStream(entity1.getContent(), fos, new CopyListener() {
                                    @Override
                                    public void transfered(int n) {
                                        bytesRecieved += n;
                                        bytesRecievedTotal += n;
                                    }
                                });
                                response1.close();
                                fos.close();

                                printMsg("?? : " + fileName);

                                lock.lock();
                                //fixBzip2File(file);
                                //printMsg(" ?");

                                extractArchive(file.getAbsolutePath());

                                //BZip2CompressorInputStream bz = new BZip2CompressorInputStream(new FileInputStream(file));
                                //OutputStream pout = new FileOutputStream(fileExt);
                                //copyStream(archStream, pout, null);
                                //pout.close();
                                //archStream.close();
                                //jTextArea2.setText(jTextArea2.getText() + "\r\n? : " + fileName);
                                printMsg("? : " + fileName);
                                //file.delete();

                                //                                    File tgt = new File(gamePath + fileName);
                                //                                    if (tgt.exists()) {
                                //                                        tgt.delete();
                                //                                    }
                                //tgt.getParentFile().mkdirs();
                                //Files.move(fileExt.toPath(), new File(gamePath + fileName).toPath());
                                //jTextArea2.setText(jTextArea2.getText() + "\r\n ??: " + fileName);
                                printMsg(" ??: " + fileName);
                                jProgressBar1.setIndeterminate(false);
                                jLabel4.setText((++filesProcessed) + "/" + model.getRowCount());
                                jProgressBar1.setValue((int) filesProcessed);
                                lock.unlock();
                            } catch (IOException ex) {
                                Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
                            } catch (Exception ex) {
                                Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
                            }
                        }
                    });
                }
            }
        }
    });

    jButton5.setEnabled(false);
    jButton6.setEnabled(false);
    jButton7.setEnabled(false);
    jButton8.setEnabled(false);
    jButton9.setEnabled(false);
    jButton10.setEnabled(false);
    jProgressBar1.setIndeterminate(true);
    new Thread() {
        @Override
        public void run() {
            do {
                long millis = new Date().getTime();
                try {
                    sleep(300);
                } catch (InterruptedException ex) {
                    Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
                }
                millis = new Date().getTime() - millis;
                BigDecimal totBig = new BigDecimal(bytesRecievedTotal / (1024 * 1024.0));
                totBig = totBig.setScale(2, BigDecimal.ROUND_CEILING);
                jLabel5.setText("?: " + (bytesRecieved / millis) + "KB/s. : "
                        + totBig + " MB");
                bytesRecieved = 0;
            } while (tpe.getActiveCount() > 0);
            tpe.shutdown();
            jButton5.setEnabled(true);
            jButton6.setEnabled(true);
            jButton7.setEnabled(true);
            jButton8.setEnabled(true);
            jButton9.setEnabled(true);
            jButton10.setEnabled(true);
            jProgressBar1.setIndeterminate(false);
            printMsg("  " + (new Date().getTime() - initTime)
                    + " ?.");
        }
    }.start();
}

From source file:org.apache.hadoop.yarn.client.cli.TopCLI.java

String getHeader(QueueMetrics queueMetrics, NodesInformation nodes) {
    StringBuilder ret = new StringBuilder();
    String queue = "root";
    if (!queues.isEmpty()) {
        queue = StringUtils.join(queues, ",");
    }// w w w  .j  a v a  2  s  . co m
    long now = Time.now();
    long uptime = 0L;
    if (rmStartTime != -1) {
        uptime = now - rmStartTime;
    }
    long days = TimeUnit.MILLISECONDS.toDays(uptime);
    long hours = TimeUnit.MILLISECONDS.toHours(uptime)
            - TimeUnit.DAYS.toHours(TimeUnit.MILLISECONDS.toDays(uptime));
    long minutes = TimeUnit.MILLISECONDS.toMinutes(uptime)
            - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(uptime));
    String uptimeStr = String.format("%dd, %d:%d", days, hours, minutes);
    String currentTime = DateFormatUtils.ISO_TIME_NO_T_FORMAT.format(now);

    ret.append(CLEAR_LINE);
    ret.append(limitLineLength(String.format("YARN top - %s, up %s, %d active users, queue(s): %s%n",
            currentTime, uptimeStr, queueMetrics.activeUsers, queue), terminalWidth, true));

    ret.append(CLEAR_LINE);
    ret.append(limitLineLength(
            String.format(
                    "NodeManager(s): %d total, %d active, %d unhealthy, %d decommissioned,"
                            + " %d lost, %d rebooted%n",
                    nodes.totalNodes, nodes.runningNodes, nodes.unhealthyNodes, nodes.decommissionedNodes,
                    nodes.lostNodes, nodes.rebootedNodes),
            terminalWidth, true));

    ret.append(CLEAR_LINE);
    ret.append(limitLineLength(String.format(
            "Queue(s) Applications: %d running, %d submitted, %d pending,"
                    + " %d completed, %d killed, %d failed%n",
            queueMetrics.appsRunning, queueMetrics.appsSubmitted, queueMetrics.appsPending,
            queueMetrics.appsCompleted, queueMetrics.appsKilled, queueMetrics.appsFailed), terminalWidth,
            true));

    ret.append(CLEAR_LINE);
    ret.append(limitLineLength(
            String.format("Queue(s) Mem(GB): %d available," + " %d allocated, %d pending, %d reserved%n",
                    queueMetrics.availableMemoryGB, queueMetrics.allocatedMemoryGB,
                    queueMetrics.pendingMemoryGB, queueMetrics.reservedMemoryGB),
            terminalWidth, true));

    ret.append(CLEAR_LINE);
    ret.append(limitLineLength(
            String.format("Queue(s) VCores: %d available," + " %d allocated, %d pending, %d reserved%n",
                    queueMetrics.availableVCores, queueMetrics.allocatedVCores, queueMetrics.pendingVCores,
                    queueMetrics.reservedVCores),
            terminalWidth, true));

    ret.append(CLEAR_LINE);
    ret.append(limitLineLength(String.format("Queue(s) Containers: %d allocated, %d pending, %d reserved%n",
            queueMetrics.allocatedContainers, queueMetrics.pendingContainers, queueMetrics.reservedContainers),
            terminalWidth, true));
    return ret.toString();
}

From source file:fr.efl.chaine.xslt.GauloisPipe.java

public void doPostCloseService(ExecutionContext context) {
    try {/* www.ja  v a2  s  .co  m*/
        context.getService().awaitTermination(5, TimeUnit.HOURS);
        if (config.getSources().getListener().getJavastep() != null) {
            JavaStep javaStep = config.getSources().getListener().getJavastep();
            LOGGER.debug("creating " + javaStep.getStepClass().getName());
            try {
                StepJava stepJava = javaStep.getStepClass().newInstance();
                for (ParameterValue pv : javaStep.getParams()) {
                    stepJava.setParameter(pv.getKey(), new XdmAtomicValue(pv.getValue()));
                }
                for (ParameterValue pv : config.getParams().values()) {
                    // la substitution a t faite avant, dans le merge
                    stepJava.setParameter(pv.getKey(), new XdmAtomicValue(pv.getValue()));
                }
                Receiver r = stepJava.getReceiver(configurationFactory.getConfiguration());
                r.open();
                r.close();
            } catch (XPathException | SaxonApiException | InstantiationException | IllegalAccessException ex) {
                LOGGER.error("while preparing doPostCloseService", ex);
            }
        }
    } catch (InterruptedException ex) {
        LOGGER.error("[" + instanceName + "] multi-thread processing interrupted, 5 hour limit exceed.");
    }
}

From source file:org.nd4j.util.StringUtils.java

public static TimeUnit stringToTimeUnit(String str) {
    switch (str.toLowerCase()) {
    case "ms":
    case "millisecond":
    case "milliseconds":
        return TimeUnit.MILLISECONDS;
    case "s":
    case "sec":
    case "second":
    case "seconds":
        return TimeUnit.SECONDS;
    case "min":
    case "minute":
    case "minutes":
        return TimeUnit.MINUTES;
    case "h":
    case "hour":
    case "hours":
        return TimeUnit.HOURS;
    case "day":
    case "days":
        return TimeUnit.DAYS;
    default:// w  w w .j  a  v  a 2  s . co m
        throw new RuntimeException("Unknown time unit: \"" + str + "\"");
    }
}

From source file:com.sonymobile.android.media.testmediaplayer.MainActivity.java

private void setTimeOnView(TextView tv, int time) {
    tv.setText(String.format("%02d:%02d:%02d", 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))));
}

From source file:org.tinymediamanager.core.entities.MediaFile.java

License:asdf

/**
 * returns the duration / runtime formatted<br>
 * eg 1h 35m.// w w  w .  ja  v a2s.co m
 * 
 * @return the duration
 */
public String getDurationHM() {
    if (this.durationInSecs == 0) {
        return "";
    }
    long h = TimeUnit.SECONDS.toHours(this.durationInSecs);
    long m = TimeUnit.SECONDS.toMinutes(this.durationInSecs - TimeUnit.HOURS.toSeconds(h));
    long s = TimeUnit.SECONDS
            .toSeconds(this.durationInSecs - TimeUnit.HOURS.toSeconds(h) - TimeUnit.MINUTES.toSeconds(m));
    if (s > 30) {
        m += 1; // round seconds
    }
    return h + "h " + String.format("%02d", m) + "m";
}

From source file:org.tinymediamanager.core.entities.MediaFile.java

License:asdf

/**
 * returns the duration / runtime formatted<br>
 * eg 01:35:00.//from   ww w .  j  a v  a2  s  . c  o  m
 * 
 * @return the duration
 */
public String getDurationHHMMSS() {
    if (this.durationInSecs == 0) {
        return "";
    }
    long h = TimeUnit.SECONDS.toHours(this.durationInSecs);
    long m = TimeUnit.SECONDS.toMinutes(this.durationInSecs - TimeUnit.HOURS.toSeconds(h));
    long s = TimeUnit.SECONDS
            .toSeconds(this.durationInSecs - TimeUnit.HOURS.toSeconds(h) - TimeUnit.MINUTES.toSeconds(m));
    return String.format("%02d:%02d:%02d", h, m, s);
}

From source file:org.apache.pulsar.compaction.CompactionTest.java

@Test
public void testCompactCompressedBatching() throws Exception {
    String topic = "persistent://my-property/use/my-ns/my-topic1";

    // subscribe before sending anything, so that we get all messages
    pulsarClient.newConsumer().topic(topic).subscriptionName("sub1").readCompacted(true).subscribe().close();

    try (Producer<byte[]> producer = pulsarClient.newProducer().topic(topic)
            .compressionType(CompressionType.LZ4).maxPendingMessages(3).enableBatching(true)
            .batchingMaxMessages(3).batchingMaxPublishDelay(1, TimeUnit.HOURS).create()) {
        producer.newMessage().key("key1").value("my-message-1".getBytes()).sendAsync();
        producer.newMessage().key("key2").value("my-message-2".getBytes()).sendAsync();
        producer.newMessage().key("key2").value("my-message-3".getBytes()).send();
    }//from   w  w w .  j  ava  2s .c om

    // compact the topic
    Compactor compactor = new TwoPhaseCompactor(conf, pulsarClient, bk, compactionScheduler);
    compactor.compact(topic).get();

    try (Consumer<byte[]> consumer = pulsarClient.newConsumer().topic(topic).subscriptionName("sub1")
            .readCompacted(true).subscribe()) {
        Message<byte[]> message1 = consumer.receive();
        Assert.assertEquals(message1.getKey(), "key1");
        Assert.assertEquals(new String(message1.getData()), "my-message-1");

        Message<byte[]> message2 = consumer.receive();
        Assert.assertEquals(message2.getKey(), "key2");
        Assert.assertEquals(new String(message2.getData()), "my-message-3");
    }
}