use of java.util.concurrent.TimeUnit in project legacy-jclouds-examples by jclouds.
the class WindowsInstanceStarter method run.
public void run() {
final String region = arguments.getRegion();
// Build a template
Template template = computeService.templateBuilder().locationId(region).imageNameMatches(arguments.getImageNamePattern()).hardwareId(arguments.getInstanceType()).build();
logger.info("Selected AMI is: %s", template.getImage().toString());
template.getOptions().inboundPorts(3389);
// Create the node
logger.info("Creating node and waiting for it to become available");
Set<? extends NodeMetadata> nodes = null;
try {
nodes = computeService.createNodesInGroup("basic-ami", 1, template);
} catch (RunNodesException e) {
logger.error(e, "Unable to start nodes; aborting");
return;
}
NodeMetadata node = Iterables.getOnlyElement(nodes);
// Wait for the administrator password
logger.info("Waiting for administrator password to become available");
// This predicate will call EC2's API to get the Windows Administrator
// password, and returns true if there is password data available.
Predicate<String> passwordReady = new Predicate<String>() {
@Override
public boolean apply(@Nullable String s) {
if (Strings.isNullOrEmpty(s))
return false;
PasswordData data = ec2Client.getWindowsServices().getPasswordDataInRegion(region, s);
if (data == null)
return false;
return !Strings.isNullOrEmpty(data.getPasswordData());
}
};
// Now wait, using RetryablePredicate
final int maxWait = 600;
final int period = 10;
final TimeUnit timeUnit = TimeUnit.SECONDS;
RetryablePredicate<String> passwordReadyRetryable = new RetryablePredicate<String>(passwordReady, maxWait, period, timeUnit);
boolean isPasswordReady = passwordReadyRetryable.apply(node.getProviderId());
if (!isPasswordReady) {
logger.error("Password is not ready after %s %s - aborting and shutting down node", maxWait, timeUnit.toString());
computeService.destroyNode(node.getId());
return;
}
// Now we can get the password data, decrypt it, and get a LoginCredentials instance
PasswordDataAndPrivateKey dataAndKey = new PasswordDataAndPrivateKey(ec2Client.getWindowsServices().getPasswordDataInRegion(region, node.getProviderId()), node.getCredentials().getPrivateKey());
WindowsLoginCredentialsFromEncryptedData f = context.getUtils().getInjector().getInstance(WindowsLoginCredentialsFromEncryptedData.class);
LoginCredentials credentials = f.apply(dataAndKey);
// Send to the log the details you need to log in to the instance with RDP
String publicIp = Iterables.getFirst(node.getPublicAddresses(), null);
logger.info("IP address: %s", publicIp);
logger.info("Login name: %s", credentials.getUser());
logger.info("Password: %s", credentials.getPassword());
// Wait for Enter on the console
logger.info("Hit Enter to shut down the node.");
InputStreamReader converter = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(converter);
try {
in.readLine();
} catch (IOException e) {
logger.error(e, "IOException while reading console input");
}
// Tidy up
logger.info("Shutting down");
computeService.destroyNode(node.getId());
}
use of java.util.concurrent.TimeUnit in project hibernate-orm by hibernate.
the class PutFromLoadStressTestCase method doTest.
private void doTest(boolean warmup) throws Exception {
ExecutorService executor = Executors.newFixedThreadPool(NUM_THREADS);
try {
CyclicBarrier barrier = new CyclicBarrier(NUM_THREADS + 1);
List<Future<String>> futures = new ArrayList<Future<String>>(NUM_THREADS);
for (int i = 0; i < NUM_THREADS; i++) {
Future<String> future = executor.submit(new SelectQueryRunner(barrier, warmup, i + 1));
futures.add(future);
Thread.sleep(LAUNCH_INTERVAL_MILLIS);
}
// wait for all threads to be ready
barrier.await();
long timeout = warmup ? WARMUP_TIME_SECS : RUNNING_TIME_SECS;
TimeUnit unit = TimeUnit.SECONDS;
// Wait for the duration of the test
Thread.sleep(unit.toMillis(timeout));
// Instruct tests to stop doing work
run.set(false);
// wait for all threads to finish
barrier.await(2, TimeUnit.MINUTES);
log.infof("[%s] All threads finished, check for exceptions", title(warmup));
for (Future<String> future : futures) {
String opsPerMS = future.get();
if (!warmup)
log.infof("[%s] Operations/ms: %s", title(warmup), opsPerMS);
}
log.infof("[%s] All future gets checked", title(warmup));
} catch (Exception e) {
log.errorf(e, "Error in one of the execution threads during %s", title(warmup));
throw e;
} finally {
executor.shutdownNow();
}
}
use of java.util.concurrent.TimeUnit in project hudson-2.x by hudson.
the class Request method callAsync.
/**
* Makes an invocation but immediately returns without waiting for the completion
* (AKA asynchronous invocation.)
*
* @param channel
* The channel from which the request will be sent.
* @return
* The {@link Future} object that can be used to wait for the completion.
* @throws IOException
* If there's an error during the communication.
*/
public final hudson.remoting.Future<RSP> callAsync(final Channel channel) throws IOException {
response = null;
channel.pendingCalls.put(id, this);
channel.send(this);
return new hudson.remoting.Future<RSP>() {
private volatile boolean cancelled;
public boolean cancel(boolean mayInterruptIfRunning) {
if (cancelled || isDone()) {
return false;
}
cancelled = true;
if (mayInterruptIfRunning) {
try {
channel.send(new Cancel(id));
} catch (IOException x) {
return false;
}
}
return true;
}
public boolean isCancelled() {
return cancelled;
}
public boolean isDone() {
return isCancelled() || response != null;
}
public RSP get() throws InterruptedException, ExecutionException {
synchronized (Request.this) {
try {
while (response == null) {
if (isCancelled()) {
throw new CancellationException();
}
// wait until the response arrives
Request.this.wait();
}
} catch (InterruptedException e) {
try {
channel.send(new Cancel(id));
} catch (IOException e1) {
// couldn't cancel. ignore.
}
throw e;
}
if (response.exception != null)
throw new ExecutionException(response.exception);
return response.returnValue;
}
}
public RSP get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
synchronized (Request.this) {
if (response == null) {
if (isCancelled()) {
throw new CancellationException();
}
// wait until the response arrives
Request.this.wait(unit.toMillis(timeout));
}
if (response == null)
throw new TimeoutException();
if (response.exception != null)
throw new ExecutionException(response.exception);
return response.returnValue;
}
}
};
}
use of java.util.concurrent.TimeUnit in project pinot by linkedin.
the class DetectionJobSchedulerUtils method getDateTimeFormatterForDataset.
/**
* Get date time formatter according to granularity of dataset
* This is to store the date in the db, in the correct SDF
* @param timeSpec
* @return
*/
public static DateTimeFormatter getDateTimeFormatterForDataset(DatasetConfigDTO datasetConfig, DateTimeZone dateTimeZone) {
String pattern = null;
TimeSpec timeSpec = ThirdEyeUtils.getTimeSpecFromDatasetConfig(datasetConfig);
TimeUnit unit = timeSpec.getDataGranularity().getUnit();
switch(unit) {
case DAYS:
pattern = DAY_FORMAT;
break;
case MINUTES:
case SECONDS:
case MILLISECONDS:
pattern = MINUTE_FORMAT;
break;
case HOURS:
default:
pattern = HOUR_FORMAT;
break;
}
DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern(pattern).withZone(dateTimeZone);
return dateTimeFormatter;
}
use of java.util.concurrent.TimeUnit in project pinot by linkedin.
the class AnomaliesResource method getTimeseriesOffsetedTimes.
private TimeRange getTimeseriesOffsetedTimes(long anomalyStartTime, long anomalyEndTime, DatasetConfigDTO datasetConfig) {
TimeUnit dataTimeunit = datasetConfig.getTimeUnit();
Period offsetPeriod;
switch(dataTimeunit) {
case // 3 days
DAYS:
offsetPeriod = new Period(0, 0, 0, 3, 0, 0, 0, 0);
break;
case // 10 hours
HOURS:
offsetPeriod = new Period(0, 0, 0, 0, 10, 0, 0, 0);
break;
case // 60 minutes
MINUTES:
offsetPeriod = new Period(0, 0, 0, 0, 0, 60, 0, 0);
break;
default:
offsetPeriod = new Period();
}
DateTimeZone dateTimeZone = DateTimeZone.forID(datasetConfig.getTimezone());
DateTime anomalyStartDateTime = new DateTime(anomalyStartTime, dateTimeZone);
DateTime anomalyEndDateTime = new DateTime(anomalyEndTime, dateTimeZone);
anomalyStartDateTime = anomalyStartDateTime.minus(offsetPeriod);
anomalyEndDateTime = anomalyEndDateTime.plus(offsetPeriod);
anomalyStartTime = anomalyStartDateTime.getMillis();
anomalyEndTime = anomalyEndDateTime.getMillis();
try {
Long maxDataTime = CACHE_REGISTRY.getCollectionMaxDataTimeCache().get(datasetConfig.getDataset());
if (anomalyEndTime > maxDataTime) {
anomalyEndTime = maxDataTime;
}
} catch (ExecutionException e) {
LOG.error("Exception when reading max time for {}", datasetConfig.getDataset(), e);
}
TimeRange range = new TimeRange(anomalyStartTime, anomalyEndTime);
return range;
}
Aggregations