Example usage for java.util.concurrent TimeoutException TimeoutException

List of usage examples for java.util.concurrent TimeoutException TimeoutException

Introduction

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

Prototype

public TimeoutException(String message) 

Source Link

Document

Constructs a TimeoutException with the specified detail message.

Usage

From source file:org.apache.hadoop.hdfs.server.namenode.TestHABasicFailover.java

public static void waitLeaderElection(List<DataNode> datanodes, NameNode nn, long timeout)
        throws TimeoutException {
    // wait for the new leader to be elected
    long initTime = System.currentTimeMillis();
    while (!nn.isLeader()) {
        try {//from  w  ww. ja v a  2s. c  o  m
            Thread.sleep(500);
        } catch (InterruptedException ex) {
            ex.printStackTrace();
        }

        // check for time out
        if (System.currentTimeMillis() - initTime >= timeout) {
            throw new TimeoutException("Namenode was not elected leader. Time out " + timeout);
        }
    }

    // wait for all datanodes to recognize the new leader
    initTime = System.currentTimeMillis();
    while (true) {

        try {
            Thread.sleep(2000); // 2sec
        } catch (InterruptedException ex) {
            ex.printStackTrace();
        }

        boolean result = doesDataNodesRecognizeLeader(datanodes, nn);
        if (result) {
            break;
        }
        // check for time out
        if (System.currentTimeMillis() - initTime >= timeout) {
            throw new TimeoutException("Datanodes weren't able to detect newly elected leader");
        }
    }
}

From source file:org.cloudifysource.esc.driver.provisioning.jclouds.DefaultProvisioningDriver.java

@Override
public MachineDetails startMachine(final String locationId, final long timeout, final TimeUnit unit)
        throws TimeoutException, CloudProvisioningException {

    logger.fine(this.getClass().getName() + ": startMachine, management mode: " + management);
    final long end = System.currentTimeMillis() + unit.toMillis(timeout);

    if (System.currentTimeMillis() > end) {
        throw new TimeoutException("Starting a new machine timed out");
    }/* ww  w  .j  a v  a  2s .  c  om*/

    try {
        final String groupName = createNewServerName();
        logger.fine("Starting a new cloud server with group: " + groupName);
        final MachineDetails md = createServer(end, groupName, locationId);
        return md;
    } catch (final Exception e) {
        throw new CloudProvisioningException("Failed to start cloud machine", e);
    }
}

From source file:uk.ac.gda.epics.client.mythen.views.LivePlotComposite.java

@Override
public void dispose() {
    if (eventAdmin != null) {
        eventAdmin.deleteIObserver(this);
        executor.shutdown();//from   ww  w. j a  va2s  .  c o  m
        boolean terminated;
        try {
            terminated = executor.awaitTermination(1, TimeUnit.MINUTES);
            if (!terminated) {
                throw new TimeoutException("Timed out waiting for plotting data file.t");
            }
        } catch (InterruptedException | TimeoutException e) {
            logger.error("Unable to plot data", e);
            throw new RuntimeException("Unable to plot data from data file.", e);
        }
    }
    if (getStartListener() != null) {
        getStartListener().deleteIObserver(this);
    }
    // clean up resources used.
    if (!plottingSystem.isDisposed()) {
        plottingSystem.clear();
    }
    plottingSystem.dispose();
    // remove reference
    super.dispose();
}

From source file:org.openspaces.admin.application.deploy.AbstractApplicationCommand.java

protected GridServiceManager waitForGridServiceManager() throws TimeoutException {
    info("Waiting for Grid Service Manager");
    final Admin admin = createAdmin();
    final GridServiceManager gsm = admin.getGridServiceManagers().waitForAtLeastOne(lookupTimeout,
            TimeUnit.MILLISECONDS);
    if (gsm == null) {
        throw new TimeoutException("GSM discovery timed out after "
                + TimeUnit.SECONDS.convert(lookupTimeout, TimeUnit.MILLISECONDS) + " seconds");
    }//from   ww w . ja va 2s.  com
    return gsm;
}

From source file:org.cloudifysource.rest.deploy.ApplicationDeployerRunnable.java

private void installServices(final boolean async) throws IOException {

    final File appDir = result.getApplicationDir();

    logger.info("Installing services for application: " + applicationName + ". Async install: " + async
            + ". Number of services: " + this.services.size());
    for (final Service service : services) {
        logger.info("Installing service: " + service.getName() + " for application: " + applicationName);
        service.getCustomProperties().put("usmJarPath", Environment.getHomeDirectory() + "/lib/platform/usm");

        final String serviceName = service.getName();
        final String absolutePUName = ServiceUtils.getAbsolutePUName(applicationName, serviceName);
        final File serviceDirectory = new File(appDir, serviceName);

        boolean found = false;

        try {//from   w ww  .  j a  v  a2s  . c  o  m
            // lookup application properties file
            final File applicationPropertiesFile = DSLReader
                    .findDefaultDSLFileIfExists(DSLUtils.APPLICATION_PROPERTIES_FILE_NAME, appDir);
            // lookup overrides file
            File actualOverridesFile = overridesFile;
            if (actualOverridesFile == null) {
                // when using the CLI, the application overrides file is inside the directory
                actualOverridesFile = DSLReader
                        .findDefaultDSLFileIfExists(DSLUtils.APPLICATION_OVERRIDES_FILE_NAME, appDir);
            }
            // Pack the folder and name it absolutePuName
            final File packedFile = Packager.pack(service, serviceDirectory, absolutePUName, null);
            result.getApplicationFile().delete();
            packedFile.deleteOnExit();
            // Deployment will be done using the service's absolute PU name.
            final InstallServiceRequest installServiceReq = createInstallServiceRequest(packedFile);
            final String appName = this.request.getApplicationName();

            final DeploymentFileHolder fileHolder = new DeploymentFileHolder();
            fileHolder.setPackedFile(packedFile);
            fileHolder.setServiceOverridesFile(actualOverridesFile);
            fileHolder.setApplicationPropertiesFile(applicationPropertiesFile);

            controller.installServiceInternal(appName, serviceName, installServiceReq, deploymentID,
                    fileHolder);
            try {
                FileUtils.deleteDirectory(packedFile.getParentFile());
            } catch (final IOException ioe) {
                // sometimes this delete fails. Not sure why. Maybe deploy
                // is async?
                logger.warning("Failed to delete temporary directory: " + packedFile.getParentFile());
            }

            if (!async) {
                logger.info("Waiting for instance of service: " + serviceName + " of application: "
                        + applicationName);
                final boolean instanceFound = controller.waitForServiceInstance(applicationName, serviceName,
                        SERVICE_INSTANCE_STARTUP_TIMEOUT_MINUTES, TimeUnit.MINUTES);
                if (!instanceFound) {
                    throw new TimeoutException("Service " + serviceName + " of application " + applicationName
                            + " was installed, but no instance of the service has started after "
                            + SERVICE_INSTANCE_STARTUP_TIMEOUT_MINUTES + " minutes.");
                }
                logger.info("Found instance of: " + serviceName);
            }

            found = true;
            logger.fine("service " + service + " deployed.");
        } catch (final Exception e) {
            logger.log(Level.SEVERE, "Failed to install service: " + serviceName + " of application: "
                    + applicationName + ". Application installation will halt. "
                    + "Some services may already have started, and should be shutdown manually. Error was: "
                    + e.getMessage(), e);
            return;
        }

        if (!found) {
            logger.severe("Failed to find an instance of service: " + serviceName
                    + " while installing application " + applicationName
                    + ". Application installation will stop. Some services may have been installed!");
            return;
        }
    }
    FileUtils.deleteDirectory(appDir);
}

From source file:ch.ivyteam.ivy.maven.engine.EngineControl.java

private void waitForEngineStart(Executor executor) throws Exception {
    int i = 0;/*from w w w  . ja  v  a2 s .com*/
    while (!engineStarted.get()) {
        Thread.sleep(1_000);
        i++;
        if (!executor.getWatchdog().isWatching()) {
            throw new RuntimeException("Engine start failed unexpected.");
        }
        if (i > context.timeoutInSeconds) {
            throw new TimeoutException("Timeout while starting engine " + context.timeoutInSeconds + " [s].\n"
                    + "Check the engine log for details or increase the timeout property '"
                    + StartTestEngineMojo.IVY_ENGINE_START_TIMEOUT_SECONDS + "'");
        }
    }
    context.log.info("Engine started after " + i + " [s]");
}

From source file:com.netflix.genie.web.rpc.grpc.services.impl.v4.GRpcAgentFileStreamServiceImpl.java

/**
 * {@inheritDoc}/*from  w w  w  .  j  ava  2  s .c o m*/
 */
@Override
public Optional<AgentFileResource> getResource(final String jobId, final Path relativePath, final URI uri) {

    final ControlStreamObserver streamObserver = this.jobIdControlStreamMap.get(jobId);
    if (streamObserver == null) {
        log.warn("Stream Record not found for job id: {}", jobId);
        return Optional.empty();
    }

    final JobDirectoryManifest manifest = streamObserver.manifestRef.get();
    if (manifest == null) {
        log.warn("Stream record for job id: {} does not have a manifest", jobId);
        return Optional.empty();
    }

    final JobDirectoryManifest.ManifestEntry manifestEntry = manifest.getEntry(relativePath.toString())
            .orElse(null);

    if (manifestEntry == null) {
        // File does not exist according to manifest
        log.warn("Requesting a file that does not exist in the manifest for job id: {}: ", jobId, relativePath);
        return Optional.of(AgentFileResourceImpl.forNonExistingResource());
    }

    // A unique ID for this file transfer
    final String fileTransferId = UUID.randomUUID().toString();

    // TODO: code upstream of here assumes files is requested in its entirety.
    // But rest of the code downstream actually treats everything as a range request.
    final int startOffset = 0;
    final int endOffset = Math.toIntExact(manifestEntry.getSize());

    // Allocate and park the buffer that will store the data in transit.
    final StreamBuffer buffer = new StreamBuffer();

    if (endOffset - startOffset == 0) {
        // When requesting an empty file (or a range of 0 bytes), short-circuit and just return an empty resource.
        buffer.closeForCompleted();
    } else {
        // Expecting some data. Track this stream and its buffer so incoming chunks can be appended.
        this.pendingTransferBuffersMap.put(fileTransferId, buffer);

        // Request file over control channel
        streamObserver.responseObserver.onNext(ServerControlMessage.newBuilder()
                .setServerFileRequest(ServerFileRequestMessage.newBuilder().setStreamId(fileTransferId)
                        .setRelativePath(relativePath.toString()).setStartOffset(startOffset)
                        .setEndOffset(endOffset).build())
                .build());

        // Schedule a timeout for this transfer to start (first chunk received)
        this.taskScheduler.schedule(() -> {
            final StreamBuffer b = pendingTransferBuffersMap.remove(fileTransferId);
            // Is this stream/buffer still in the 'pending' map?
            if (b != null) {
                b.closeForError(new TimeoutException("Timeout waiting for transfer to start"));
            }
        }, Instant.now().plusMillis(FILE_TRANSFER_BEGIN_TIMEOUT_MILLIS));
    }

    final AgentFileResource resource = AgentFileResourceImpl.forAgentFile(uri, manifestEntry.getSize(),
            manifestEntry.getLastModifiedTime(), Paths.get(manifestEntry.getPath()), jobId,
            buffer.getInputStream());

    return Optional.of(resource);
}

From source file:gobblin.couchbase.writer.CouchbaseWriter.java

@Override
public Future<WriteResponse> write(final D record, final WriteCallback callback) {
    assertRecordWritable(record);/*  w w  w  .j  a  v a 2s .  c  o m*/
    if (record instanceof TupleDocument) {
        ((TupleDocument) record).content().value1().retain();
    }
    Observable<D> observable = _bucket.async().upsert(record);
    if (callback == null) {
        return new WriteResponseFuture<>(
                observable.timeout(_operationTimeout, _operationTimeunit).toBlocking().toFuture(),
                _defaultWriteResponseMapper);
    } else {

        final AtomicBoolean callbackFired = new AtomicBoolean(false);
        final BlockingQueue<Pair<WriteResponse, Throwable>> writeResponseQueue = new ArrayBlockingQueue<>(1);

        final Future<WriteResponse> writeResponseFuture = new Future<WriteResponse>() {
            @Override
            public boolean cancel(boolean mayInterruptIfRunning) {
                return false;
            }

            @Override
            public boolean isCancelled() {
                return false;
            }

            @Override
            public boolean isDone() {
                return callbackFired.get();
            }

            @Override
            public WriteResponse get() throws InterruptedException, ExecutionException {
                Pair<WriteResponse, Throwable> writeResponseThrowablePair = writeResponseQueue.take();
                return getWriteResponseorThrow(writeResponseThrowablePair);
            }

            @Override
            public WriteResponse get(long timeout, TimeUnit unit)
                    throws InterruptedException, ExecutionException, TimeoutException {
                Pair<WriteResponse, Throwable> writeResponseThrowablePair = writeResponseQueue.poll(timeout,
                        unit);
                if (writeResponseThrowablePair == null) {
                    throw new TimeoutException("Timeout exceeded while waiting for future to be done");
                } else {
                    return getWriteResponseorThrow(writeResponseThrowablePair);
                }
            }
        };

        observable.timeout(_operationTimeout, _operationTimeunit).subscribe(new Subscriber<D>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable e) {
                callbackFired.set(true);
                writeResponseQueue.add(new Pair<WriteResponse, Throwable>(null, e));
                callback.onFailure(e);
            }

            @Override
            public void onNext(D doc) {
                try {
                    callbackFired.set(true);
                    WriteResponse writeResponse = new GenericWriteResponse<D>(doc);
                    writeResponseQueue.add(new Pair<WriteResponse, Throwable>(writeResponse, null));
                    callback.onSuccess(writeResponse);
                } finally {
                    if (doc instanceof TupleDocument) {
                        ((TupleDocument) doc).content().value1().release();
                    }
                }
            }
        });
        return writeResponseFuture;
    }
}

From source file:com.vmware.photon.controller.common.dcp.ServiceHostUtils.java

/**
 * Function used to wait for a service to be available.
 *
 * @param host// w  w  w .j  ava2s . c  om
 * @param timeout
 * @param serviceLinks
 * @throws Throwable
 */
public static void waitForServiceAvailability(ServiceHost host, long timeout, String... serviceLinks)
        throws Throwable {
    final CountDownLatch latch = new CountDownLatch(serviceLinks.length);
    final Throwable error = new Throwable("Error: registerForAvailability returned errors");

    Operation.CompletionHandler handler = new Operation.CompletionHandler() {
        @Override
        public void handle(Operation operation, Throwable throwable) {
            if (null != throwable) {
                error.addSuppressed(throwable);
            }

            latch.countDown();
        }
    };
    host.registerForServiceAvailability(handler, serviceLinks);

    if (!latch.await(timeout, TimeUnit.MILLISECONDS)) {
        throw new TimeoutException(
                String.format("One or several of service(s) %s not available", Utils.toJson(serviceLinks)));
    }

    if (error.getSuppressed().length > 0) {
        throw error;
    }
}

From source file:org.apache.oozie.test.hive.MiniHS2.java

private void waitForStartup() throws Exception {
    int waitTime = 0;
    long startupTimeout = 1000L * 1000000000L;
    CLIServiceClient hs2Client = getServiceClientInternal();
    SessionHandle sessionHandle = null;/*from   ww w.j av  a  2  s  .c om*/
    do {
        Thread.sleep(500L);
        waitTime += 500L;
        if (waitTime > startupTimeout) {
            throw new TimeoutException("Couldn't access new HiveServer2: " + getJdbcURL());
        }
        try {
            sessionHandle = hs2Client.openSession("foo", "bar");
        } catch (Exception e) {
            // service not started yet
            continue;
        }
        hs2Client.closeSession(sessionHandle);
        break;
    } while (true);
}