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:com.cse3310.phms.ui.activities.AddAppointmentActivity.java

@AfterViews
void onSetupViews() {
    if (mSelectedDate != null) {
        appointmentTime = mSelectedDate.getTime();
    }// w  w  w  .  j av  a2  s.  c  o m

    // 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.omertron.themoviedbapi.AbstractTests.java

/**
 * Read the object back from a file//from   w ww .  j a  v a 2s  . com
 *
 * @param <T>
 * @param filename
 * @return
 */
private static <T> T readObject(final String baseFilename) {
    String filename = baseFilename + FILENAME_EXT;
    File serFile = new File(filename);

    if (serFile.exists()) {
        long diff = System.currentTimeMillis() - serFile.lastModified();
        if (diff < TimeUnit.HOURS.toMillis(1)) {
            LOG.info("File '{}' is current, no need to reacquire", filename);
        } else {
            LOG.info("File '{}' is too old, re-acquiring", filename);
            return null;
        }
    } else {
        LOG.info("File '{}' doesn't exist", filename);
        return null;
    }

    LOG.info("Reading object from '{}'", filename);
    try {
        byte[] serObject = FileUtils.readFileToByteArray(serFile);
        return (T) SerializationUtils.deserialize(serObject);
    } catch (IOException ex) {
        LOG.info("Failed to read {}: {}", filename, ex.getMessage(), ex);
        return null;
    }
}

From source file:org.apache.nutch.api.NutchServer.java

/**
 * Public constructor which accepts the port we wish to run the server on as
 * well as the logging granularity. If the latter option is not provided via
 * {@link org.apache.nutch.api.NutchServer#main(String[])} then it defaults to
 * 'INFO' however best attempts should always be made to specify a logging
 * level./*from   w  w w .  ja  v  a  2  s.c om*/
 */
public NutchServer() {
    configManager = new RAMConfManager();
    BlockingQueue<Runnable> runnables = Queues.newArrayBlockingQueue(JOB_CAPACITY);
    NutchServerPoolExecutor executor = new NutchServerPoolExecutor(10, JOB_CAPACITY, 1, TimeUnit.HOURS,
            runnables);
    jobMgr = new RAMJobManager(new JobFactory(), executor, configManager);

    // Create a new Component.
    component = new Component();
    component.getLogger().setLevel(Level.parse(logLevel));

    // Add a new HTTP server listening on defined port.
    component.getServers().add(Protocol.HTTP, port);

    Context childContext = component.getContext().createChildContext();
    JaxRsApplication application = new JaxRsApplication(childContext);
    application.add(this);
    application.setStatusService(new ErrorStatusService());
    childContext.getAttributes().put(NUTCH_SERVER, this);

    // Attach the application.
    component.getDefaultHost().attach(application);
}

From source file:org.apache.lens.server.user.LDAPBackedDatabaseUserConfigLoader.java

/**
 * Instantiates a new LDAP backed database user config loader.
 *
 * @param conf the conf/*from w w w .  j av  a2  s.c  o  m*/
 * @throws UserConfigLoaderException the user config loader exception
 */
public LDAPBackedDatabaseUserConfigLoader(final HiveConf conf) throws UserConfigLoaderException {
    super(conf);
    expiryHours = conf.getInt(LensConfConstants.USER_RESOLVER_CACHE_EXPIRY, 2);
    intermediateQuerySql = conf.get(LensConfConstants.USER_RESOLVER_LDAP_INTERMEDIATE_DB_QUERY);
    intermediateDeleteSql = conf.get(LensConfConstants.USER_RESOLVER_LDAP_INTERMEDIATE_DB_DELETE_SQL);
    intermediateInsertSql = conf.get(LensConfConstants.USER_RESOLVER_LDAP_INTERMEDIATE_DB_INSERT_SQL);
    ldapFields = conf.get(LensConfConstants.USER_RESOLVER_LDAP_FIELDS).split("\\s*,\\s*");
    searchBase = conf.get(LensConfConstants.USER_RESOLVER_LDAP_SEARCH_BASE);
    searchFilterPattern = conf.get(LensConfConstants.USER_RESOLVER_LDAP_SEARCH_FILTER);
    intermediateCache = CacheBuilder.newBuilder().expireAfterWrite(expiryHours, TimeUnit.HOURS)
            .maximumSize(conf.getInt(LensConfConstants.USER_RESOLVER_CACHE_MAX_SIZE, 100)).build();
    cache = CacheBuilder.newBuilder().expireAfterWrite(expiryHours, TimeUnit.HOURS)
            .maximumSize(conf.getInt(LensConfConstants.USER_RESOLVER_CACHE_MAX_SIZE, 100)).build();

    env = new Hashtable<String, Object>() {
        {
            put(Context.SECURITY_AUTHENTICATION, "simple");
            put(Context.SECURITY_PRINCIPAL, conf.get(LensConfConstants.USER_RESOLVER_LDAP_BIND_DN));
            put(Context.SECURITY_CREDENTIALS, conf.get(LensConfConstants.USER_RESOLVER_LDAP_BIND_PASSWORD));
            put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
            put(Context.PROVIDER_URL, conf.get(LensConfConstants.USER_RESOLVER_LDAP_URL));
            put("java.naming.ldap.attributes.binary", "objectSID");
        }
    };
}

From source file:com.graphaware.importer.data.access.QueueDbDataReader.java

/**
 * {@inheritDoc}//from  w  w w .j a  va  2  s . com
 */
@Override
public final void read(final String query, final String hint) {
    if (records != null) {
        throw new IllegalStateException("Previous reader hasn't been closed");
    }

    LOG.info("Start query: \n" + query);

    if (query.startsWith("alter")) {
        jdbcTemplate.execute(query);
        noMoreRecords = true;
        return;
    }

    records = new ArrayBlockingQueue<>(queueCapacity());

    new Thread(new Runnable() {
        @Override
        public void run() {
            Date d1 = Calendar.getInstance().getTime();

            try {
                jdbcTemplate.query(query, new ResultSetExtractor<Void>() {
                    @Override
                    public Void extractData(ResultSet rs) throws SQLException, DataAccessException {
                        ResultSetMetaData metaData = rs.getMetaData();
                        int colCount = metaData.getColumnCount();

                        while (rs.next()) {
                            Map<String, String> columns = new HashMap<>();
                            for (int i = 1; i <= colCount; i++) {
                                columns.put(metaData.getColumnLabel(i), rs.getString(i));
                            }
                            columns.put(ROW, String.valueOf(rs.getRow()));

                            try {
                                records.offer(columns, 1, TimeUnit.HOURS);
                            } catch (InterruptedException e) {
                                LOG.warn(
                                        "Was waiting for more than 1 hour to insert a record for processing, had to drop it");
                            }
                        }

                        return null;
                    }
                });
            } finally {
                noMoreRecords = true;
            }

            long diffInSeconds = TimeUnit.MILLISECONDS
                    .toSeconds(Calendar.getInstance().getTime().getTime() - d1.getTime());

            LOG.info("Finished querying for " + hint + " in " + diffInSeconds + " seconds");
        }
    }, "DB READER - " + hint).start();
}

From source file:org.chaos.fx.cnbeta.theme.ThemePreferencesFragment.java

@Override
public boolean onPreferenceClick(Preference preference) {
    if (PreferenceKeys.NIGHT_MODE_START_TIME.equals(preference.getKey())) {
        showTimePicker(PreferenceHelper.getInstance().getNightModeStartTime(),
                new TimePickerDialog.OnTimeSetListener() {
                    @Override// w  w  w .j a  v a2  s . c  om
                    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                        long timeInMillis = TimeUnit.HOURS.toMillis(hourOfDay)
                                + TimeUnit.MINUTES.toMillis(minute);
                        PreferenceHelper.getInstance().setNightModeStartTime(timeInMillis);
                    }
                });
        return true;
    } else if (PreferenceKeys.NIGHT_MODE_END_TIME.equals(preference.getKey())) {
        showTimePicker(PreferenceHelper.getInstance().getNightModeEndTime(),
                new TimePickerDialog.OnTimeSetListener() {
                    @Override
                    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                        long timeInMillis = TimeUnit.HOURS.toMillis(hourOfDay)
                                + TimeUnit.MINUTES.toMillis(minute);
                        PreferenceHelper.getInstance().setNightModeEndTime(timeInMillis);
                    }
                });
        return true;
    }
    return false;
}

From source file:org.xdi.oxd.server.license.LicenseService.java

private void schedulePeriodicValidation() {
    final ScheduledExecutorService executorService = Executors
            .newSingleThreadScheduledExecutor(CoreUtils.daemonThreadFactory());
    executorService.scheduleAtFixedRate(new Runnable() {
        @Override/*from ww w. j av a  2 s . c  o  m*/
        public void run() {
            licenseValid = validate();
        }
    }, 1, 24, TimeUnit.HOURS);
}

From source file:com.zb.app.biz.service.impl.TravelCompanyServiceImpl.java

@PostConstruct
public void cronCache() {
    Result companyRegist = notifyService.regist(new NotifyListener() {

        @EventConfig(events = { EventType.companyAdd, EventType.companyDelete, EventType.companyUpdate })
        public void companyEvent(CompanyEvent event) {
            handle(event);/*from  w w w.jav  a  2s  . c  o  m*/
        }
    });
    if (companyRegist.isFailed()) {
        logger.error("TravelCompanyServiceImpl init companyRegist ?failed!");
    } else {
        logger.error("TravelCompanyServiceImpl init companyRegist ?success!");
    }

    ScheduledExecutorService newScheduledThreadPool = Executors.newScheduledThreadPool(1);
    newScheduledThreadPool.scheduleAtFixedRate(new Runnable() {

        @Override
        public void run() {
            try {
                init();
            } catch (Throwable e) {
                logger.error("init travelCompanyCacheMap error", e);
            }
        }

    }, 0, 12, TimeUnit.HOURS);
}

From source file:org.apache.metron.profiler.client.window.WindowProcessorTest.java

@Test
public void testSparse() {
    for (String text : new String[] { "30 minute window every 1 hour from 2 hours ago to 30 minutes ago",
            "30 minute window every 1 hour starting from 2 hours ago to 30 minutes ago",
            "30 minute window every 1 hour starting from 2 hours ago until 30 minutes ago",
            "30 minute window for every 1 hour starting from 2 hours ago until 30 minutes ago", }) {
        Window w = WindowProcessor.process(text);
        /*// ww w  .j a v a  2 s.co  m
        A window size of 30 minutes
        Starting 2 hour ago and continuing until 30 minutes ago
        window 1: ( now - 2 hour, now - 2 hour + 30 minutes)
        window 2: (now - 1 hour, now - 1 hour + 30 minutes)
         */
        Date now = new Date();
        List<Range<Long>> intervals = w.toIntervals(now.getTime());
        Assert.assertEquals(2, intervals.size());
        assertEquals(now.getTime() - TimeUnit.HOURS.toMillis(2), intervals.get(0).getMinimum());
        assertEquals(now.getTime() - TimeUnit.HOURS.toMillis(2) + TimeUnit.MINUTES.toMillis(30),
                intervals.get(0).getMaximum());
        assertEquals(now.getTime() - TimeUnit.HOURS.toMillis(1), intervals.get(1).getMinimum());
        assertEquals(now.getTime() - TimeUnit.HOURS.toMillis(1) + TimeUnit.MINUTES.toMillis(30),
                intervals.get(1).getMaximum());
    }
}

From source file:com.intelligentsia.dowsers.entity.store.fs.FileEntityStore.java

/**
 * Build a new instance of FileEntityStore with default cache:
 * <ul>//from   w ww. ja va2s .  c o  m
 * <li>Maximum size : 1000 elements</li>
 * <li>expire after access : 1 hour</li>
 * </ul>
 * 
 * @param root
 *            root directory of this {@link EntityStore}.
 * @param entityMapper
 *            {@link EntityMapper} to use
 * @throws NullPointerException
 *             if one of parameters is null
 * @throws IllegalStateException
 *             if root is not a directory of if it cannot be created
 */
public FileEntityStore(final File root, final EntityMapper entityMapper) {
    this(root, entityMapper, CacheBuilder.newBuilder().maximumSize(1000).expireAfterAccess(1, TimeUnit.HOURS));
}