Example usage for java.util.concurrent TimeUnit MILLISECONDS

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

Introduction

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

Prototype

TimeUnit MILLISECONDS

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

Click Source Link

Document

Time unit representing one thousandth of a second.

Usage

From source file:org.jdal.text.PeriodFormatter.java

/**
 * {@inheritDoc}/*from w  w w .  jav a2s  .  c  o m*/
 */
public String print(Number number, Locale locale) {
    long period = number.longValue();
    long days = TimeUnit.MILLISECONDS.toDays(period);
    long left = period - TimeUnit.DAYS.toMillis(days);
    long hours = TimeUnit.MILLISECONDS.toHours(left);
    left -= TimeUnit.HOURS.toMillis(hours);
    long minutes = TimeUnit.MILLISECONDS.toMinutes(left);
    left -= TimeUnit.MINUTES.toMillis(minutes);
    long seconds = TimeUnit.MILLISECONDS.toSeconds(left);

    StringBuilder sb = new StringBuilder();

    if (days != 0)
        append(sb, days, DAYS);

    if (hours != 0)
        append(sb, hours, HOURS);

    if (minutes != 0)
        append(sb, minutes, MINUTES);

    if (seconds != 0)
        append(sb, seconds, SECONDS);

    return sb.toString();
}

From source file:Main.java

/**
 * This method returns the number of days since the epoch (January 01, 1970, 12:00 Midnight UTC)
 * in UTC time from the current date.//from  w  w w .  ja  va  2  s  . c  om
 *
 * @param utcDate A date in milliseconds in UTC time.
 *
 * @return The number of days from the epoch to the date argument.
 */
private static long elapsedDaysSinceEpoch(long utcDate) {
    return TimeUnit.MILLISECONDS.toDays(utcDate);
}

From source file:cn.leancloud.diamond.io.watch.WatchService.java

public WatchService(long checkInterval) {
    service = Executors.newSingleThreadScheduledExecutor();
    service.scheduleAtFixedRate(new CheckThread(), checkInterval, checkInterval, TimeUnit.MILLISECONDS);
}

From source file:au.com.jwatmuff.eventmanager.Main.java

/**
 * Main method.//ww w.  ja  v a  2s .  co  m
 */
public static void main(String args[]) {
    LogUtils.setupUncaughtExceptionHandler();

    /* Set timeout for RMI connections - TODO: move to external file */
    System.setProperty("sun.rmi.transport.tcp.handshakeTimeout", "2000");
    updateRmiHostName();

    /*
     * Set up menu bar for Mac
     */
    System.setProperty("apple.laf.useScreenMenuBar", "true");
    System.setProperty("com.apple.mrj.application.apple.menu.about.name", "Event Manager");

    /*
     * Set look and feel to 'system' style
     */
    try {
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    } catch (Exception e) {
        log.info("Failed to set system look and feel");
    }

    /*
     * Set workingDir to a writable folder for storing competitions, settings etc.
     */
    String applicationData = System.getenv("APPDATA");
    if (applicationData != null) {
        workingDir = new File(applicationData, "EventManager");
        if (workingDir.exists() || workingDir.mkdirs()) {
            // redirect logging to writable folder
            LogUtils.reconfigureFileAppenders("log4j.properties", workingDir);
        } else {
            workingDir = new File(".");
        }
    }

    // log version for debugging
    log.info("Running version: " + VISIBLE_VERSION + " (Internal: " + VERSION + ")");

    /*
     * Copy license if necessary
     */
    File license1 = new File("license.lic");
    File license2 = new File(workingDir, "license.lic");
    if (license1.exists() && !license2.exists()) {
        try {
            FileUtils.copyFile(license1, license2);
        } catch (IOException e) {
            log.warn("Failed to copy license from " + license1 + " to " + license2, e);
        }
    }
    if (license1.exists() && license2.exists()) {
        if (license1.lastModified() > license2.lastModified()) {
            try {
                FileUtils.copyFile(license1, license2);
            } catch (IOException e) {
                log.warn("Failed to copy license from " + license1 + " to " + license2, e);
            }
        }
    }

    /*
     * Check if run lock exists, if so ask user if it is ok to continue
     */
    if (!obtainRunLock(false)) {
        int response = JOptionPane.showConfirmDialog(null,
                "Unable to obtain run-lock.\nPlease ensure that no other instances of EventManager are running before continuing.\nDo you wish to continue?",
                "Run-lock detected", JOptionPane.YES_NO_OPTION);
        if (response == JOptionPane.YES_OPTION)
            obtainRunLock(true);
        else
            System.exit(0);
    }

    try {
        LoadWindow loadWindow = new LoadWindow();
        loadWindow.setVisible(true);

        loadWindow.addMessage("Reading settings..");

        /*
         * Read properties from file
         */
        final Properties props = new Properties();
        try {
            Properties defaultProps = PropertiesLoaderUtils
                    .loadProperties(new ClassPathResource("eventmanager.properties"));
            props.putAll(defaultProps);
        } catch (IOException ex) {
            log.error(ex);
        }

        props.putAll(System.getProperties());

        File databaseStore = new File(workingDir, "comps");
        int rmiPort = Integer.parseInt(props.getProperty("eventmanager.rmi.port"));

        loadWindow.addMessage("Loading Peer Manager..");
        log.info("Loading Peer Manager");

        ManualDiscoveryService manualDiscoveryService = new ManualDiscoveryService();
        JmDNSRMIPeerManager peerManager = new JmDNSRMIPeerManager(rmiPort, new File(workingDir, "peerid.dat"));
        peerManager.addDiscoveryService(manualDiscoveryService);

        monitorNetworkInterfaceChanges(peerManager);

        loadWindow.addMessage("Loading Database Manager..");
        log.info("Loading Database Manager");

        DatabaseManager databaseManager = new SQLiteDatabaseManager(databaseStore, peerManager);
        LicenseManager licenseManager = new LicenseManager(workingDir);

        loadWindow.addMessage("Loading Load Competition Dialog..");
        log.info("Loading Load Competition Dialog");

        LoadCompetitionWindow loadCompetitionWindow = new LoadCompetitionWindow(databaseManager, licenseManager,
                peerManager);
        loadCompetitionWindow.setTitle(WINDOW_TITLE);

        loadWindow.dispose();
        log.info("Starting Load Competition Dialog");

        while (true) {
            // reset permission checker to use our license
            licenseManager.updatePermissionChecker();

            GUIUtils.runModalJFrame(loadCompetitionWindow);

            if (loadCompetitionWindow.getSuccess()) {
                DatabaseInfo info = loadCompetitionWindow.getSelectedDatabaseInfo();

                if (!databaseManager.checkLock(info.id)) {
                    String message = "EventManager did not shut down correctly the last time this competition was open. To avoid potential data corruption, you are advised to take the following steps:\n"
                            + "1) Do NOT open this competition\n" + "2) Create a backup of this competition\n"
                            + "3) Delete the competition from this computer\n"
                            + "4) If possible, reload this competition from another computer on the network\n"
                            + "5) Alternatively, you may manually load the backup onto all computers on the network, ensuring the 'Preserve competition ID' option is checked.";
                    String title = "WARNING: Potential Data Corruption Detected";

                    int status = JOptionPane.showOptionDialog(null, message, title, JOptionPane.YES_NO_OPTION,
                            JOptionPane.ERROR_MESSAGE, null,
                            new Object[] { "Cancel (recommended)", "Open anyway" }, "Cancel (recommended)");

                    if (status == 0)
                        continue; // return to load competition window
                }

                SynchronizingWindow syncWindow = new SynchronizingWindow();
                syncWindow.setVisible(true);
                long t = System.nanoTime();
                DistributedDatabase database = databaseManager.activateDatabase(info.id, info.passwordHash);
                long dt = System.nanoTime() - t;
                log.debug(String.format("Initial sync in %dms",
                        TimeUnit.MILLISECONDS.convert(dt, TimeUnit.NANOSECONDS)));
                syncWindow.dispose();

                if (loadCompetitionWindow.isNewDatabase()) {
                    GregorianCalendar calendar = new GregorianCalendar();
                    Date today = calendar.getTime();
                    calendar.set(Calendar.MONTH, Calendar.DECEMBER);
                    calendar.set(Calendar.DAY_OF_MONTH, 31);
                    Date endOfYear = new java.sql.Date(calendar.getTimeInMillis());

                    CompetitionInfo ci = new CompetitionInfo();
                    ci.setName(info.name);
                    ci.setStartDate(today);
                    ci.setEndDate(today);
                    ci.setAgeThresholdDate(endOfYear);
                    //ci.setPasswordHash(info.passwordHash);
                    License license = licenseManager.getLicense();
                    if (license != null) {
                        ci.setLicenseName(license.getName());
                        ci.setLicenseType(license.getType().toString());
                        ci.setLicenseContact(license.getContactPhoneNumber());
                    }
                    database.add(ci);
                }

                // Set PermissionChecker to use database's license type
                String competitionLicenseType = database.get(CompetitionInfo.class, null).getLicenseType();
                PermissionChecker.setLicenseType(LicenseType.valueOf(competitionLicenseType));

                TransactionNotifier notifier = new TransactionNotifier();
                database.setListener(notifier);

                MainWindow mainWindow = new MainWindow();
                mainWindow.setDatabase(database);
                mainWindow.setNotifier(notifier);
                mainWindow.setPeerManager(peerManager);
                mainWindow.setLicenseManager(licenseManager);
                mainWindow.setManualDiscoveryService(manualDiscoveryService);
                mainWindow.setTitle(WINDOW_TITLE);
                mainWindow.afterPropertiesSet();

                TestUtil.setActivatedDatabase(database);

                // show main window (modally)
                GUIUtils.runModalJFrame(mainWindow);

                // shutdown procedures

                // System.exit();

                database.shutdown();
                databaseManager.deactivateDatabase(1500);

                if (mainWindow.getDeleteOnExit()) {
                    for (File file : info.localDirectory.listFiles())
                        if (!file.isDirectory())
                            file.delete();
                    info.localDirectory.deleteOnExit();
                }
            } else {
                // This can cause an RuntimeException - Peer is disconnected
                peerManager.stop();
                System.exit(0);
            }
        }
    } catch (Throwable e) {
        log.error("Error in main function", e);
        String message = e.getMessage();
        if (message == null)
            message = "";
        if (message.length() > 100)
            message = message.substring(0, 97) + "...";
        GUIUtils.displayError(null,
                "An unexpected error has occured.\n\n" + e.getClass().getSimpleName() + "\n" + message);
        System.exit(0);
    }
}

From source file:com.github.parisoft.resty.utils.CookieUtils.java

public static String toString(org.apache.http.cookie.Cookie... cookies) {
    if (isEmpty(cookies)) {
        return null;
    }//from w  ww .j  a v  a  2s . com

    final HttpCookie[] httpCookies = new HttpCookie[cookies.length];

    for (int i = 0; i < cookies.length; i++) {
        final org.apache.http.cookie.Cookie srcCookie = cookies[i];
        final HttpCookie httpCookie = new HttpCookie(srcCookie.getName(), srcCookie.getValue());
        httpCookie.setComment(srcCookie.getComment());
        httpCookie.setDomain(srcCookie.getDomain());
        httpCookie.setPath(srcCookie.getPath());
        httpCookie.setSecure(srcCookie.isSecure());
        httpCookie.setVersion(srcCookie.getVersion());

        final Date now = new Date();

        if (srcCookie.isExpired(now)) {
            httpCookie.setMaxAge(0);
        } else {
            httpCookie.setMaxAge(
                    TimeUnit.MILLISECONDS.toSeconds(srcCookie.getExpiryDate().getTime() - now.getTime()));
        }

        httpCookies[i] = httpCookie;
    }

    return toString(httpCookies);
}

From source file:hello.Runner.java

@Override
public void run(String... args) throws Exception {
    System.out.println("Sending message...");
    rabbitTemplate.convertAndSend(Application.queueName, "Hello from RabbitMQ!");
    receiver.getLatch().await(10000, TimeUnit.MILLISECONDS);
    context.close();/*ww w . jav a 2  s  .co m*/
}

From source file:com.yufei.dataget.dataretriver.HttpDataRetriverUsingFirefoxDriverWithTimeOut.java

@Override
public String getHtmlContent() {
    final HttpDataRetriverUsingFirefoxDriver hdrufd = new HttpDataRetriverUsingFirefoxDriver(
            this.dataRetrieverFeatures);

    String htmlContent = null;//w w w. ja  va2s  .c o  m
    try {
        htmlContent = TimeOutUtils.runWithTimeout(new Callable<String>() {

            @Override
            public String call() throws Exception {
                hdrufd.setUrl(url);
                hdrufd.connect();

                return hdrufd.getHtmlContent();
            }
        }, this.dataRetrieverFeatures.getRequestTimeout(), TimeUnit.MILLISECONDS);
    } catch (TimeoutException e) {
        mLog.info("got timeout!");
    } catch (Exception ex) {
        Logger.getLogger(HttpDataRetriverUsingFirefoxDriverWithTimeOut.class.getName()).log(Level.SEVERE, null,
                ex);
    } finally {
        hdrufd.disconnect();

    }
    return htmlContent;
}

From source file:io.gravitee.gateway.service.ratelimit.RateLimitUpdater.java

@Override
public void run() {
    while (!Thread.interrupted()) {
        try {//from ww w .  j a  v a  2  s  .c om
            RateLimit rateLimit = queue.poll(getPollingTimeout(), TimeUnit.MILLISECONDS);
            if (rateLimit != null) {
                queue.offer(rateLimit);
            }

            while (!queue.isEmpty()) {
                rateLimit = queue.poll(getPollingTimeout(), TimeUnit.MILLISECONDS);
                if (rateLimit != null) {
                    delegateRateLimitRepository.save(rateLimit);
                }
            }
        } catch (InterruptedException ie) {

        } catch (Exception ex) {
            // Do nothing here
        }
    }
}

From source file:com.ok2c.lightmtp.impl.pool.LeasedSession.java

LeasedSession(final String id, final SessionEndpoint endpoint, final IOSession iosession) {
    super(id, endpoint, iosession, -1, TimeUnit.MILLISECONDS);
}

From source file:com.watchrabbit.scanner.attacker.verify.BasicXSSVerificationStrategyIT.java

@Test
public void shouldFindXss() {
    RemoteWebDriver driver = firefoxFactory.produceDriver();
    try {//from   w  w w .j a  va2s  .  com
        Stopwatch watch = Stopwatch.createStarted(() -> driver.get("http://localhost:8080"));
        Vulnerability vulnerability = new BasicXSSVerificationStrategy().verify(driver,
                watch.getExecutionTime(TimeUnit.MILLISECONDS));

        assertThat(vulnerability).isEqualTo(Vulnerability.EXISTS);
    } finally {
        firefoxFactory.returnWebDriver(driver);
    }
}