Example usage for java.util.concurrent TimeUnit DAYS

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

Introduction

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

Prototype

TimeUnit DAYS

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

Click Source Link

Document

Time unit representing twenty four hours.

Usage

From source file:pt.ua.tm.neji.batch.FileBatchExecutor.java

private int processFiles(final String inputFolderPath, final String inputWildcardFilter,
        final String outputFolderPath, final int numThreads, Context context,
        final Class<? extends Processor> processorCls, Object... args) {

    int filesProcessed = 0;
    File inputFolder = new File(inputFolderPath);
    FileFilter fileFilter = newFileFilter(inputWildcardFilter, compressed);
    File[] files = inputFolder.listFiles(fileFilter);

    logger.info("Starting thread pool with support for {} threads...", numThreads);
    ExecutorService executor = Executors.newFixedThreadPool(numThreads);

    LinkedList<Future> futures = new LinkedList<>();

    for (File file : files) {

        // Make corpus, output file
        Corpus corpus = new Corpus();

        // By default, the corpus identifier is the file name
        corpus.setIdentifier(FilenameUtils.getBaseName(file.getName()));

        // Make in/out corpus wrappers
        InputFile inputFile = new InputFile(corpus, file, compressed);
        List<OutputFile> outputFiles = new ArrayList<>();
        for (OutputFormat outputFormat : context.getConfiguration().getOutputFormats()) {
            File outFile = OutputFile.newOutputFile(outputFolderPath,
                    FilenameUtils.getBaseName(FilenameUtils.getBaseName(file.getName())), outputFormat,
                    compressed);//  w  ww . j av  a  2  s  . c  om
            outputFiles.add(new OutputFile(corpus, outFile, compressed));
        }

        if (storeDocuments) {
            processedCorpora.add(corpus);
        }

        Processor processor;
        try {
            processor = newProcessor(processorCls, context, inputFile, outputFiles, addAnnotationsWithoutIDs,
                    args);
        } catch (NejiException ex) {
            String m = "There was a problem creating the processor of the file: " + file.getAbsolutePath();
            logger.error(m, ex);
            throw new RuntimeException(m, ex);
        }

        Future submit = executor.submit(processor);
        futures.add(submit);
    }

    logger.info("");
    logger.info("{} file(s) to process.", futures.size());
    logger.info("Started processing...");

    Iterator<Future> it = futures.iterator();
    while (it.hasNext()) {
        Future future = it.next();
        try {
            Object o = future.get();
            future = null;
            it.remove();
            filesProcessed++;
        } catch (ExecutionException | InterruptedException ex) {
            String m = "There was a problem running the processor.";
            logger.error(m, ex);
        }
    }

    executor.shutdown();
    try {
        executor.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);
    } catch (InterruptedException ex) {
        String m = "There was a problem executing the processing tasks.";
        logger.error(m, ex);
        throw new RuntimeException(m, ex);
    }

    return filesProcessed;
}

From source file:com.breadwallet.BreadWalletApp.java

public void promptForAuthentication(Activity context, int mode, PaymentRequestEntity requestEntity,
        String message, String title, PaymentRequestWrapper paymentRequest, boolean forcePasscode) {
    Log.e(TAG, "promptForAuthentication: " + mode);
    if (context == null)
        return;/* w  w w . ja v a2  s .com*/
    KeyguardManager keyguardManager = (KeyguardManager) context.getSystemService(Activity.KEYGUARD_SERVICE);

    boolean useFingerPrint = ActivityCompat.checkSelfPermission(this,
            Manifest.permission.USE_FINGERPRINT) == PackageManager.PERMISSION_GRANTED
            && mFingerprintManager.isHardwareDetected() && mFingerprintManager.hasEnrolledFingerprints();
    if (mode == BRConstants.AUTH_FOR_PAY) {
        long limit = KeyStoreManager.getSpendLimit(context);
        long totalSent = BRWalletManager.getInstance(context).getTotalSent();

        if (requestEntity != null)
            if (limit <= totalSent + requestEntity.amount) {
                useFingerPrint = false;
            }
    }

    if (mode == BRConstants.AUTH_FOR_LIMIT || mode == BRConstants.AUTH_FOR_PHRASE) {
        useFingerPrint = false;
    }

    if (KeyStoreManager.getFailCount(context) != 0) {
        useFingerPrint = false;
    }
    long passTime = KeyStoreManager.getLastPasscodeUsedTime(context);
    if (passTime + TimeUnit.MILLISECONDS.convert(2, TimeUnit.DAYS) <= System.currentTimeMillis()) {
        useFingerPrint = false;
    }
    if (forcePasscode)
        useFingerPrint = false;

    if (keyguardManager.isKeyguardSecure()) {
        if (useFingerPrint) {
            // This happens when no fingerprints are registered.
            FingerprintDialogFragment fingerprintDialogFragment = new FingerprintDialogFragment();
            fingerprintDialogFragment.setMode(mode);
            fingerprintDialogFragment.setPaymentRequestEntity(requestEntity, paymentRequest);
            fingerprintDialogFragment.setMessage(message);
            fingerprintDialogFragment.setTitle(message != null ? "" : title);
            if (!context.isDestroyed())
                fingerprintDialogFragment.show(context.getFragmentManager(),
                        FingerprintDialogFragment.class.getName());
        } else {
            PasswordDialogFragment passwordDialogFragment = new PasswordDialogFragment();
            passwordDialogFragment.setMode(mode);
            passwordDialogFragment.setPaymentRequestEntity(requestEntity, paymentRequest);
            passwordDialogFragment.setVerifyOnlyTrue();
            passwordDialogFragment.setMessage(message);
            if (!context.isDestroyed())
                passwordDialogFragment.show(context.getFragmentManager(),
                        PasswordDialogFragment.class.getName());
        }
    } else {
        showDeviceNotSecuredWarning(context);
    }

}

From source file:dk.dma.ais.lib.FileConvert.java

/** {@inheritDoc} */
@Override//w  w  w . j  av a  2  s  . c  om
protected void run(Injector injector) throws Exception {
    configureFileEnding();

    final EConsumer<String> consumer = new EConsumer<String>() {

        @Override
        public void accept(String s) throws IllegalArgumentException, IllegalAccessException,
                NoSuchFieldException, SecurityException, IOException, InterruptedException {
            Path path = Paths.get(s);
            LOG.debug("Started processing file " + path);

            Path endPath;
            if (keepFileStructure) {
                Path relative;
                relative = path;
                endPath = Paths.get(Paths.get(convertTo).toString(), relative.toString());
                new File(endPath.toString()).mkdirs();
            } else {
                endPath = Paths.get("");
            }

            String filename = path.getFileName().toString();
            if (!filename.endsWith(fileEnding))
                filename = FilenameUtils.removeExtension(filename) + fileEnding;
            Path filePath = Paths.get(endPath.toString(), filename);

            LOG.debug("Output File: " + filePath.toString());

            final OutputStream fos = new FileOutputStream(filePath.toString()); // 2

            final boolean createSituationFolder = !StringUtils.isBlank(kmzSnapshotAt);
            final long snapshotAtEpochMillis = createSituationFolder
                    ? LocalDateTime.parse(kmzSnapshotAt, formatter).toInstant(ZoneOffset.UTC).toEpochMilli()
                    : -1;

            OutputStreamSink<AisPacket> sink;
            if ("kmz".equals(outputSinkFormat)) {
                //AisPacketKMZOutputSink(filter, createSituationFolder, createMovementsFolder, createTracksFolder, isPrimaryTarget, isSecondaryTarget, triggerSnapshot, snapshotDescriptionSupplier, movementInterpolationStep, supplyTitle, supplyDescription, iconHrefSupplier);
                sink = AisPacketOutputSinks.newKmzSink(e -> true, // this.filter = e -> true;
                        createSituationFolder, // this.createSituationFolder = true;
                        true, // createMovementsFolder = true;
                        true, // this.createTracksFolder = true;
                        e -> kmzPrimaryMmsi <= 0 ? false : e.tryGetAisMessage().getUserId() == kmzPrimaryMmsi, // this.isPrimaryTarget = e -> false;
                        e -> kmzSecondaryMmsi <= 0 ? false
                                : e.tryGetAisMessage().getUserId() == kmzSecondaryMmsi, // this.isSecondaryTarget = e -> false;
                        e -> e.getBestTimestamp() >= snapshotAtEpochMillis, // this.triggerSnapshot = e -> false;
                        () -> "Situation at " + kmzSnapshotAt, // this.snapshotDescriptionSupplier = null;
                        () -> 10, // this.title = defaultTitleSupplier;
                        () -> "description", // this.description = defaultDescriptionSupplier;
                        () -> "10", //this.movementInterpolationStep = defaultMovementInterpolationStepSupplier;
                        (shipTypeCargo, navigationalStatus) -> "" // this.iconHrefSupplier = defaultIconHrefSupplier;
                );

            } else
                sink = AisPacketOutputSinks.getOutputSink(outputSinkFormat, columns);

            sink.closeWhenFooterWritten();

            AisPacketReader apis = AisPacketReader.createFromFile(path, false);

            apis.writeTo(fos, sink);
            apis.close();
            fos.close();
        }
    };

    /*
     * Creates a pool of executors, 4 threads. Each thread will open a file using an aispacket reader, 10000 files can be
     * submitted to the queue, afterwards the calling thread will execute the job instead.
     */
    ThreadPoolExecutor threadpoolexecutor = new ThreadPoolExecutor(4, 4, 1, TimeUnit.SECONDS,
            new ArrayBlockingQueue<>(10000), new ThreadPoolExecutor.CallerRunsPolicy());
    for (final String s : sources) {
        threadpoolexecutor.execute(() -> {
            try {
                consumer.accept(s);
            } catch (Exception e) {
                e.printStackTrace();
            }

        });
    }

    threadpoolexecutor.shutdown();
    threadpoolexecutor.awaitTermination(999, TimeUnit.DAYS);
}

From source file:com.yahoo.pulsar.broker.loadbalance.impl.ModularLoadManagerImpl.java

/**
 * Initialize this load manager using the given PulsarService. Should be called only once, after invoking the
 * default constructor.//from  www  . j  av a2  s  . co m
 * 
 * @param pulsar
 *            The service to initialize with.
 */
public void initialize(final PulsarService pulsar) {
    adminCache = CacheBuilder.newBuilder().removalListener(new RemovalListener<String, PulsarAdmin>() {
        public void onRemoval(RemovalNotification<String, PulsarAdmin> removal) {
            removal.getValue().close();
        }
    }).expireAfterAccess(1, TimeUnit.DAYS).build(new CacheLoader<String, PulsarAdmin>() {
        @Override
        public PulsarAdmin load(String key) throws Exception {
            // key - broker name already is valid URL, has prefix "http://"
            return new PulsarAdmin(new URL(key),
                    pulsar.getConfiguration().getBrokerClientAuthenticationPlugin(),
                    pulsar.getConfiguration().getBrokerClientAuthenticationParameters());
        }
    });

    availableActiveBrokers = new ZooKeeperChildrenCache(pulsar.getLocalZkCache(),
            LoadManager.LOADBALANCE_BROKERS_ROOT);
    availableActiveBrokers.registerListener(new ZooKeeperCacheListener<Set<String>>() {
        @Override
        public void onUpdate(String path, Set<String> data, Stat stat) {
            if (log.isDebugEnabled()) {
                log.debug("Update Received for path {}", path);
            }
            scheduler.submit(ModularLoadManagerImpl.this::updateAll);
        }
    });

    brokerDataCache = new ZooKeeperDataCache<LocalBrokerData>(pulsar.getLocalZkCache()) {
        @Override
        public LocalBrokerData deserialize(String key, byte[] content) throws Exception {
            return ObjectMapperFactory.getThreadLocal().readValue(content, LocalBrokerData.class);
        }
    };

    brokerDataCache.registerListener(this);

    if (SystemUtils.IS_OS_LINUX) {
        brokerHostUsage = new LinuxBrokerHostUsageImpl(pulsar);
    } else {
        brokerHostUsage = new GenericBrokerHostUsageImpl(pulsar);
    }

    conf = pulsar.getConfiguration();

    // Initialize the default stats to assume for unseen bundles (hard-coded for now).
    defaultStats.msgThroughputIn = DEFAULT_MESSAGE_THROUGHPUT;
    defaultStats.msgThroughputOut = DEFAULT_MESSAGE_THROUGHPUT;
    defaultStats.msgRateIn = DEFAULT_MESSAGE_RATE;
    defaultStats.msgRateOut = DEFAULT_MESSAGE_RATE;

    localData = new LocalBrokerData(pulsar.getWebServiceAddress(), pulsar.getWebServiceAddressTls(),
            pulsar.getBrokerServiceUrl(), pulsar.getBrokerServiceUrlTls());
    placementStrategy = ModularLoadManagerStrategy.create(conf);
    policies = new SimpleResourceAllocationPolicies(pulsar);
    this.pulsar = pulsar;
    zkClient = pulsar.getZkClient();
}

From source file:org.lilyproject.testclientfw.BaseTestTool.java

public void stopExecutor() throws InterruptedException {
    executor.shutdown();//from   ww  w .  j ava  2s . c  om
    // There might be quite some jobs waiting in the queue, and we don't care how long they take to run
    // to an end
    boolean successfulFinish = executor.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);
    if (!successfulFinish) {
        System.out.println("Executor did not end successfully");
    }
    executor = null;
}

From source file:org.apache.kylin.job.impl.threadpool.DefaultScheduler.java

@Override
public synchronized void init(JobEngineConfig jobEngineConfig) throws SchedulerException {
    if (!initialized) {
        initialized = true;/*from  ww  w.j a v a  2s .c  o m*/
    } else {
        return;
    }
    String ZKConnectString = getZKConnectString(jobEngineConfig);
    if (StringUtils.isEmpty(ZKConnectString)) {
        throw new IllegalArgumentException("ZOOKEEPER_QUORUM is empty!");
    }

    this.jobEngineConfig = jobEngineConfig;
    RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
    this.zkClient = CuratorFrameworkFactory.newClient(ZKConnectString, retryPolicy);
    this.zkClient.start();
    this.sharedLock = new InterProcessMutex(zkClient, schedulerId());
    boolean hasLock = false;
    try {
        hasLock = sharedLock.acquire(3, TimeUnit.SECONDS);
    } catch (Exception e) {
        logger.warn("error acquire lock", e);
    }
    if (!hasLock) {
        logger.warn("fail to acquire lock, scheduler has not been started");
        zkClient.close();
        return;
    }
    executableManager = ExecutableManager.getInstance(jobEngineConfig.getConfig());
    //load all executable, set them to a consistent status
    fetcherPool = Executors.newScheduledThreadPool(1);
    int corePoolSize = jobEngineConfig.getMaxConcurrentJobLimit();
    jobPool = new ThreadPoolExecutor(corePoolSize, corePoolSize, Long.MAX_VALUE, TimeUnit.DAYS,
            new SynchronousQueue<Runnable>());
    context = new DefaultContext(Maps.<String, Executable>newConcurrentMap(), jobEngineConfig.getConfig());

    for (AbstractExecutable executable : executableManager.getAllExecutables()) {
        if (executable.getStatus() == ExecutableState.READY) {
            executableManager.updateJobOutput(executable.getId(), ExecutableState.ERROR, null,
                    "scheduler initializing work to reset job to ERROR status");
        }
    }
    executableManager.updateAllRunningJobsToError();

    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {
            logger.debug("Closing zk connection");
            try {
                shutdown();
            } catch (SchedulerException e) {
                logger.error("error shutdown scheduler", e);
            }
        }
    });

    fetcherPool.scheduleAtFixedRate(new FetcherRunner(), 10,
            ExecutableConstants.DEFAULT_SCHEDULER_INTERVAL_SECONDS, TimeUnit.SECONDS);
    hasStarted = true;
}

From source file:eu.stratuslab.marketplace.server.MarketPlaceApplication.java

private void init(String dataDir, String storeType, String fileStoreType) {
    setName("StratusLab Marketplace");
    setDescription("Marketplace for StratusLab images");
    setOwner("StratusLab");
    setAuthor("Stuart Kenny");

    getMetadataService().addExtension("multipart", MediaType.MULTIPART_FORM_DATA, false);
    getMetadataService().addExtension("www_form", MediaType.APPLICATION_WWW_FORM, false);
    getMetadataService().addExtension("application_rdf", MediaType.APPLICATION_RDF_XML, true);
    getMetadataService().addExtension("application_xml", MediaType.APPLICATION_XML, false);

    getMetadataService().setDefaultMediaType(MediaType.APPLICATION_XML);

    setStatusService(new MarketPlaceStatusService());

    getTunnelService().setUserAgentTunnel(true);

    this.dataDir = dataDir;

    boolean success = MetadataFileUtils.createIfNotExists(dataDir);
    if (!success) {
        LOGGER.severe("Unable to create directory: " + dataDir);
    }//  ww w .ja v a  2  s  .c o m

    success = MetadataFileUtils.createIfNotExists(Configuration.getParameterValue(PENDING_DIR));
    if (!success) {
        LOGGER.severe("Unable to create directory: " + Configuration.getParameterValue(PENDING_DIR));
    }

    whitelist = new EndorserWhitelist();

    RdfStoreFactory factory = new RdfStoreFactoryImpl();
    store = factory.createRdfStore(RdfStoreFactory.SESAME_PROVIDER, storeType);
    store.initialize();

    FileStore internalStore = null;

    if (fileStoreType.equals("file")) {
        internalStore = new FlatFileStore(dataDir);
    } else if (fileStoreType.equals("couchbase")) {
        internalStore = new CouchbaseStore(dataDir);
    }

    if (Configuration.getParameterValueAsBoolean(REPLICATION_ENABLED)) {
        fileStore = new GitStore(dataDir, internalStore);

        final Runnable update = new Runnable() {
            public void run() {
                rdfIndexUpdate();
            }
        };

        rdfUpdater = new RdfStoreUpdater(fileStore, new Processor(this));
        indexUpdateHandle = indexUpdater.scheduleWithFixedDelay(update, 1, 5, TimeUnit.MINUTES);
    } else {
        fileStore = internalStore;
    }

    queryBuilder = new SparqlBuilder();

    final Runnable remind = new Runnable() {
        public void run() {
            remind();
        }
    };

    final Runnable expires = new Runnable() {
        public void run() {
            expiry();
        }
    };

    reminder = new Reminder(this);
    expiry = new Reminder(this);

    if (Configuration.getParameterValueAsBoolean(ENDORSER_REMINDER)) {
        reminderHandle = scheduler.scheduleWithFixedDelay(remind, REMINDER_INTERVAL, REMINDER_INTERVAL,
                TimeUnit.DAYS);
        reminderHandle = scheduler.scheduleWithFixedDelay(expires, EXPIRY_INTERVAL, EXPIRY_INTERVAL,
                TimeUnit.DAYS);
    }

}

From source file:io.spring.initializr.web.project.MainController.java

private ResponseEntity<String> dependenciesFor(InitializrMetadataVersion version, String bootVersion) {
    InitializrMetadata metadata = this.metadataProvider.get();
    Version v = bootVersion != null ? Version.parse(bootVersion)
            : Version.parse(metadata.getBootVersions().getDefault().getId());
    DependencyMetadata dependencyMetadata = this.dependencyMetadataProvider.get(metadata, v);
    String content = new DependencyMetadataV21JsonMapper().write(dependencyMetadata);
    return ResponseEntity.ok().contentType(version.getMediaType()).eTag(createUniqueId(content))
            .cacheControl(CacheControl.maxAge(7, TimeUnit.DAYS)).body(content);
}

From source file:org.lbogdanov.poker.web.page.SessionPage.java

private String formatDate(Date created) {
    final long MILLIS_PER_WEEK = TimeUnit.DAYS.toMillis(7);
    Locale locale = getLocale();//from w ww .j ava 2 s .co  m
    PrettyTime prettyTime = new PrettyTime(locale);
    Duration largest = Iterables.getFirst(prettyTime.calculatePreciseDuration(created), null);
    if (largest != null && largest.getUnit().getMillisPerUnit() < MILLIS_PER_WEEK) {
        return prettyTime.format(largest);
    } else { // fallback to an absolute date string when difference is more than a week
        return DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, locale).format(created);
    }
}