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.mitre.openid.connect.client.UserInfoFetcher.java

public UserInfoFetcher(HttpClient httpClient) {
    cache = CacheBuilder.newBuilder().expireAfterWrite(1, TimeUnit.HOURS) // expires 1 hour after fetch
            .maximumSize(100).build(new UserInfoLoader(httpClient));
}

From source file:com.google.cloud.bigtable.hbase.ManyThreadDriver.java

private static void runTest(String projectId, String instanceId, final String tableName) throws Exception {
    Configuration configuration = new Configuration();
    configuration.set("hbase.client.connection.impl", "com.google.cloud.bigtable.hbase1_0.BigtableConnection");
    configuration.set("google.bigtable.project.id", projectId);
    configuration.set("google.bigtable.instance.id", instanceId);
    try (Connection connection = ConnectionFactory.createConnection(configuration)) {
        Admin admin = connection.getAdmin();

        HTableDescriptor descriptor = new HTableDescriptor(TableName.valueOf(tableName));
        descriptor.addFamily(new HColumnDescriptor("cf"));
        try {/*from   w  w  w . jav a 2  s .  c o  m*/
            admin.createTable(descriptor);
        } catch (IOException ignore) {
            // Soldier on, maybe the table already exists.
        }

        final byte[] value = Bytes.toBytes(RandomStringUtils
                .randomAlphanumeric(Integer.parseInt(System.getProperty("valueSize", "1024"))));

        int numThreads = Integer.parseInt(System.getProperty("numThreads", "1000"));
        ExecutorService executor = Executors.newFixedThreadPool(numThreads);
        for (int i = 0; i < numThreads; i++) {
            Runnable r = new Runnable() {
                @Override
                public void run() {
                    try {
                        final Table table = connection.getTable(TableName.valueOf(tableName));

                        while (true) {
                            // Workload: two reads and a write.
                            table.get(new Get(Bytes.toBytes(key())));
                            table.get(new Get(Bytes.toBytes(key())));
                            Put p = new Put(Bytes.toBytes(key()));
                            p.addColumn(Bytes.toBytes("cf"), Bytes.toBytes("col"), value);
                            table.put(p);
                        }
                    } catch (Exception e) {
                        System.out.println(e.getMessage());
                    }
                }
            };
            executor.execute(r);
        }

        // TODO Make a parameter
        executor.awaitTermination(48, TimeUnit.HOURS);
    }
}

From source file:com.softminds.matrixcalculator.base_activities.SplashScreen.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    int SPLASH_TIME_OUT = 2000;

    ((GlobalValues) getApplication()).SetDonationKeyStatus();

    if (!((GlobalValues) getApplication()).DonationKeyFound()) { //if user is non pro then only check for offer key
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("promotion_offer", false);

        remoteConfig.setDefaults(hashMap);

        remoteConfig.setConfigSettings(//from  w  w  w .  j a  va 2  s . c  om
                new FirebaseRemoteConfigSettings.Builder().setDeveloperModeEnabled(BuildConfig.DEBUG).build());

        final Task<Void> fetch = remoteConfig.fetch(TimeUnit.HOURS.toSeconds(6));
        //if offer exist then activate pro features
        fetch.addOnSuccessListener(new OnSuccessListener<Void>() {
            @Override
            public void onSuccess(Void aVoid) {
                remoteConfig.activateFetched();
                UpdateKey();
            }
        });
    }

    //init the key status here
    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
    boolean isDark = preferences.getBoolean("DARK_THEME_KEY", false);
    if (isDark)
        setTheme(R.style.AppThemeDark);
    else
        setTheme(R.style.AppTheme);
    super.onCreate(savedInstanceState);
    setContentView(R.layout.splash_screen);
    TextView textView = findViewById(R.id.textView9);
    String s = "Version " + BuildConfig.VERSION_NAME;
    textView.setText(s);
    RelativeLayout Root = findViewById(R.id.splash_screen);
    try {
        if (isDark) {
            Root.setBackgroundColor(ContextCompat.getColor(this, R.color.DarkcolorPrimaryDark));
        } else
            Root.setBackgroundColor(ContextCompat.getColor(getApplicationContext(), R.color.colorPrimaryDark));
    } catch (NullPointerException e) {
        Toast.makeText(getApplicationContext(), R.string.FatalError, Toast.LENGTH_SHORT).show();
        e.printStackTrace();
        finish();
    }
    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            Intent intent = new Intent(getApplicationContext(), MainActivity.class);
            startActivity(intent);
            finish();

        }
    }, SPLASH_TIME_OUT);

    if (PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).getBoolean("PERSIST_ENABLER",
            false)) {
        try {
            FileInputStream fis = getApplicationContext().openFileInput("persist_data.mat");
            ObjectInputStream os = new ObjectInputStream(fis);
            ArrayList<MatrixV2> vars = (ArrayList<MatrixV2>) os.readObject();
            Log.d("TTT", "ABOUT TO RESTORE " + String.valueOf(vars.size()));
            os.close();
            fis.close();
            Log.d("TTT", "Previously on MainList "
                    + String.valueOf(((GlobalValues) getApplication()).GetCompleteList().size()));
            ((GlobalValues) getApplication()).GetCompleteList().clear();
            ((GlobalValues) getApplication()).GetCompleteList().addAll(vars);
            Log.d("TTT", "Total Value "
                    + String.valueOf(((GlobalValues) getApplication()).GetCompleteList().size()));
            Toast.makeText(getApplicationContext(), "Restored all Variables", Toast.LENGTH_SHORT).show();
        } catch (FileNotFoundException | ClassNotFoundException e) {
            // Nothing to restore simply skip
            e.printStackTrace();
        } catch (IOException e) {
            Toast.makeText(getApplicationContext(), "Cannot Load Persisted Variable. I/O Error",
                    Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        }
    }
}

From source file:org.bimserver.tools.ifcloader.BulkLoader.java

private void start() {
    Path basePath = Paths.get("C:\\Bulk");
    Path bulkPath = basePath.resolve("bulk");
    Path regularPath = basePath.resolve("single");
    try (JsonBimServerClientFactory factory = new JsonBimServerClientFactory("http://localhost:8080")) {
        ExecutorService executorService = new ThreadPoolExecutor(16, 16, 1, TimeUnit.HOURS,
                new ArrayBlockingQueue<>(10000));
        try (BimServerClient client = factory
                .create(new UsernamePasswordAuthenticationInfo("admin@bimserver.org", "admin"))) {
            if (Files.exists(bulkPath)) {
                DirectoryStream<Path> stream = Files.newDirectoryStream(bulkPath);
                for (Path path : stream) {
                    executorService.submit(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                SProject project = client.getServiceInterface()
                                        .addProject(path.getFileName().toString(), "ifc2x3tc1");
                                client.bulkCheckin(project.getOid(), path, "Automatic bulk checkin");
                            } catch (ServerException e) {
                                e.printStackTrace();
                            } catch (UserException e) {
                                e.printStackTrace();
                            } catch (PublicInterfaceNotFoundException e) {
                                e.printStackTrace();
                            }/*from  w w w .ja  v a2  s . c  o  m*/
                        }
                    });
                }
            }
            if (Files.exists(regularPath)) {
                DirectoryStream<Path> regularStream = Files.newDirectoryStream(regularPath);
                for (Path regularFile : regularStream) {
                    executorService.submit(new Runnable() {
                        @Override
                        public void run() {
                            String filename = regularFile.getFileName().toString().toLowerCase();
                            try {
                                if (filename.endsWith(".ifc") || filename.endsWith(".ifczip")) {
                                    String schema = client.getServiceInterface().determineIfcVersion(
                                            extractHead(regularFile),
                                            filename.toLowerCase().endsWith(".ifczip"));
                                    SProject project = client.getServiceInterface().addProject(filename,
                                            schema);
                                    SDeserializerPluginConfiguration deserializer = client.getServiceInterface()
                                            .getSuggestedDeserializerForExtension("ifc", project.getOid());
                                    client.checkinSync(project.getOid(), "Automatic checkin",
                                            deserializer.getOid(), false, regularFile);
                                } else {
                                    LOGGER.info("Skipping " + filename);
                                }
                            } catch (Exception e) {
                                LOGGER.error(filename, e);
                            }
                        }
                    });
                }
            }
            executorService.shutdown();
            executorService.awaitTermination(24, TimeUnit.HOURS);
        }
    } catch (BimServerClientException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.fastbootmobile.encore.utils.Utils.java

/**
 * Format milliseconds into an human-readable track length.
 * Examples:/* w w  w . j a  v a2s  .co m*/
 * - 01:48:24 for 1 hour, 48 minutes, 24 seconds
 * - 24:02 for 24 minutes, 2 seconds
 * - 52s for 52 seconds
 *
 * @param timeMs The time to format, in milliseconds
 * @return A formatted string
 */
public static String formatTrackLength(long timeMs) {
    long hours = TimeUnit.MILLISECONDS.toHours(timeMs);
    long minutes = TimeUnit.MILLISECONDS.toMinutes(timeMs) - TimeUnit.HOURS.toMinutes(hours);
    long seconds = TimeUnit.MILLISECONDS.toSeconds(timeMs) - TimeUnit.HOURS.toSeconds(hours)
            - TimeUnit.MINUTES.toSeconds(minutes);

    if (hours > 0) {
        return String.format("%02d:%02d:%02d", hours, minutes, seconds);
    } else if (minutes > 0) {
        return String.format("%02d:%02d", minutes, seconds);
    } else if (seconds > 0) {
        return String.format("%02ds", seconds);
    } else if (seconds == 0) {
        return "-:--";
    } else {
        return "N/A";
    }
}

From source file:com.autodomum.provider.telldus.TelldusComponent.java

@Override
public void run() {
    LOG.info("Started!");
    try {/* w  w  w .  j a va2 s. c  om*/
        while (true) {
            final Lamp lamp = lampStates.poll(1, TimeUnit.HOURS);

            if (lamp != null && lamp.getCallIds() != null) {
                for (String callId : lamp.getCallIds()) {
                    try {
                        for (int i = 0; i < 3; i++) {
                            if (lamp.getOn()) {
                                Runtime.getRuntime().exec("tdtool --on " + callId);
                                LOG.debug("Call: tdtool --on {}", callId);
                            } else {
                                Runtime.getRuntime().exec("tdtool --off " + callId);
                                LOG.debug("Call: tdtool --off {}", callId);
                            }
                        }
                    } catch (IOException e) {
                        LOG.warn("Failed to call tdtool for {}", lamp, e);
                    }
                    Thread.sleep(1500);
                }
            }
        }
    } catch (InterruptedException e) {
    }
    LOG.info("Exit!");
}

From source file:com.linkedin.pinot.core.segment.index.ColumnMetadataTest.java

public SegmentGeneratorConfig CreateSegmentConfigWithoutCreator() throws Exception {
    final String filePath = TestUtils
            .getFileFromResourceUrl(ColumnMetadataTest.class.getClassLoader().getResource(AVRO_DATA));
    // Intentionally changed this to TimeUnit.Hours to make it non-default for testing.
    SegmentGeneratorConfig config = SegmentTestUtils.getSegmentGenSpecWithSchemAndProjectedColumns(
            new File(filePath), INDEX_DIR, "daysSinceEpoch", TimeUnit.HOURS, "testTable");
    config.setSegmentNamePostfix("1");
    config.setTimeColumnName("daysSinceEpoch");
    return config;
}

From source file:com.janrain.backplane2.server.V2MessageProcessor.java

@Override
public void takeLeadership(CuratorFramework curatorFramework) throws Exception {
    setLeader(true);/*w  w w  .j  a v  a 2  s  .  co  m*/
    logger.info("[" + BackplaneSystemProps.getMachineName() + "] v2 leader elected for message processing");

    ScheduledFuture<?> cleanupTask = scheduledExecutor.scheduleAtFixedRate(cleanupRunnable, 1, 2,
            TimeUnit.HOURS);
    insertMessages();
    cleanupTask.cancel(false);

    logger.info("[" + BackplaneSystemProps.getMachineName() + "] v2 leader ended message processing");
}

From source file:com.hpcloud.util.Duration.java

public static Duration hours(long count) {
    return new Duration(count, TimeUnit.HOURS);
}