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:org.apache.hadoop.mapreduce.v2.hs.HistoryFileManager.java

protected ThreadPoolExecutor createMoveToDoneThreadPool(int numMoveThreads) {
    ThreadFactory tf = new ThreadFactoryBuilder().setNameFormat("MoveIntermediateToDone Thread #%d").build();
    return new ThreadPoolExecutor(numMoveThreads, numMoveThreads, 1, TimeUnit.HOURS,
            new LinkedBlockingQueue<Runnable>(), tf);
}

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

@Test
public void testKeyLessMessagesPassThrough() 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).create();
            Producer<byte[]> producerBatch = pulsarClient.newProducer().topic(topic).maxPendingMessages(3)
                    .enableBatching(true).batchingMaxMessages(3).batchingMaxPublishDelay(1, TimeUnit.HOURS)
                    .create()) {/*from w  w  w . j  a  v  a2 s .c o m*/
        producerNormal.newMessage().value("my-message-1".getBytes()).send();

        producerBatch.newMessage().value("my-message-2".getBytes()).sendAsync();
        producerBatch.newMessage().key("key1").value("my-message-3".getBytes()).sendAsync();
        producerBatch.newMessage().key("key1").value("my-message-4".getBytes()).send();

        producerBatch.newMessage().key("key2").value("my-message-5".getBytes()).sendAsync();
        producerBatch.newMessage().key("key2").value("my-message-6".getBytes()).sendAsync();
        producerBatch.newMessage().value("my-message-7".getBytes()).send();

        producerNormal.newMessage().value("my-message-8".getBytes()).send();
    }

    // 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.assertFalse(message1.hasKey());
        Assert.assertEquals(new String(message1.getData()), "my-message-1");

        Message<byte[]> message2 = consumer.receive();
        Assert.assertFalse(message2.hasKey());
        Assert.assertEquals(new String(message2.getData()), "my-message-2");

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

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

        Message<byte[]> message5 = consumer.receive();
        Assert.assertFalse(message5.hasKey());
        Assert.assertEquals(new String(message5.getData()), "my-message-7");

        Message<byte[]> message6 = consumer.receive();
        Assert.assertFalse(message6.hasKey());
        Assert.assertEquals(new String(message6.getData()), "my-message-8");
    }
}

From source file:com.eucalyptus.blockstorage.S3SnapshotTransfer.java

private void initializeEucaS3Client() throws SnapshotTransferException {
    if (role == null) {
        try {/*from w w w  .  j av  a2 s.c o  m*/
            role = BlockStorageUtil.checkAndConfigureBlockStorageAccount();
        } catch (Exception e) {
            LOG.error("Failed to initialize account for snapshot transfers due to " + e);
            throw new SnapshotTransferException("Failed to initialize eucalyptus account for snapshot transfes",
                    e);
        }
    }

    try {
        SecurityToken token = SecurityTokenManager.issueSecurityToken(role, (int) TimeUnit.HOURS.toSeconds(1));
        eucaS3Client = EucaS3ClientFactory.getEucaS3Client(
                new BasicSessionCredentials(token.getAccessKeyId(), token.getSecretKey(), token.getToken()));
    } catch (Exception e) {
        LOG.error("Failed to initialize S3 client for snapshot transfers due to " + e);
        throw new SnapshotTransferException("Failed to initialize S3 client for snapshot transfers", e);
    }
}

From source file:dentex.youtube.downloader.service.DownloadsService.java

private 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

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

From source file:org.bimserver.GeometryGenerator.java

@SuppressWarnings("unchecked")
public GenerateGeometryResult generateGeometry(long uoid, final PluginManager pluginManager,
        final DatabaseSession databaseSession, final IfcModelInterface model, final int pid, final int rid,
        final boolean store, GeometryCache geometryCache)
        throws BimserverDatabaseException, GeometryGeneratingException {
    GenerateGeometryResult generateGeometryResult = new GenerateGeometryResult();
    packageMetaData = model.getPackageMetaData();
    productClass = packageMetaData.getEClass("IfcProduct");
    productRepresentationClass = packageMetaData.getEClass("IfcProductRepresentation");
    geometryFeature = productClass.getEStructuralFeature("geometry");
    representationFeature = productClass.getEStructuralFeature("Representation");
    representationsFeature = productRepresentationClass.getEStructuralFeature("Representations");

    if (geometryCache != null && !geometryCache.isEmpty()) {
        returnCachedData(model, geometryCache, databaseSession, pid, rid);
        return null;
    }//  w  w w  . ja  v a 2s .  c  om
    long start = System.nanoTime();
    String pluginName = "";
    if (model.getPackageMetaData().getSchema() == Schema.IFC4) {
        pluginName = "org.bimserver.ifc.step.serializer.Ifc4StepSerializerPlugin";
    } else if (model.getPackageMetaData().getSchema() == Schema.IFC2X3TC1) {
        pluginName = "org.bimserver.ifc.step.serializer.Ifc2x3tc1StepSerializerPlugin";
    }

    try {
        final SerializerPlugin ifcSerializerPlugin = (SerializerPlugin) pluginManager.getPlugin(pluginName,
                true);
        if (ifcSerializerPlugin == null) {
            throw new UserException("No IFC serializer found");
        }

        User user = (User) databaseSession.get(uoid, OldQuery.getDefault());
        UserSettings userSettings = user.getUserSettings();
        RenderEnginePluginConfiguration defaultRenderEngine = userSettings.getDefaultRenderEngine();
        if (defaultRenderEngine == null) {
            throw new UserException("No default render engine has been selected for this user");
        }
        final RenderEnginePlugin renderEnginePlugin = pluginManager
                .getRenderEngine(defaultRenderEngine.getPluginDescriptor().getPluginClassName(), true);
        if (renderEnginePlugin == null) {
            throw new UserException("No (enabled) render engine found of type "
                    + defaultRenderEngine.getPluginDescriptor().getPluginClassName());
        }

        int maxSimultanousThreads = Math.min(
                bimServer.getServerSettingsCache().getServerSettings().getRenderEngineProcesses(),
                Runtime.getRuntime().availableProcessors());
        if (maxSimultanousThreads < 1) {
            maxSimultanousThreads = 1;
        }

        final RenderEngineSettings settings = new RenderEngineSettings();
        settings.setPrecision(Precision.SINGLE);
        settings.setIndexFormat(IndexFormat.AUTO_DETECT);
        settings.setGenerateNormals(true);
        settings.setGenerateTriangles(true);
        settings.setGenerateWireFrame(false);

        final RenderEngineFilter renderEngineFilter = new RenderEngineFilter();

        if (maxSimultanousThreads == 1) {
            Runner runner = new Runner(null, renderEnginePlugin, databaseSession, settings, store, model,
                    ifcSerializerPlugin, model, pid, rid, null, renderEngineFilter, generateGeometryResult);
            runner.run();
        } else {
            Set<EClass> classes = new HashSet<>();
            for (IdEObject object : model.getAllWithSubTypes(packageMetaData.getEClass("IfcProduct"))) {
                IdEObject representation = (IdEObject) object.eGet(representationFeature);
                if (representation != null
                        && ((List<?>) representation.eGet(representationsFeature)).size() > 0) {
                    classes.add(object.eClass());
                }
            }

            if (classes.size() == 0) {
                return null;
            }

            classes.remove(packageMetaData.getEClass("IfcAnnotation"));
            classes.remove(packageMetaData.getEClass("IfcOpeningElement"));

            LOGGER.debug("Using " + maxSimultanousThreads + " processes for geometry generation");
            ThreadPoolExecutor executor = new ThreadPoolExecutor(maxSimultanousThreads, maxSimultanousThreads,
                    24, TimeUnit.HOURS, new ArrayBlockingQueue<Runnable>(classes.size()));

            final Map<IdEObject, IdEObject> bigMap = new HashMap<IdEObject, IdEObject>();

            HideAllInversesObjectIDM idm = new HideAllInversesObjectIDM(
                    CollectionUtils.singleSet(packageMetaData.getEPackage()),
                    pluginManager.getMetaDataManager().getPackageMetaData("ifc2x3tc1").getSchemaDefinition());
            OidProvider oidProvider = new OidProvider() {
                @Override
                public long newOid(EClass eClass) {
                    return databaseSession.newOid(eClass);
                }
            };
            for (final EClass eClass : classes) {
                final BasicIfcModel targetModel = new BasicIfcModel(
                        pluginManager.getMetaDataManager().getPackageMetaData("ifc2x3tc1"), null);
                ModelHelper modelHelper = new ModelHelper(bimServer.getMetaDataManager(), targetModel);
                modelHelper.setOidProvider(oidProvider);
                modelHelper.setObjectIDM(idm);

                IdEObject newOwnerHistory = modelHelper.copyBasicObjects(model, bigMap);

                for (IdEObject idEObject : model.getAll(eClass)) {
                    IdEObject newObject = modelHelper.copy(idEObject, false,
                            ModelHelper.createObjectIdm(idEObject.eClass()));
                    modelHelper.copyDecomposes(idEObject, newOwnerHistory);
                    bigMap.put(newObject, idEObject);
                    if (eClass.getName().equals("IfcWallStandardCase")) {
                        EStructuralFeature hasOpeningsFeature = idEObject.eClass()
                                .getEStructuralFeature("HasOpenings");
                        for (IdEObject ifcRelVoidsElement : ((List<IdEObject>) idEObject
                                .eGet(hasOpeningsFeature))) {
                            bigMap.put(modelHelper.copy(ifcRelVoidsElement, false), ifcRelVoidsElement);
                            EStructuralFeature relatedOpeningElementFeature = ifcRelVoidsElement.eClass()
                                    .getEStructuralFeature("RelatedOpeningElement");
                            IdEObject relatedOpeningElement = (IdEObject) ifcRelVoidsElement
                                    .eGet(relatedOpeningElementFeature);
                            if (relatedOpeningElement != null) {
                                bigMap.put(modelHelper.copy(relatedOpeningElement, false),
                                        relatedOpeningElement);
                            }
                        }
                    }
                }

                executor.submit(new Runner(eClass, renderEnginePlugin, databaseSession, settings, store,
                        targetModel, ifcSerializerPlugin, model, pid, rid, bigMap, renderEngineFilter,
                        generateGeometryResult));
            }
            executor.shutdown();
            executor.awaitTermination(24, TimeUnit.HOURS);
        }

        long end = System.nanoTime();
        LOGGER.info("Rendertime: " + ((end - start) / 1000000) + "ms, " + "Reused: "
                + Formatters.bytesToString(bytesSaved.get()) + ", Total: "
                + Formatters.bytesToString(totalBytes.get()) + ", Final: "
                + Formatters.bytesToString(totalBytes.get() - bytesSaved.get()));
    } catch (Exception e) {
        LOGGER.error("", e);
        throw new GeometryGeneratingException(e);
    }
    return generateGeometryResult;
}

From source file:org.apache.flink.client.CliFrontend.java

/**
 * Sends a {@link org.apache.flink.runtime.messages.JobManagerMessages.TriggerSavepoint}
 * message to the job manager./*from w  w w . ja  va2s .  c  om*/
 */
private int triggerSavepoint(SavepointOptions options, JobID jobId, String savepointDirectory) {
    try {
        ActorGateway jobManager = getJobManagerGateway(options);

        logAndSysout("Triggering savepoint for job " + jobId + ".");
        Future<Object> response = jobManager.ask(new TriggerSavepoint(jobId, Option.apply(savepointDirectory)),
                new FiniteDuration(1, TimeUnit.HOURS));

        Object result;
        try {
            logAndSysout("Waiting for response...");
            result = Await.result(response, FiniteDuration.Inf());
        } catch (Exception e) {
            throw new Exception("Triggering a savepoint for the job " + jobId + " failed.", e);
        }

        if (result instanceof TriggerSavepointSuccess) {
            TriggerSavepointSuccess success = (TriggerSavepointSuccess) result;
            logAndSysout("Savepoint completed. Path: " + success.savepointPath());
            logAndSysout("You can resume your program from this savepoint with the run command.");

            return 0;
        } else if (result instanceof TriggerSavepointFailure) {
            TriggerSavepointFailure failure = (TriggerSavepointFailure) result;
            throw failure.cause();
        } else {
            throw new IllegalStateException("Unknown JobManager response of type " + result.getClass());
        }
    } catch (Throwable t) {
        return handleError(t);
    }
}

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

@Test
public void testEmptyPayloadDeletes() 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)
            .create();//w  w w  . ja  v  a2s  .  c om
            Producer<byte[]> producerBatch = pulsarClient.newProducer().topic(topic).maxPendingMessages(3)
                    .enableBatching(true).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();
    }

    // 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:com.caseystalnaker.android.popinvideodemo.fragments.Camera2VideoFragment.java

private void startCountdownTimer() {
    mCountdownTimerWrapper.setVisibility(LinearLayout.VISIBLE);
    mCountdownTimer = new CountDownTimer(Utils.VIDEO_TIME_LIMIT, 1000) {

        public void onTick(long millisUntilFinished) {
            mCountdownText.setText("" + String.format(Utils.COUNTDOWN_TIMER_FORMAT,
                    TimeUnit.MILLISECONDS.toHours(millisUntilFinished),
                    TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished)
                            - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millisUntilFinished)),
                    TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) - TimeUnit.MINUTES
                            .toSeconds(TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished))));
        }/*from w w  w .  jav a2  s .c  o  m*/

        public void onFinish() {
            stopRecordingVideo(true);
        }
    }.start();

}

From source file:org.computeforcancer.android.client.Monitor.java

private void sendNotification(long overall) {
    //Log.d("TEST", "sendNotification overall " + overall);
    String hours = String.format("%02d", TimeUnit.MILLISECONDS.toHours(overall));
    String minutes = String.format("%02d", TimeUnit.MILLISECONDS.toMinutes(overall)
            - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(overall)));
    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.notify_icon)
            .setContentTitle(getApplicationContext().getString(R.string.app_name))
            .setContentText(String.format(getString(R.string.notification), hours, minutes))
            .setStyle(new NotificationCompat.BigTextStyle()
                    .bigText(String.format(getString(R.string.notification), hours, minutes)));

    NotificationManager mNotificationManager = (NotificationManager) getSystemService(
            Context.NOTIFICATION_SERVICE);
    mNotificationManager.notify(1, mBuilder.build());
}

From source file:org.apache.carbondata.core.scan.executor.impl.AbstractQueryExecutor.java

/**
 * Below method will be used to finish the execution
 *
 * @throws QueryExecutionException//from  w w w . j  a  v a2 s . c  o  m
 */
@Override
public void finish() throws QueryExecutionException {
    CarbonUtil.clearBlockCache(queryProperties.dataBlocks);
    if (null != queryIterator) {
        queryIterator.close();
    }
    if (null != queryProperties.executorService) {
        queryProperties.executorService.shutdown();
        try {
            queryProperties.executorService.awaitTermination(1, TimeUnit.HOURS);
        } catch (InterruptedException e) {
            throw new QueryExecutionException(e);
        }
    }
}