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.metron.dataloads.bulk.ElasticsearchDataPrunerTest.java

@Test
public void testDeletesCorrectIndexes() throws Exception {

    //Mock Cluster Admin
    ClusterAdminClient clusterAdminClient = mock(ClusterAdminClient.class);
    ClusterStateRequestBuilder clusterStateRequestBuilder = mock(ClusterStateRequestBuilder.class);
    ClusterStateResponse clusterStateResponse = mock(ClusterStateResponse.class);
    ClusterState clusterState = mock(ClusterState.class);
    ObjectObjectHashMap<String, IndexMetaData> clusterIndexes = new ObjectObjectHashMap();
    MetaData clusterMetadata = mock(MetaData.class);
    when(adminClient.cluster()).thenReturn(clusterAdminClient);
    when(clusterAdminClient.prepareState()).thenReturn(clusterStateRequestBuilder);
    when(clusterStateRequestBuilder.get()).thenReturn(clusterStateResponse);
    when(clusterStateResponse.getState()).thenReturn(clusterState);
    when(clusterState.getMetaData()).thenReturn(clusterMetadata);

    int numDays = 5;

    Date indexDate = new Date();

    indexDate.setTime(testDate.getTime() - TimeUnit.DAYS.toMillis(numDays));

    for (int i = 0; i < numDays * 24; i++) {

        String indexName = "sensor_index_" + dateFormat.format(indexDate);
        clusterIndexes.put(indexName, null);
        indexDate.setTime(indexDate.getTime() + TimeUnit.HOURS.toMillis(1));

    }/*from w w  w .  j  a va 2  s . c o  m*/

    when(clusterMetadata.getIndices()).thenReturn(ImmutableOpenMap.copyOf(clusterIndexes));

    EasyMock.expect(deleteIndexResponse.isAcknowledged()).andReturn(true);

    replayAll();
    ElasticsearchDataPruner pruner = new ElasticsearchDataPruner(testDate, 1, configuration, indexClient,
            "sensor_index_");
    pruner.indexClient = indexClient;
    Long deleteCount = pruner.prune();
    assertEquals("Should have pruned 24 indices", 24L, deleteCount.longValue());
    verifyAll();

}

From source file:org.apache.hadoop.mapreduce.v2.app.launcher.ContainerLauncherImpl.java

protected void serviceStart() throws Exception {

    ThreadFactory tf = new ThreadFactoryBuilder().setNameFormat("ContainerLauncher #%d").setDaemon(true)
            .build();//w  ww .  ja v  a  2s . c o m

    // Start with a default core-pool size of 10 and change it dynamically.
    launcherPool = new ThreadPoolExecutor(initialPoolSize, Integer.MAX_VALUE, 1, TimeUnit.HOURS,
            new LinkedBlockingQueue<Runnable>(), tf);
    eventHandlingThread = new Thread() {
        @Override
        public void run() {
            ContainerLauncherEvent event = null;
            Set<String> allNodes = new HashSet<String>();

            while (!stopped.get() && !Thread.currentThread().isInterrupted()) {
                try {
                    event = eventQueue.take();
                } catch (InterruptedException e) {
                    if (!stopped.get()) {
                        LOG.error("Returning, interrupted : " + e);
                    }
                    return;
                }
                allNodes.add(event.getContainerMgrAddress());

                int poolSize = launcherPool.getCorePoolSize();

                // See if we need up the pool size only if haven't reached the
                // maximum limit yet.
                if (poolSize != limitOnPoolSize) {

                    // nodes where containers will run at *this* point of time. This is
                    // *not* the cluster size and doesn't need to be.
                    int numNodes = allNodes.size();
                    int idealPoolSize = Math.min(limitOnPoolSize, numNodes);

                    if (poolSize < idealPoolSize) {
                        // Bump up the pool size to idealPoolSize+initialPoolSize, the
                        // later is just a buffer so we are not always increasing the
                        // pool-size
                        int newPoolSize = Math.min(limitOnPoolSize, idealPoolSize + initialPoolSize);
                        LOG.info("Setting ContainerLauncher pool size to " + newPoolSize
                                + " as number-of-nodes to talk to is " + numNodes);
                        launcherPool.setCorePoolSize(newPoolSize);
                    }
                }

                // the events from the queue are handled in parallel
                // using a thread pool
                launcherPool.execute(createEventProcessor(event));

                // TODO: Group launching of multiple containers to a single
                // NodeManager into a single connection
            }
        }
    };
    eventHandlingThread.setName("ContainerLauncher Event Handler");
    eventHandlingThread.start();
    super.serviceStart();
}

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

/**
 * Execute the specified templates on the specified files to the specified
 * output directory on the specified number of threads.
 *
 * @param templates the specified templates
 * @param inputs the specified input files
 * @param outputDirectory the specified output directory
 * @param nbThreads the specified number of thread
 * @param processor the processor/*  w  w  w. ja v  a2 s  .co  m*/
 * @param listener The listener to start, if not null
 * @return <tt>false</tt> if an error occurs while processing.
 */
private boolean executesPipeOnMultiThread(final Pipe pipe, List<ParametrableFile> inputs, int nbThreads,
        Listener listener) {
    ExecutorService service = (nbThreads == 1) ? Executors.newSingleThreadExecutor(getThreadFactory())
            : Executors.newFixedThreadPool(nbThreads, getThreadFactory());
    // a try to solve multi-thread compiling problem...
    // that's a pretty dirty hack, but just a try, to test...
    if (xslCache.isEmpty() && !inputs.isEmpty()) {
        // in the opposite case, there is only a listener, and probably the first
        // file will be proccess alone...
        try {
            XsltTransformer transformer = buildTransformer(pipe, inputs.get(0).getFile(),
                    inputs.get(0).getFile().toURI().toURL().toExternalForm(),
                    ParametersMerger.merge(inputs.get(0).getParameters(), config.getParams()), messageListener,
                    null);
        } catch (IOException | InvalidSyntaxException | URISyntaxException | SaxonApiException ex) {
            String msg = "while pre-compiling for a multi-thread use...";
            LOGGER.error(msg);
            errors.add(new GauloisRunException(msg, ex));
        }
    }
    for (ParametrableFile pf : inputs) {
        final ParametrableFile fpf = pf;
        Runnable r = new Runnable() {
            @Override
            public void run() {
                try {
                    execute(pipe, fpf, messageListener);
                } catch (SaxonApiException | IOException | InvalidSyntaxException | URISyntaxException ex) {
                    String msg = "[" + instanceName + "] while processing " + fpf.getFile().getName();
                    LOGGER.error(msg, ex);
                    errors.add(new GauloisRunException(msg, fpf.getFile()));
                }
            }
        };
        service.execute(r);
    }
    if (listener == null) {
        // on ajoute plus rien
        service.shutdown();
        try {
            service.awaitTermination(5, TimeUnit.HOURS);
            return true;
        } catch (InterruptedException ex) {
            LOGGER.error("[" + instanceName + "] multi-thread processing interrupted, 5 hour limit exceed.");
            return false;
        }
    } else {
        ExecutionContext context = new ExecutionContext(this, pipe, messageListener, service);
        final HttpListener httpListener = new HttpListener(listener.getPort(), listener.getStopKeyword(),
                context);
        Runnable runner = new Runnable() {
            @Override
            public void run() {
                httpListener.run();
            }
        };
        new Thread(runner).start();
        return true;
    }
}

From source file:uk.codingbadgers.SurvivalPlus.SurvivalPlus.java

/**
 * @param time//  w w  w . j  a v a 2  s .  c  o m
 * @return
 */
public static String formatTime(Long time) {

    Long days = TimeUnit.MILLISECONDS.toDays(time);
    time = time - TimeUnit.DAYS.toMillis(days);

    Long hours = TimeUnit.MILLISECONDS.toHours(time);
    time = time - TimeUnit.HOURS.toMillis(hours);

    Long minutes = TimeUnit.MILLISECONDS.toMinutes(time);
    time = time - TimeUnit.MINUTES.toMillis(minutes);

    Long seconds = TimeUnit.MILLISECONDS.toSeconds(time);

    String formattedTime = "";
    if (days != 0) {
        formattedTime += (days == 1 ? "1 Day" : days + " Days");
    }

    if (hours != 0) {
        if (days != 0) {
            formattedTime += ", ";
        }
        formattedTime += (hours == 1 ? "1 Hour" : hours + " Hours");
    }

    if (minutes != 0) {
        if (days != 0 || hours != 0) {
            formattedTime += ", ";
        }
        formattedTime += (minutes == 1 ? "1 Minute" : minutes + " Minutes");
    }

    if (seconds != 0) {
        if (days != 0 || hours != 0 || minutes != 0) {
            formattedTime += ", ";
        }
        formattedTime += (seconds == 1 ? "1 Second" : seconds + " Seconds");
    }

    return formattedTime;
}

From source file:org.apache.hadoop.hdfs.server.datanode.DiskBalancer.java

/**
 * Verifies that this plan is not older than 24 hours.
 *
 * @param plan - Node Plan//w ww.j a  va2s . com
 */
private void verifyTimeStamp(NodePlan plan) throws DiskBalancerException {
    long now = Time.now();
    long planTime = plan.getTimeStamp();

    // TODO : Support Valid Plan hours as a user configurable option.
    if ((planTime + (TimeUnit.HOURS.toMillis(DiskBalancerConstants.DISKBALANCER_VALID_PLAN_HOURS))) < now) {
        String hourString = "Plan was generated more than "
                + Integer.toString(DiskBalancerConstants.DISKBALANCER_VALID_PLAN_HOURS) + " hours ago.";
        LOG.error("Disk Balancer - " + hourString);
        throw new DiskBalancerException(hourString, DiskBalancerException.Result.OLD_PLAN_SUBMITTED);
    }
}

From source file:org.apache.marmotta.kiwi.infinispan.embedded.InfinispanEmbeddedCacheManager.java

/**
 * Return the URI -> namespace cache from the cache manager. Used for looking up namespaces
 * @return/*from w  w  w. ja  v a 2  s .  co  m*/
 */
public Map getNamespaceUriCache() {
    if (nsUriCache == null) {
        if (isClustered()) {
            Configuration nsuriConfiguration = new ConfigurationBuilder().read(defaultConfiguration)
                    .clustering().cacheMode(CacheMode.REPL_ASYNC).eviction()
                    .maxEntries(config.getNamespaceCacheSize()).expiration().lifespan(1, TimeUnit.DAYS).build();
            cacheManager.defineConfiguration(NS_URI_CACHE, nsuriConfiguration);
        } else {
            Configuration nsuriConfiguration = new ConfigurationBuilder().read(defaultConfiguration).eviction()
                    .maxEntries(config.getNamespaceCacheSize()).expiration().lifespan(1, TimeUnit.HOURS)
                    .build();
            cacheManager.defineConfiguration(NS_URI_CACHE, nsuriConfiguration);
        }

        nsUriCache = new AsyncMap(cacheManager.getCache(NS_URI_CACHE).getAdvancedCache()
                .withFlags(Flag.SKIP_LOCKING, Flag.SKIP_CACHE_LOAD, Flag.SKIP_REMOTE_LOOKUP));
    }
    return nsUriCache;
}

From source file:de.mendelson.comm.as2.client.AS2Gui.java

/**
 * Creates new form NewJFrame/* w  ww.  j  a  v a2  s  .  co m*/
 */
public AS2Gui(Splash splash, String host) {
    this.host = host;
    //Set System default look and feel
    try {
        //support the command line option -Dswing.defaultlaf=...
        if (System.getProperty("swing.defaultlaf") == null) {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        }
    } catch (Exception e) {
        this.logger.warning(this.getClass().getName() + ":" + e.getMessage());
    }
    //load resource bundle
    try {
        this.rb = (MecResourceBundle) ResourceBundle.getBundle(ResourceBundleAS2Gui.class.getName());
    } catch (MissingResourceException e) {
        throw new RuntimeException("Oops..resource bundle " + e.getClassName() + " not found.");
    }
    initComponents();
    this.jButtonNewVersion.setVisible(false);
    this.jPanelRefreshWarning.setVisible(false);
    //set preference values to the GUI
    this.setBounds(this.clientPreferences.getInt(PreferencesAS2.FRAME_X),
            this.clientPreferences.getInt(PreferencesAS2.FRAME_Y),
            this.clientPreferences.getInt(PreferencesAS2.FRAME_WIDTH),
            this.clientPreferences.getInt(PreferencesAS2.FRAME_HEIGHT));
    //ensure to display all messages
    this.getLogger().setLevel(Level.ALL);
    LogConsolePanel consolePanel = new LogConsolePanel(this.getLogger());
    //define the colors for the log levels
    consolePanel.setColor(Level.SEVERE, LogConsolePanel.COLOR_BROWN);
    consolePanel.setColor(Level.WARNING, LogConsolePanel.COLOR_BLUE);
    consolePanel.setColor(Level.INFO, LogConsolePanel.COLOR_BLACK);
    consolePanel.setColor(Level.CONFIG, LogConsolePanel.COLOR_DARK_GREEN);
    consolePanel.setColor(Level.FINE, LogConsolePanel.COLOR_DARK_GREEN);
    consolePanel.setColor(Level.FINER, LogConsolePanel.COLOR_DARK_GREEN);
    consolePanel.setColor(Level.FINEST, LogConsolePanel.COLOR_DARK_GREEN);
    this.jPanelServerLog.add(consolePanel);
    this.setTitle(AS2ServerVersion.getProductName() + " " + AS2ServerVersion.getVersion());
    //initialize the help system if available
    this.initializeJavaHelp();
    this.jTableMessageOverview.getSelectionModel().addListSelectionListener(this);
    this.jTableMessageOverview.getTableHeader().setReorderingAllowed(false);
    //icon columns
    TableColumn column = this.jTableMessageOverview.getColumnModel().getColumn(0);
    column.setMaxWidth(20);
    column.setResizable(false);
    column = this.jTableMessageOverview.getColumnModel().getColumn(1);
    column.setMaxWidth(20);
    column.setResizable(false);
    this.jTableMessageOverview.setDefaultRenderer(Date.class,
            new TableCellRendererDate(DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT)));
    //add row sorter
    RowSorter<TableModel> sorter = new TableRowSorter<TableModel>(this.jTableMessageOverview.getModel());
    jTableMessageOverview.setRowSorter(sorter);
    sorter.addRowSorterListener(this);
    this.jPanelFilterOverview.setVisible(this.showFilterPanel);
    this.jMenuItemHelpForum.setEnabled(Desktop.isDesktopSupported());
    //destroy splash, possible login screen for the client should come up
    if (splash != null) {
        splash.destroy();
    }
    this.setButtonState();
    this.jTableMessageOverview.addMouseListener(this);
    //popup menu issues
    this.jPopupMenu.setInvoker(this.jScrollPaneMessageOverview);
    this.jPopupMenu.addPopupMenuListener(this);
    super.addMessageProcessor(this);
    //perform the connection to the server
    //warning! this works for localhost only so far
    int clientServerCommPort = this.clientPreferences.getInt(PreferencesAS2.CLIENTSERVER_COMM_PORT);
    if (splash != null) {
        splash.destroy();
    }
    this.browserLinkedPanel.cyleText(new String[] {
            "For additional EDI software to convert and process your data please contact <a href='http://www.mendelson-e-c.com'>mendelson-e-commerce GmbH</a>",
            "To buy a commercial license please visit the <a href='http://shop.mendelson-e-c.com/'>mendelson online shop</a>",
            "Most trading partners demand a trusted certificate - Order yours at the <a href='http://ca.mendelson-e-c.com'>mendelson CA</a> now!",
            "Looking for additional secure data transmission software? Try the <a href='http://oftp2.mendelson-e-c.com'>mendelson OFTP2</a> solution!",
            "You want to send EDIFACT data from your SAP system? Ask <a href='mailto:info@mendelson.de?subject=Please%20inform%20me%20about%20your%20SAP%20integration%20solutions'>mendelson-e-commerce GmbH</a> for a solution.",
            "You need a secure FTP solution? <a href='mailto:info@mendelson.de?subject=Please%20inform%20me%20about%20your%20SFTP%20solution'>Ask us</a> for the mendelson SFTP software.",
            "Convert flat files, EDIFACT, SAP IDos, VDA, inhouse formats? <a href='mailto:info@mendelson.de?subject=Please%20inform%20me%20about%20your%20converter%20solution'>Ask us</a> for the mendelson EDI converter.",
            "For commercial support of this software please buy a license at <a href='http://as2.mendelson-e-c.com'>the mendelson AS2</a> website.",
            "Have a look at the <a href='http://www.mendelson-e-c.com/products_mbi.php'>mendelson business integration</a> for a powerful EDI solution.",
            "The <a href='mailto:info@mendelson.de?subject=Please%20inform%20me%20about%20your%20RosettaNet%20solution'>mendelson RosettaNet solution</a> supports RNIF 1.1 and RNIF 2.0.",
            "The <a href='http://www.mendelson-e-c.com/products_ide.php'>mendelson converter IDE</a> is the graphical mapper for the mendelson converter.",
            "To process any XML data and convert it to EDIFACT, VDA, flat files, IDocs and inhouse formats use <a href='http://www.mendelson-e-c.com/products_converter.php'>the mendelson converter</a>.",
            "To transmit your EDI data via HTTP/S please <a href='mailto:info@mendelson.de?subject=Please%20inform%20me%20about%20your%20HTTPS%20solution'>ask us</a> for the mendelson HTTPS solution.",
            "If you have questions regarding this product please refer to the <a href='http://community.mendelson-e-c.com/'>mendelson community</a>.", });
    this.connect(new InetSocketAddress(host, clientServerCommPort), 5000);
    Runnable dailyNewsThread = new Runnable() {

        @Override
        public void run() {
            while (true) {
                long lastUpdateCheck = Long.valueOf(clientPreferences.get(PreferencesAS2.LAST_UPDATE_CHECK));
                //check only once a day even if the system is started n times a day
                if (lastUpdateCheck < (System.currentTimeMillis() - TimeUnit.HOURS.toMillis(23))) {
                    clientPreferences.put(PreferencesAS2.LAST_UPDATE_CHECK,
                            String.valueOf(System.currentTimeMillis()));
                    jButtonNewVersion.setVisible(false);
                    String version = (AS2ServerVersion.getVersion() + " " + AS2ServerVersion.getBuild())
                            .replace(' ', '+');
                    Header[] header = htmlPanel.setURL(
                            "http://www.mendelson.de/en/mecas2/client_welcome.php?version=" + version,
                            AS2ServerVersion.getProductName() + " " + AS2ServerVersion.getVersion(),
                            new File("start/client_welcome.html"));
                    if (header != null) {
                        String downloadURL = null;
                        String actualBuild = null;
                        for (Header singleHeader : header) {
                            if (singleHeader.getName().equals("x-actual-build")) {
                                actualBuild = singleHeader.getValue().trim();
                            }
                            if (singleHeader.getName().equals("x-download-url")) {
                                downloadURL = singleHeader.getValue().trim();
                            }
                        }
                        if (downloadURL != null && actualBuild != null) {
                            try {
                                int thisBuild = AS2ServerVersion.getBuildNo();
                                int availableBuild = Integer.valueOf(actualBuild);
                                if (thisBuild < availableBuild) {
                                    jButtonNewVersion.setVisible(true);
                                }
                                downloadURLNewVersion = downloadURL;
                            } catch (Exception e) {
                                //nop
                            }
                        }
                    }
                } else {
                    htmlPanel.setPage(new File("start/client_welcome.html"));
                }
                try {
                    //check once a day for new update
                    Thread.sleep(TimeUnit.DAYS.toMillis(1));
                } catch (InterruptedException e) {
                    //nop
                }
            }
        }
    };
    Executors.newSingleThreadExecutor().submit(dailyNewsThread);
    this.as2StatusBar.setConnectedHost(this.host);
}

From source file:org.alfresco.dataprep.ContentAspects.java

/**
 * Method to add Restrictable Aspect /*from  ww  w .  ja  v  a2 s  .  c  o m*/
 * 
 * @param userName login username
 * @param password login password
 * @param siteName site name
 * @param contentName file or folder name
 * @param hours no of hours for OfflineExpiresAfter property
 */
public void addRestrictable(final String userName, final String password, final String siteName,
        final String contentName, final int hours) {
    Session session = getCMISSession(userName, password);
    addAspect(session, siteName, contentName, DocumentAspect.RESTRICTABLE);
    long milliseconds = TimeUnit.HOURS.toMillis(hours);
    Map<String, Object> propertyMap = new HashMap<String, Object>();
    propertyMap.put("dp:offlineExpiresAfter", milliseconds);
    String contentNodeRef = getNodeRef(userName, password, siteName, contentName);
    addProperties(session, contentNodeRef, propertyMap);
}

From source file:org.alfresco.extension.bulkimport.impl.Scanner.java

/**
 * Awaits completion of the import, by checking if the import thread pool
 * and associated queue are empty, with sleeps in between polls.
 * /*from  w w  w .j  av a  2s. c o m*/
 * @throws InterruptedException If a sleep is interrupted.
 */
private final void awaitCompletion() throws InterruptedException {
    if (multiThreadedImport) {
        // Log status then wait for everything to wrap up...
        if (debug(log))
            debug(log, "Scanning complete. Waiting for completion of multithreaded import.");
        logStatusInfo();
    }

    importThreadPool.shutdown(); // Orderly shutdown (lets the queue drain)

    // Log status every hour, then go back to waiting - in single threaded case this won't wait at all
    while (!importThreadPool.awaitTermination(1, TimeUnit.HOURS)) {
        logStatusInfo();
    }
}

From source file:ch.cern.db.flume.sink.elasticsearch.ElasticSearchSink.java

private long parseTTL(String ttl) {
    matcher = matcher.reset(ttl);// ww w.  j a v a2  s  .  c  o m
    while (matcher.find()) {
        if (matcher.group(2).equals("ms")) {
            return Long.parseLong(matcher.group(1));
        } else if (matcher.group(2).equals("s")) {
            return TimeUnit.SECONDS.toMillis(Integer.parseInt(matcher.group(1)));
        } else if (matcher.group(2).equals("m")) {
            return TimeUnit.MINUTES.toMillis(Integer.parseInt(matcher.group(1)));
        } else if (matcher.group(2).equals("h")) {
            return TimeUnit.HOURS.toMillis(Integer.parseInt(matcher.group(1)));
        } else if (matcher.group(2).equals("d")) {
            return TimeUnit.DAYS.toMillis(Integer.parseInt(matcher.group(1)));
        } else if (matcher.group(2).equals("w")) {
            return TimeUnit.DAYS.toMillis(7 * Integer.parseInt(matcher.group(1)));
        } else if (matcher.group(2).equals("")) {
            logger.info("TTL qualifier is empty. Defaulting to day qualifier.");
            return TimeUnit.DAYS.toMillis(Integer.parseInt(matcher.group(1)));
        } else {
            logger.debug("Unknown TTL qualifier provided. Setting TTL to 0.");
            return 0;
        }
    }
    logger.info("TTL not provided. Skipping the TTL config by returning 0.");
    return 0;
}