List of usage examples for java.util.concurrent TimeoutException TimeoutException
public TimeoutException(String message)
From source file:org.cloudifysource.esc.driver.provisioning.jclouds.DefaultProvisioningDriver.java
@Override public MachineDetails[] startManagementMachines(final long duration, final TimeUnit unit) throws TimeoutException, CloudProvisioningException { if (duration < 0) { throw new TimeoutException("Starting a new machine timed out"); }//from w w w .j a v a2s . co m final long endTime = System.currentTimeMillis() + unit.toMillis(duration); logger.fine("DefaultCloudProvisioning: startMachine - management == " + management); final String managementMachinePrefix = this.cloud.getProvider().getManagementGroup(); if (StringUtils.isBlank(managementMachinePrefix)) { throw new CloudProvisioningException( "The management group name is missing - can't locate existing servers!"); } // first check if management already exists final MachineDetails[] existingManagementServers = getExistingManagementServers(); if (existingManagementServers.length > 0) { final String serverDescriptions = createExistingServersDescription(managementMachinePrefix, existingManagementServers); throw new CloudProvisioningException( "Found existing servers matching group " + managementMachinePrefix + ": " + serverDescriptions); } // launch the management machines publishEvent(EVENT_ATTEMPT_START_MGMT_VMS); final int numberOfManagementMachines = this.cloud.getProvider().getNumberOfManagementMachines(); final MachineDetails[] createdMachines = doStartManagementMachines(endTime, numberOfManagementMachines); publishEvent(EVENT_MGMT_VMS_STARTED); return createdMachines; }
From source file:org.cloudifysource.esc.driver.provisioning.storage.openstack.OpenstackStorageDriver.java
private void waitForVolumeToReachStatus(final Volume.Status targetStatus, final Optional<? extends VolumeApi> volumeApi, final String volumeId, final long endTime) throws StorageProvisioningException, TimeoutException, InterruptedException { if (!volumeApi.isPresent()) { throw new StorageProvisioningException( "Failed to get volume status, Openstack API is not initialized."); }/* ww w. j a v a 2s.c o m*/ logger.info("waiting for volume to reach status: " + targetStatus.toString()); while (true) { final Volume volume = volumeApi.get().get(volumeId); if (volume != null) { Volume.Status volumeStatus = volume.getStatus(); if (volumeStatus == targetStatus) { //volume is ready break; } else if (volumeStatus == Volume.Status.ERROR) { throw new StorageProvisioningException( "Storage volume management encountered an error. " + "Volume id: " + volumeId); } if (System.currentTimeMillis() > endTime) { throw new TimeoutException("timeout while waiting for volume to reach status \" " + targetStatus + "\". Current status is: " + volume.getStatus()); } } Thread.sleep(VOLUME_POLLING_INTERVAL_MILLIS); } }
From source file:org.openspaces.grid.gsm.machines.plugins.NonBlockingElasticMachineProvisioningAdapter.java
@Override public FutureGridServiceAgents getDiscoveredMachinesAsync(final long duration, final TimeUnit unit) { final AtomicReference<Object> ref = new AtomicReference<Object>(null); final long start = System.currentTimeMillis(); final long end = start + unit.toMillis(duration); submit(new Runnable() { public void run() { try { GridServiceAgent[] agents = machineProvisioning.getDiscoveredMachines(duration, unit); ref.set(agents);//w w w .java2 s .c o m } catch (ElasticMachineProvisioningException e) { ref.set(e); } catch (ElasticGridServiceAgentProvisioningException e) { ref.set(e); } catch (InterruptedException e) { ref.set(e); } catch (TimeoutException e) { ref.set(e); } catch (NoClassDefFoundError e) { ref.set((new NoClassDefFoundElasticMachineProvisioningException(e))); } catch (Throwable e) { logger.error("Unexpected exception", e); ref.set(e); } } }); return new FutureGridServiceAgents() { public boolean isDone() { return System.currentTimeMillis() > end || ref.get() != null; } public ExecutionException getException() { Object result = ref.get(); if (result != null && result instanceof Throwable) { Throwable throwable = (Throwable) result; return new ExecutionException(throwable.getMessage(), throwable); } return null; } public boolean isTimedOut() { Object result = ref.get(); return System.currentTimeMillis() > end || (result != null && result instanceof TimeoutException); } public Date getTimestamp() { return new Date(start); } public GridServiceAgent[] get() throws ExecutionException, IllegalStateException, TimeoutException { Object result = ref.get(); if (result == null) { if (System.currentTimeMillis() > end) { throw new TimeoutException("Starting a new machine took more than " + unit.toSeconds(duration) + " seconds to complete."); } throw new IllegalStateException("Async operation is not done yet."); } if (getException() != null) { throw getException(); } return (GridServiceAgent[]) result; } }; }
From source file:no.ntnu.osnap.com.Protocol.java
/** * Sends raw data expressed as a byte array to the remote device to the specified pint * @param pin/* ww w .j ava 2 s . c o m*/ * @param data array of bytes to send * @param blocking determines if method should wait until a Timeout happens or should return * immediately and send data asynchronously. * @throws TimeoutException */ public final void data(byte[] data, boolean blocking) throws TimeoutException { ArrayList<ProtocolInstruction> newInstructions = new ArrayList<ProtocolInstruction>(); //ProtocolInstruction tempInstruction; /*if (data.length > MAX_CONTENT_SIZE){ byte[] tempBytes = new byte[MAX_CONTENT_SIZE]; int restSize = 0; for (int i = 0; i < data.length; ++i){ tempBytes[i % MAX_CONTENT_SIZE] = data[i]; if (i % MAX_CONTENT_SIZE == 0){ newInstructions.add( new ProtocolInstruction(OpCode.DATA, (byte)1, tempBytes) ); if (data.length - i < MAX_CONTENT_SIZE){ restSize = data.length - i; } } } byte[] restBytes = new byte[restSize]; for (int i = 0; i < restSize; ++i){ restBytes[i] = tempBytes[i]; } newInstructions.add( new ProtocolInstruction(OpCode.DATA, (byte)0, restBytes) ); } else*/ { newInstructions.add(new ProtocolInstruction(OpCode.DATA, (byte) 0, data)); } if (!blocking) { for (ProtocolInstruction instr : newInstructions) { queueInstruction(instr); } } else { lock(); for (ProtocolInstruction newInstruction : newInstructions) { waitingForAck = OpCode.DATA; try { sendBytes(newInstruction.getInstructionBytes()); } catch (IOException ex) { System.out.println("Send fail"); } long time = System.currentTimeMillis(); while (waitingForAck != null) { if (System.currentTimeMillis() - time > TIMEOUT) { waitingForAck = null; throw new TimeoutException("Timeout"); } try { Thread.sleep(10); } catch (InterruptedException ex) { } } ackProcessingComplete(); } release(); } }
From source file:org.cloudifysource.esc.driver.provisioning.jclouds.DefaultProvisioningDriver.java
private NodeMetadata waitForNodeToBecomeReady(final String id, final long end) throws CloudProvisioningException, InterruptedException, TimeoutException { NodeMetadata node = null;/*from www.j a v a 2 s. c o m*/ while (System.currentTimeMillis() < end) { node = deployer.getServerByID(id); if (node == null) { logger.fine("Server Status (" + id + ") Not Found, please wait..."); Thread.sleep(CLOUD_NODE_STATE_POLLING_INTERVAL); break; } else { switch (node.getStatus()) { case RUNNING: return node; case PENDING: logger.fine("Server Status (" + id + ") still PENDING, please wait..."); Thread.sleep(CLOUD_NODE_STATE_POLLING_INTERVAL); break; case TERMINATED: case ERROR: case UNRECOGNIZED: case SUSPENDED: default: throw new CloudProvisioningException("Failed to allocate server - Cloud reported node in " + node.getStatus().toString() + " state. Node details: " + node); } } } throw new TimeoutException("Node failed to reach RUNNING mode in time"); }
From source file:org.apache.aurora.common.zookeeper.ZooKeeperClient.java
/** * Returns the current active ZK connection or establishes a new one if none has yet been * established or a previous connection was disconnected or had its session time out. This * method will attempt to re-use sessions when possible. * * @param connectionTimeout the maximum amount of time to wait for the connection to the ZK * cluster to be established; 0 to wait forever * @return a connected ZooKeeper client//from w w w .j a v a 2 s. c o m * @throws ZooKeeperConnectionException if there was a problem connecting to the ZK cluster * @throws InterruptedException if interrupted while waiting for a connection to be established * @throws TimeoutException if a connection could not be established within the configured * session timeout */ public synchronized ZooKeeper get(Amount<Long, Time> connectionTimeout) throws ZooKeeperConnectionException, InterruptedException, TimeoutException { if (zooKeeper == null) { final CountDownLatch connected = new CountDownLatch(1); Watcher watcher = event -> { switch (event.getType()) { // Guard the None type since this watch may be used as the default watch on calls by // the client outside our control. case None: switch (event.getState()) { case Expired: LOG.info("Zookeeper session expired. Event: " + event); close(); break; case SyncConnected: connected.countDown(); break; } } eventQueue.offer(event); }; try { zooKeeper = (sessionState != null) ? new ZooKeeper(zooKeeperServers, sessionTimeoutMs, watcher, sessionState.sessionId, sessionState.sessionPasswd) : new ZooKeeper(zooKeeperServers, sessionTimeoutMs, watcher); } catch (IOException e) { throw new ZooKeeperConnectionException("Problem connecting to servers: " + zooKeeperServers, e); } if (connectionTimeout.getValue() > 0) { if (!connected.await(connectionTimeout.as(Time.MILLISECONDS), TimeUnit.MILLISECONDS)) { close(); throw new TimeoutException("Timed out waiting for a ZK connection after " + connectionTimeout); } } else { try { connected.await(); } catch (InterruptedException ex) { LOG.info("Interrupted while waiting to connect to zooKeeper"); close(); throw ex; } } credentials.authenticate(zooKeeper); sessionState = new SessionState(zooKeeper.getSessionId(), zooKeeper.getSessionPasswd()); } return zooKeeper; }
From source file:org.apache.hadoop.hdfs.server.balancer.TestBalancer.java
/** * Wait until balanced: each datanode gives utilization within * BALANCE_ALLOWED_VARIANCE of average/* ww w .ja v a2 s . c o m*/ * @throws IOException * @throws TimeoutException */ static void waitForBalancer(long totalUsedSpace, long totalCapacity, ClientProtocol client, MiniDFSCluster cluster, Balancer.Parameters p, int expectedExcludedNodes) throws IOException, TimeoutException { long timeout = TIMEOUT; long failtime = (timeout <= 0L) ? Long.MAX_VALUE : Time.now() + timeout; if (!p.nodesToBeIncluded.isEmpty()) { totalCapacity = p.nodesToBeIncluded.size() * CAPACITY; } if (!p.nodesToBeExcluded.isEmpty()) { totalCapacity -= p.nodesToBeExcluded.size() * CAPACITY; } final double avgUtilization = ((double) totalUsedSpace) / totalCapacity; boolean balanced; do { DatanodeInfo[] datanodeReport = client.getDatanodeReport(DatanodeReportType.ALL); assertEquals(datanodeReport.length, cluster.getDataNodes().size()); balanced = true; int actualExcludedNodeCount = 0; for (DatanodeInfo datanode : datanodeReport) { double nodeUtilization = ((double) datanode.getDfsUsed()) / datanode.getCapacity(); if (Dispatcher.Util.isExcluded(p.nodesToBeExcluded, datanode)) { assertTrue(nodeUtilization == 0); actualExcludedNodeCount++; continue; } if (!Dispatcher.Util.isIncluded(p.nodesToBeIncluded, datanode)) { assertTrue(nodeUtilization == 0); actualExcludedNodeCount++; continue; } if (Math.abs(avgUtilization - nodeUtilization) > BALANCE_ALLOWED_VARIANCE) { balanced = false; if (Time.now() > failtime) { throw new TimeoutException("Rebalancing expected avg utilization to become " + avgUtilization + ", but on datanode " + datanode + " it remains at " + nodeUtilization + " after more than " + TIMEOUT + " msec."); } try { Thread.sleep(100); } catch (InterruptedException ignored) { } break; } } assertEquals(expectedExcludedNodes, actualExcludedNodeCount); } while (!balanced); }
From source file:org.apache.hadoop.hdfs.server.namenode.ha.TestPipelinesFailover.java
/** * Try to recover the lease on the given file for up to 60 seconds. * @param fsOtherUser the filesystem to use for the recoverLease call * @param testPath the path on which to run lease recovery * @throws TimeoutException if lease recover does not succeed within 60 * seconds//from ww w . j a v a 2 s . c om * @throws InterruptedException if the thread is interrupted */ private static void loopRecoverLease(final FileSystem fsOtherUser, final Path testPath) throws TimeoutException, InterruptedException, IOException { try { GenericTestUtils.waitFor(new Supplier<Boolean>() { @Override public Boolean get() { boolean success; try { success = ((DistributedFileSystem) fsOtherUser).recoverLease(testPath); } catch (IOException e) { throw new RuntimeException(e); } if (!success) { LOG.info("Waiting to recover lease successfully"); } return success; } }, 5000, 600000); } catch (TimeoutException e) { throw new TimeoutException("Timed out recovering lease for " + testPath); } }
From source file:no.group09.connection.Protocol.java
/** * Sends raw data expressed as a byte array to the remote device to the specified pint * @param pin//from w w w. j a v a 2s.co m * @param data array of bytes to send * @param blocking determines if method should wait until a Timeout happens or should return * immediately and send data asynchronously. * @throws TimeoutException */ public final void data(byte[] data, boolean blocking) throws TimeoutException { ArrayList<ProtocolInstruction> newInstructions = new ArrayList<ProtocolInstruction>(); //ProtocolInstruction tempInstruction; /*if (data.length > MAX_CONTENT_SIZE){ byte[] tempBytes = new byte[MAX_CONTENT_SIZE]; int restSize = 0; for (int i = 0; i < data.length; ++i){ tempBytes[i % MAX_CONTENT_SIZE] = data[i]; if (i % MAX_CONTENT_SIZE == 0){ newInstructions.add( new ProtocolInstruction(OpCode.DATA, (byte)1, tempBytes) ); if (data.length - i < MAX_CONTENT_SIZE){ restSize = data.length - i; } } } byte[] restBytes = new byte[restSize]; for (int i = 0; i < restSize; ++i){ restBytes[i] = tempBytes[i]; } newInstructions.add( new ProtocolInstruction(OpCode.DATA, (byte)0, restBytes) ); } else*/ { newInstructions.add(new ProtocolInstruction(OpCode.DATA, (byte) 0, data)); } if (!blocking) { for (ProtocolInstruction instr : newInstructions) { queueInstruction(instr); } } else { lock(); for (ProtocolInstruction newInstruction : newInstructions) { waitingForAck = OpCode.DATA; try { sendBytes(newInstruction.getInstructionBytes()); } catch (IOException ex) { Log.d(TAG, "Send fail"); } long time = System.currentTimeMillis(); while (waitingForAck != null) { if (System.currentTimeMillis() - time > TIMEOUT) { waitingForAck = null; throw new TimeoutException("Timeout"); } try { Thread.sleep(10); } catch (InterruptedException ex) { } } ackProcessingComplete(); } release(); } }
From source file:org.apache.marmotta.platform.sparql.services.sparql.SparqlServiceImpl.java
@Override public void query(final QueryLanguage language, final String query, final OutputStream output, final String format, int timeoutInSeconds) throws MarmottaException, TimeoutException, MalformedQueryException { log.debug("executing SPARQL query:\n{}", query); Future<Boolean> future = executorService.submit(new Callable<Boolean>() { @Override//w w w . j a va2s .c o m public Boolean call() throws Exception { long start = System.currentTimeMillis(); try { RepositoryConnection connection = sesameService.getConnection(); try { connection.begin(); Query sparqlQuery = connection.prepareQuery(language, query, configurationService.getBaseUri()); if (sparqlQuery instanceof TupleQuery) { query((TupleQuery) sparqlQuery, output, format); } else if (sparqlQuery instanceof BooleanQuery) { query((BooleanQuery) sparqlQuery, output, format); } else if (sparqlQuery instanceof GraphQuery) { query((GraphQuery) sparqlQuery, output, format); } else { throw new InvalidArgumentException( "SPARQL query type " + sparqlQuery.getClass() + " not supported!"); } connection.commit(); } catch (Exception ex) { connection.rollback(); throw ex; } finally { connection.close(); } } catch (RepositoryException e) { log.error("error while getting repository connection: {}", e); throw new MarmottaException("error while getting repository connection", e); } catch (QueryEvaluationException e) { log.error("error while evaluating query: {}", e); throw new MarmottaException("error while evaluating query ", e); } catch (MalformedQueryException e) { log.error("error because malformed query: {}", e); throw new MarmottaException("error because malformed query", e); } log.debug("SPARQL execution took {}ms", System.currentTimeMillis() - start); return Boolean.TRUE; } }); try { future.get(timeoutInSeconds, TimeUnit.SECONDS); } catch (InterruptedException | TimeoutException e) { log.info("SPARQL query execution aborted due to timeout"); future.cancel(true); throw new TimeoutException("SPARQL query execution aborted due to timeout (" + configurationService.getIntConfiguration("sparql.timeout", 60) + "s)"); } catch (ExecutionException e) { log.info("SPARQL query execution aborted due to exception"); log.debug("exception details", e); if (e.getCause() instanceof MarmottaException) { throw (MarmottaException) e.getCause(); } else if (e.getCause() instanceof MalformedQueryException) { throw (MalformedQueryException) e.getCause(); } else { throw new MarmottaException("unknown exception while evaluating SPARQL query", e.getCause()); } } }