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:org.thiesen.jiffs.jobs.clusterer.Clusterer.java

private Map<String, Long> findClusters() {
    final Iterable<StoryDBO> unprocessed = _storyDAO.findForClustering();
    final StopWatch watch = new StopWatch();

    watch.start();/* w w  w  .  j ava  2 s  .  co  m*/

    final Map<String, Long> foundClusters = Maps.newConcurrentMap();
    final Semaphore maxEnqueedTasks = new Semaphore(100000);
    final List<ClusterItem> clusterItems = Lists.newLinkedList(transform(unprocessed));
    final Iterator<ClusterItem> firstIterator = clusterItems.iterator();
    while (firstIterator.hasNext()) {
        final ClusterItem firstItem = firstIterator.next();
        for (final ClusterItem secondItem : clusterItems) {
            if (firstItem == secondItem) {
                continue;
            }
            EXECUTOR.submit(new ClusterFinder(maxEnqueedTasks, foundClusters, firstItem, secondItem));
            maxEnqueedTasks.acquireUninterruptibly();
        }
        firstIterator.remove();
    }

    EXECUTOR.shutdown();

    try {
        EXECUTOR.awaitTermination(1, TimeUnit.DAYS);
    } catch (InterruptedException e) {
        Thread.interrupted();
    }
    watch.stop();

    System.out.println("Clustering took " + watch);

    return foundClusters;
}

From source file:edu.msu.cme.rdp.kmer.cli.KmerCoverage.java

/**
 * This program maps the kmers from reads to kmers on each contig,
 * writes the mean, median coverage of each contig to a file
 * writes the kmer abundance to a file/*from   w ww .  j  av  a2 s.co  m*/
 * @param args
 * @throws IOException 
 */
public static void main(String[] args) throws IOException, InterruptedException {
    int kmerSize = 45;
    final int maxThreads;
    final int maxTasks = 1000;
    final PrintStream match_reads_out;
    try {
        CommandLine cmdLine = new PosixParser().parse(options, args);
        args = cmdLine.getArgs();
        if (args.length < 5) {
            throw new Exception("Unexpected number of arguments");
        }
        kmerSize = Integer.parseInt(args[0]);
        if (kmerSize > Kmer.max_nucl_kmer_size) {
            throw new Exception("kmerSize should be less than " + Kmer.max_nucl_kmer_size);
        }
        if (cmdLine.hasOption("match_reads_out")) {
            match_reads_out = new PrintStream(cmdLine.getOptionValue("match_reads_out"));
        } else {
            match_reads_out = null;
        }
        if (cmdLine.hasOption("threads")) {
            maxThreads = Integer.valueOf(cmdLine.getOptionValue("threads"));
            if (maxThreads >= Runtime.getRuntime().availableProcessors()) {
                System.err.println(" Runtime.getRuntime().availableProcessors() "
                        + Runtime.getRuntime().availableProcessors());
            }

        } else {
            maxThreads = 1;
        }

        final KmerCoverage kmerCoverage = new KmerCoverage(kmerSize, new SequenceReader(new File(args[1])));

        final AtomicInteger outstandingTasks = new AtomicInteger();
        ExecutorService service = Executors.newFixedThreadPool(maxThreads);

        Sequence seq;

        // parse one file at a time
        for (int index = 4; index < args.length; index++) {

            SequenceReader reader = new SequenceReader(new File(args[index]));
            while ((seq = reader.readNextSequence()) != null) {
                if (seq.getSeqString().length() < kmerSize) {
                    continue;
                }
                final Sequence threadSeq = seq;

                Runnable r = new Runnable() {

                    public void run() {
                        try {
                            kmerCoverage.processReads(threadSeq, match_reads_out);
                            outstandingTasks.decrementAndGet();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                };

                outstandingTasks.incrementAndGet();
                service.submit(r);

                while (outstandingTasks.get() >= maxTasks)
                    ;

            }
            reader.close();
        }
        service.shutdown();
        service.awaitTermination(1, TimeUnit.DAYS);

        kmerCoverage.printCovereage(new FileOutputStream(new File(args[2])),
                new FileOutputStream(new File(args[3])));
        if (match_reads_out != null) {
            match_reads_out.close();
        }
    } catch (Exception e) {
        new HelpFormatter().printHelp(
                "KmerCoverage <kmerSize> <query_file> <coverage_out> <abundance_out> <reads_file> <reads_file>...\nmaximum kmerSize "
                        + Kmer.max_nucl_kmer_size,
                options);
        e.printStackTrace();
        System.exit(1);
    }
}

From source file:uk.ac.cam.cl.dtg.segue.dao.content.GitContentManager.java

/**
 * Constructor for instantiating a new Git Content Manager Object.
 * /*w ww .j  a  v  a 2 s. c  om*/
 * @param database
 *            - that the content Manager manages.
 * @param searchProvider
 *            - search provider that the content manager manages and controls.
 * @param contentMapper
 *            - The utility class for mapping content objects.
 */
@Inject
public GitContentManager(final GitDb database, final ISearchProvider searchProvider,
        final ContentMapper contentMapper, final PropertiesLoader globalProperties) {
    this.database = database;
    this.mapper = contentMapper;
    this.searchProvider = searchProvider;
    this.globalProperties = globalProperties;
    this.allowOnlyPublishedContent = Boolean
            .parseBoolean(globalProperties.getProperty(Constants.SHOW_ONLY_PUBLISHED_CONTENT));

    if (this.allowOnlyPublishedContent) {
        log.info("API Configured to only allow published content to be returned.");
    }

    this.cache = CacheBuilder.newBuilder().softValues().expireAfterAccess(1, TimeUnit.DAYS).build();
}

From source file:com.room5.server.spring_boot.jmx.JMXServerStatistics.java

/**
 * Current uptime:  http://localhost:9191/jolokia/read/com.room5.jmx:name=JMXServerStatistics/Uptime
 *//*  w  w w.  j  av a2 s. c  o  m*/
@ManagedMetric(description = "Current system uptime.", displayName = "Current system uptime.", metricType = MetricType.COUNTER, currencyTimeLimit = 10)
public String getUptime() {
    long upTime = System.currentTimeMillis() - startTime;

    long days = TimeUnit.MILLISECONDS.toDays(upTime);
    long hoursRaw = TimeUnit.MILLISECONDS.toHours(upTime);
    long minutesRaw = TimeUnit.MILLISECONDS.toMinutes(upTime);

    //convert to string
    return String.format("%d days, %d hrs, %d min, %d sec", days, hoursRaw - TimeUnit.DAYS.toHours(days),
            minutesRaw - TimeUnit.HOURS.toMinutes(hoursRaw),
            TimeUnit.MILLISECONDS.toSeconds(upTime) - TimeUnit.MINUTES.toSeconds(minutesRaw));
}

From source file:org.carbondata.query.carbon.merger.impl.SortedScannedResultMerger.java

/**
 * Below method will be used to get the final query
 * return/* www.  ja  v a 2  s  .co  m*/
 *
 * @return iterator over result
 */
@Override
public CarbonIterator<Result> getQueryResultIterator() throws QueryExecutionException {
    execService.shutdown();
    try {
        execService.awaitTermination(1, TimeUnit.DAYS);
    } catch (InterruptedException e1) {
        LOGGER.error("Problem in thread termination" + e1.getMessage());
    }
    if (scannedResultList.size() > 0) {
        mergeScannedResults(scannedResultList);
        scannedResultList = null;
    }
    LOGGER.debug("Finished result merging from all slices");
    sortResult();
    return new MemoryBasedResultIterator(mergedScannedResult);
}

From source file:flpitu88.web.backend.psicoweb.services.AutenticacionUtilsService.java

@Override
@Transactional(readOnly = true)//from   w  w  w  .jav a 2 s.c o  m
public AutenticacionDTO issueToken(String email) {
    // Issue a token (can be a random String persisted to a database or a JWT token)
    // The issued token must be associated to a user
    // Return the issued token
    try {
        // Encode a JWT with default algorithm
        HashMap<String, Object> payload = new HashMap<>();

        long iat = System.currentTimeMillis();
        long expiracion = TimeUnit.MILLISECONDS.convert(30, TimeUnit.DAYS);

        payload.put("email", email);
        payload.put("iat", new Long(iat));
        payload.put("exp", new Long(iat + expiracion));
        //            payload.put("state", new HashMap<>());

        String token = Jwt.encode(payload, key);

        Usuario user = usDao.getUsuarioByMail(email);

        AutenticacionDTO autenticacionDTO = new AutenticacionDTO(token, user.getAdministrador());

        return autenticacionDTO;

    } catch (Exception e) {
        logger.log(Level.SEVERE, "No se ha podido generar el token para el usuario {0}", email);
    }
    return null;
}

From source file:org.sonatype.nexus.proxy.RequestFlagsTest.java

@Before
public void prepare() throws Exception {
    HttpServletResponse resp;/*from  ww w.j  av a 2s  .co m*/

    recordedRequestsBehaviour = new Record();
    // somewhere in near past
    lastModifiedSender = new LastModifiedSender(
            new Date(System.currentTimeMillis() - TimeUnit.DAYS.toMillis(3)));

    server = Proxy.withPort(0).serve(PATH)
            .withBehaviours(recordedRequestsBehaviour, lastModifiedSender, content(CONTENT)).start();
    nexus = lookup(Nexus.class);
    proxyRepository = createProxyRepository();

    // disable security
    final NexusConfiguration nexusConfiguration = lookup(NexusConfiguration.class);
    nexusConfiguration.setSecurityEnabled(false);
    nexusConfiguration.saveConfiguration();
}

From source file:com.vaushell.superpipes.tools.http.ImageExtractor.java

/**
 * Return the biggest image URI of this webpage.
 *
 * @param rootURI Webpage URI/* www .  j ava2 s . c  om*/
 * @return Biggest image
 * @throws IOException
 */
public BufferedImage extractBiggest(final URI rootURI) throws IOException {
    final List<URI> imagesURIs = new ArrayList<>();
    HttpEntity responseEntity = null;
    try {
        // Exec request
        final HttpGet get = new HttpGet(rootURI);

        try (final CloseableHttpResponse response = client.execute(get)) {
            final StatusLine sl = response.getStatusLine();
            if (sl.getStatusCode() != 200) {
                throw new IOException(sl.getReasonPhrase());
            }

            responseEntity = response.getEntity();

            try (final InputStream is = responseEntity.getContent()) {
                final Document doc = Jsoup.parse(is, "UTF-8", rootURI.toString());

                final Elements elts = doc.select("img");
                if (elts != null) {
                    for (final Element elt : elts) {
                        final String src = elt.attr("src");
                        if (src != null && !src.isEmpty()) {
                            try {
                                imagesURIs.add(rootURI.resolve(src));
                            } catch (final IllegalArgumentException ex) {
                                // Ignore wrong encoded URI
                            }
                        }
                    }
                }
            }
        }
    } finally {
        if (responseEntity != null) {
            EntityUtils.consume(responseEntity);
        }
    }

    final BufferedImage[] images = new BufferedImage[imagesURIs.size()];
    final ExecutorService service = Executors.newCachedThreadPool();
    for (int i = 0; i < imagesURIs.size(); ++i) {
        final int num = i;

        service.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    images[num] = HTTPhelper.loadPicture(client, imagesURIs.get(num));
                } catch (final IOException ex) {
                    images[num] = null;
                }
            }
        });
    }

    service.shutdown();

    try {
        service.awaitTermination(1L, TimeUnit.DAYS);
    } catch (final InterruptedException ex) {
        // Ignore
    }

    BufferedImage biggest = null;
    int biggestSize = Integer.MIN_VALUE;
    for (int i = 0; i < imagesURIs.size(); ++i) {
        if (images[i] != null) {
            final int actualSize = images[i].getWidth() * images[i].getHeight();
            if (actualSize > biggestSize) {
                biggest = images[i];

                biggestSize = actualSize;
            }
        }
    }

    return biggest;
}

From source file:com.cse3310.phms.ui.activities.AddAppointmentActivity.java

@AfterViews
void onSetupViews() {
    if (mSelectedDate != null) {
        appointmentTime = mSelectedDate.getTime();
    }//from w  w  w. j  a va 2 s  .c  om

    // set spinner to get early reminder time
    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.early_reminder_chose,
            android.R.layout.simple_spinner_item);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    mReminderSpinner.setAdapter(adapter);
    mReminderSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            switch (position) {
            case 0:
                earlyMillis = 0;
                break;
            case 1:
                earlyMillis = TimeUnit.MINUTES.toMillis(5);
                break;
            case 2:
                earlyMillis = TimeUnit.MINUTES.toMillis(10);
                break;
            case 3:
                earlyMillis = TimeUnit.MINUTES.toMillis(30);
                break;
            case 4:
                earlyMillis = TimeUnit.HOURS.toMillis(1);
                break;
            case 5:
                earlyMillis = TimeUnit.HOURS.toMillis(2);
                break;
            case 6:
                earlyMillis = TimeUnit.HOURS.toMillis(12);
                break;
            case 7:
                earlyMillis = TimeUnit.HOURS.toMillis(24);
                break;
            case 8:
                earlyMillis = TimeUnit.DAYS.toMillis(2);
                break;
            case 9:
                earlyMillis = TimeUnit.DAYS.toMillis(7);
                break;
            }
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    });

    mAppointmentView.setVisibility(View.GONE);
    mTimeButtonTextView.setText(MyDateFormatter.formatTime(mSelectedDate.getTime()));
}

From source file:com.ning.metrics.collector.processing.db.FeedEventSpoolProcessor.java

@Inject
public FeedEventSpoolProcessor(final CollectorConfig config, final SubscriptionStorage subscriptionStorage,
        final FeedEventStorage feedEventStorage, final Scheduler quartzScheduler) throws SchedulerException {
    this.config = config;
    this.subscriptionStorage = subscriptionStorage;
    this.feedEventStorage = feedEventStorage;
    this.eventStorageBuffer = new ArrayBlockingQueue<FeedEvent>(1000, false);
    this.executorShutdownTimeOut = config.getSpoolWriterExecutorShutdownTime();
    this.quartzScheduler = quartzScheduler;

    final List<String> eventTypesList = Splitter.on(config.getFilters()).omitEmptyStrings()
            .splitToList(config.getFiltersEventType());
    if (eventTypesList.contains(DBStorageTypes.FEED_EVENT.getDbStorageType())) {
        this.executorService = new LoggingExecutor(1, 1, Long.MAX_VALUE, TimeUnit.DAYS,
                new ArrayBlockingQueue<Runnable>(2), new NamedThreadFactory("FeedEvents-Storage-Threads"),
                new ThreadPoolExecutor.CallerRunsPolicy());
        this.executorService.submit(new FeedEventInserter(this.executorService, this));

        if (!quartzScheduler.isStarted()) {
            quartzScheduler.start();// ww  w .  ja  v  a  2 s.c o  m
            scheduleFeedEventCleanupCronJob();
        }
    } else {
        this.executorService = null;
    }

}