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.cloudifysource.esc.driver.provisioning.storage.aws.EbsStorageDriver.java

private void waitForVolumeToReachStatus(final Status status, final long end, final String volumeId)
        throws TimeoutException, StorageProvisioningException {

    logger.fine("Waiting for volume '" + volumeId + "' to reach status " + status);

    Set<Volume> volumes;//from w ww  .j a v a2 s  . c  om
    while (System.currentTimeMillis() < end) {
        try {
            volumes = this.ebsClient.describeVolumesInRegion(this.region, volumeId);
            Thread.sleep(WAIT_FOR_STATUS_RETRY_INTERVAL_MILLIS);
        } catch (Exception e) {
            throw new StorageProvisioningException(
                    "Failed getting volume description." + " Reason: " + e.getMessage(), e);
        }
        Volume volume = volumes.iterator().next();
        Status volumeStatus = volume.getStatus();
        if (volumeStatus.equals(status)) {
            return;
        } else {
            logger.fine("Volume[" + volumeId + "] is in status " + volume.getStatus());
        }
    }
    throw new TimeoutException("Timed out waiting for storage status to become " + status.toString());
}

From source file:no.group09.connection.Protocol.java

/**
 * Set the specified pin on the remote device to HIGH (true) or LOW (false)
 * @param pin which pin to change/*from  w w  w .j  ava2s  .co m*/
 * @param value true if the pin is to be set HIGH or false if it is LOW
 * @param blocking determines if this method should wait until success or Timeout happens
 * @throws TimeoutException if the remote device used too long to respond
 */
public final void write(int pin, boolean value, boolean blocking) throws TimeoutException {
    ProtocolInstruction newInstruction = new ProtocolInstruction(OpCode.PIN_W, (byte) pin,
            new byte[] { value ? (byte) 1 : (byte) 0 });

    if (!blocking) {
        queueInstruction(newInstruction);
    } else {
        lock();

        waitingForAck = OpCode.PIN_W;

        try {
            sendBytes(newInstruction.getInstructionBytes());
        } catch (IOException ex) {
            System.out.println("Send fail");
        }
        release();

        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();
    }
}

From source file:gobblin.runtime.embedded.EmbeddedGobblin.java

/**
 * Launch the Gobblin job asynchronously. This method will return when the Gobblin job has started.
 * @return a {@link JobExecutionDriver}. This object is a future that will resolve when the Gobblin job finishes.
 * @throws TimeoutException if the Gobblin job does not start within the launch timeout.
 *//* ww w  .j ava  2s  .c o  m*/
@NotOnCli
public JobExecutionDriver runAsync() throws TimeoutException, InterruptedException {
    // Run function to distribute jars to workers in distributed mode
    this.distributeJarsFunction.run();

    Config sysProps = ConfigFactory.parseMap(this.builtConfigMap).withFallback(this.defaultSysConfig);
    Config userConfig = ConfigFactory.parseMap(this.userConfigMap);

    JobSpec jobSpec;
    if (this.jobFile.isPresent()) {
        try {
            Path jobFilePath = this.jobFile.get();
            PullFileLoader loader = new PullFileLoader(jobFilePath.getParent(),
                    jobFilePath.getFileSystem(new Configuration()),
                    PullFileLoader.DEFAULT_JAVA_PROPS_PULL_FILE_EXTENSIONS,
                    PullFileLoader.DEFAULT_HOCON_PULL_FILE_EXTENSIONS);
            Config jobConfig = userConfig.withFallback(loader.loadPullFile(jobFilePath, sysProps, false));
            ImmutableFSJobCatalog.JobSpecConverter converter = new ImmutableFSJobCatalog.JobSpecConverter(
                    jobFilePath.getParent(), Optional.<String>absent());
            jobSpec = converter.apply(jobConfig);
        } catch (IOException ioe) {
            throw new RuntimeException("Failed to run embedded Gobblin.", ioe);
        }
    } else {
        Config finalConfig = userConfig.withFallback(sysProps);
        if (this.template != null) {
            try {
                finalConfig = this.template.getResolvedConfig(finalConfig);
            } catch (SpecNotFoundException | JobTemplate.TemplateException exc) {
                throw new RuntimeException(exc);
            }
        }
        jobSpec = this.specBuilder.withConfig(finalConfig).build();
    }

    ResolvedJobSpec resolvedJobSpec;
    try {
        resolvedJobSpec = new ResolvedJobSpec(jobSpec);
    } catch (SpecNotFoundException | JobTemplate.TemplateException exc) {
        throw new RuntimeException("Failed to resolved template.", exc);
    }
    final JobCatalog jobCatalog = new StaticJobCatalog(Optional.of(this.useLog),
            Lists.<JobSpec>newArrayList(resolvedJobSpec));

    SimpleGobblinInstanceEnvironment instanceEnvironment = new SimpleGobblinInstanceEnvironment(
            "EmbeddedGobblinInstance", this.useLog, getSysConfig());

    StandardGobblinInstanceDriver.Builder builder = new StandardGobblinInstanceDriver.Builder(
            Optional.<GobblinInstanceEnvironment>of(instanceEnvironment)).withLog(this.useLog)
                    .withJobCatalog(jobCatalog).withImmediateJobScheduler();

    for (GobblinInstancePluginFactory plugin : this.plugins) {
        builder.addPlugin(plugin);
    }

    final GobblinInstanceDriver driver = builder.build();

    EmbeddedJobLifecycleListener listener = new EmbeddedJobLifecycleListener(this.useLog);
    driver.registerJobLifecycleListener(listener);

    driver.startAsync();

    boolean started = listener.awaitStarted(this.launchTimeout.getTimeout(), this.launchTimeout.getTimeUnit());
    if (!started) {
        log.warn("Timeout waiting for job to start. Aborting.");
        driver.stopAsync();
        driver.awaitTerminated(this.shutdownTimeout.getTimeout(), this.shutdownTimeout.getTimeUnit());
        throw new TimeoutException("Timeout waiting for job to start.");
    }

    final JobExecutionDriver jobDriver = listener.getJobDriver();
    // Stop the Gobblin instance driver when the job finishes.
    Futures.addCallback(jobDriver, new FutureCallback<JobExecutionResult>() {
        @Override
        public void onSuccess(@Nullable JobExecutionResult result) {

            stopGobblinInstanceDriver();
        }

        @Override
        public void onFailure(Throwable t) {
            stopGobblinInstanceDriver();
        }

        private void stopGobblinInstanceDriver() {
            try {
                driver.stopAsync();
                driver.awaitTerminated(EmbeddedGobblin.this.shutdownTimeout.getTimeout(),
                        EmbeddedGobblin.this.shutdownTimeout.getTimeUnit());
            } catch (TimeoutException te) {
                log.error("Failed to shutdown Gobblin instance driver.");
            }
        }
    });

    return listener.getJobDriver();
}

From source file:org.cloudifysource.esc.driver.provisioning.openstack.OpenStackCloudifyDriver.java

@Override
public MachineDetails startMachine(final ProvisioningContext context, final long duration, final TimeUnit unit)
        throws TimeoutException, CloudProvisioningException {
    logger.fine(this.getClass().getName() + ": startMachine, management mode: " + management);
    final long end = System.currentTimeMillis() + unit.toMillis(duration);

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

    try {
        // Create application secgroups
        this.createSecurityGroup(this.openstackPrefixes.getApplicationName());
        this.createSecurityGroup(this.openstackPrefixes.getServiceName());
        this.createSecurityGroupsRules();

        if (networkHelper.useApplicationNetworkTemplate()) {
            // Network
            final Network network = this
                    .getOrCreateNetwork(this.networkHelper.getApplicationNetworkPrefixedName());
            if (network != null) {
                // Subnets
                final NetworkConfiguration networkTemplate = this.networkHelper.getApplicationNetworkTemplate();
                final List<org.cloudifysource.domain.cloud.network.Subnet> subnets = networkTemplate
                        .getSubnets();
                for (final org.cloudifysource.domain.cloud.network.Subnet subnetConfig : subnets) {
                    this.getOrCreateSubnet(subnetConfig, network);
                }
            }
        }

        final String groupName = serverNamePrefix + this.configuration.getServiceName() + "-"
                + counter.incrementAndGet();
        logger.fine("Starting a new cloud server with group: " + groupName);
        final ComputeTemplate computeTemplate = this.cloud.getCloudCompute().getTemplates()
                .get(this.cloudTemplateName);

        final MachineDetails md = this.createServer(groupName, end, computeTemplate, context.getLocationId());
        return md;
    } catch (final OpenstackException e) {
        throw new CloudProvisioningException("Failed to start cloud machine", e);
    }
}

From source file:org.apache.hive.jdbc.miniHS2.MiniHS2.java

private void waitForStartup() throws Exception {
    int waitTime = 0;
    long startupTimeout = 1000L * 1000L;
    CLIServiceClient hs2Client = getServiceClientInternal();
    SessionHandle sessionHandle = null;//from w  w w .  j a  v  a2 s  .c  o  m
    do {
        Thread.sleep(500L);
        waitTime += 500L;
        if (waitTime > startupTimeout) {
            throw new TimeoutException("Couldn't access new HiveServer2: " + getJdbcURL());
        }
        try {
            Map<String, String> sessionConf = new HashMap<String, String>();
            /**
            if (isUseMiniKdc()) {
              getMiniKdc().loginUser(getMiniKdc().getDefaultUserPrincipal());
              sessionConf.put("principal", serverPrincipal);
            }
             */
            sessionHandle = hs2Client.openSession("foo", "bar", sessionConf);
        } catch (Exception e) {
            // service not started yet
            continue;
        }
        hs2Client.closeSession(sessionHandle);
        break;
    } while (true);
}

From source file:org.cloudifysource.esc.driver.provisioning.azure.client.MicrosoftAzureRestClient.java

/**
 * This method creates a virtual machine and a corresponding cloud service.
 * the cloud service will use the affinity group specified by deploymentDesc.getAffinityGroup();
 * If another request was made this method will wait until the pending request is finished.
 * //from w  w  w.j av  a 2 s  .  c  o m
 * If a failure happened after the cloud service was created, this method will delete it and throw.
 * 
 * @param deplyomentDesc
 *            .
 * @param endTime
 *            .
 * @return an instance of {@link RoleDetails} containing the ip addresses
 *         information for the created role.
 * @throws MicrosoftAzureException .
 * @throws TimeoutException .
 * @throws InterruptedException .
 */
public RoleDetails createVirtualMachineDeployment(
        final CreatePersistentVMRoleDeploymentDescriptor deplyomentDesc, final long endTime)
        throws MicrosoftAzureException, TimeoutException, InterruptedException {

    long currentTimeInMillis = System.currentTimeMillis();
    long lockTimeout = endTime - currentTimeInMillis - ESTIMATED_TIME_TO_START_VM;
    if (lockTimeout < 0) {
        throw new MicrosoftAzureException("Aborted request to provision virtual machine. "
                + "The timeout is less then the estimated time to provision the machine");
    }

    logger.fine(getThreadIdentity() + "Waiting for pending request lock for lock " + pendingRequest.hashCode());
    boolean lockAcquired = pendingRequest.tryLock(lockTimeout, TimeUnit.MILLISECONDS);

    String serviceName = null;
    Deployment deployment = null;

    if (lockAcquired) {

        logger.fine(getThreadIdentity() + "Lock acquired : " + pendingRequest.hashCode());
        logger.fine(getThreadIdentity() + "Executing a request to provision a new virtual machine");

        try {

            serviceName = createCloudService(deplyomentDesc.getAffinityGroup(), endTime);

            deplyomentDesc.setHostedServiceName(serviceName);
            deplyomentDesc.setDeploymentName(serviceName);

            deployment = requestBodyBuilder.buildDeployment(deplyomentDesc);

            String xmlRequest = MicrosoftAzureModelUtils.marshall(deployment, false);

            logger.fine(getThreadIdentity() + "Launching virtual machine : " + deplyomentDesc.getRoleName());

            ClientResponse response = doPost("/services/hostedservices/" + serviceName + "/deployments",
                    xmlRequest);
            String requestId = extractRequestId(response);
            waitForRequestToFinish(requestId, endTime);
            logger.fine(getThreadIdentity() + "About to release lock " + pendingRequest.hashCode());
            pendingRequest.unlock();
        } catch (final Exception e) {
            logger.fine(getThreadIdentity() + "A failure occured : about to release lock "
                    + pendingRequest.hashCode());
            if (serviceName != null) {
                try {
                    // delete the dedicated cloud service that was created for the virtual machine.
                    deleteCloudService(serviceName, endTime);
                } catch (final Exception e1) {
                    logger.warning("Failed deleting cloud service " + serviceName + " : " + e1.getMessage());
                    logger.finest(ExceptionUtils.getFullStackTrace(e1));
                }
            }
            pendingRequest.unlock();
            if (e instanceof MicrosoftAzureException) {
                throw (MicrosoftAzureException) e;
            }
            if (e instanceof TimeoutException) {
                throw (TimeoutException) e;
            }
            if (e instanceof InterruptedException) {
                throw (InterruptedException) e;
            }
            throw new MicrosoftAzureException(e);
        }
    } else {
        throw new TimeoutException(
                "Failed to acquire lock for deleteDeployment request after + " + lockTimeout + " milliseconds");
    }

    Deployment deploymentResponse = null;
    try {
        deploymentResponse = waitForDeploymentStatus("Running", serviceName, deployment.getDeploymentSlot(),
                endTime);

        deploymentResponse = waitForRoleInstanceStatus("ReadyRole", serviceName, deployment.getDeploymentSlot(),
                endTime);
    } catch (final Exception e) {
        logger.fine("Error while waiting for VM status : " + e.getMessage());
        // the VM was created but with a bad status
        deleteVirtualMachineByDeploymentName(serviceName, deployment.getName(), endTime);
        if (e instanceof MicrosoftAzureException) {
            throw (MicrosoftAzureException) e;
        }
        if (e instanceof TimeoutException) {
            throw (TimeoutException) e;
        }
        if (e instanceof InterruptedException) {
            throw (InterruptedException) e;
        }
        throw new MicrosoftAzureException(e);
    }

    RoleDetails roleAddressDetails = new RoleDetails();
    roleAddressDetails.setId(deploymentResponse.getPrivateId());
    roleAddressDetails
            .setPrivateIp(deploymentResponse.getRoleInstanceList().getRoleInstances().get(0).getIpAddress());
    ConfigurationSets configurationSets = deploymentResponse.getRoleList().getRoles().get(0)
            .getConfigurationSets();

    String publicIp = null;
    for (ConfigurationSet configurationSet : configurationSets) {
        if (configurationSet instanceof NetworkConfigurationSet) {
            NetworkConfigurationSet networkConfigurationSet = (NetworkConfigurationSet) configurationSet;
            publicIp = networkConfigurationSet.getInputEndpoints().getInputEndpoints().get(0).getvIp();
        }
    }
    roleAddressDetails.setPublicIp(publicIp);

    return roleAddressDetails;
}

From source file:com.jivesoftware.os.amza.service.AmzaService.java

@Override
public RingMember awaitLeader(PartitionName partitionName, long waitForLeaderElection) throws Exception {
    if (partitionName.isSystemPartition()) {
        throw new IllegalArgumentException("System partitions do not have leaders. " + partitionName);
    } else {/*from   w  w  w  . ja  v  a2  s .  co  m*/
        long endAfterTimestamp = System.currentTimeMillis() + waitForLeaderElection;
        do {
            try {
                Waterline leader = partitionStripeProvider.awaitLeader(partitionName, waitForLeaderElection);
                return (leader != null) ? RingMember.fromAquariumMember(leader.getMember()) : null;
            } catch (PartitionIsExpungedException e) {
                LOG.warn("Awaiting leader for expunged partition {}, we will compost and retry", partitionName);
                partitionComposter.compostPartitionIfNecessary(partitionName);
            }
        } while (System.currentTimeMillis() < endAfterTimestamp);
    }
    throw new TimeoutException("Timed out awaiting leader for " + partitionName);
}

From source file:org.apache.samza.processor.StreamProcessor.java

/**
 * Stops the {@link SamzaContainer}.//from  www  . ja  v a 2  s .c  om
 * @return true if {@link SamzaContainer} had shutdown within task.shutdown.ms. false otherwise.
 */
private boolean stopSamzaContainer() {
    boolean hasContainerShutdown = true;
    if (container != null) {
        try {
            container.shutdown();
            LOGGER.info("Waiting {} ms for the container: {} to shutdown.", taskShutdownMs, container);
            hasContainerShutdown = containerShutdownLatch.await(taskShutdownMs, TimeUnit.MILLISECONDS);
        } catch (InterruptedException e) {
            LOGGER.error("Exception occurred when shutting down the container: {}.", container, e);
            hasContainerShutdown = false;
            if (containerException != null) {
                containerException = e;
            }
        }
        LOGGER.info(String.format("Shutdown status of container: %s for stream processor: %s is: %b.",
                container, processorId, hasContainerShutdown));
    }

    // We want to propagate TimeoutException when container shutdown times out. It is possible that the timeout exception
    // we propagate to the application runner maybe overwritten by container failure cause in case of interleaved execution.
    // It is acceptable since container exception is much more useful compared to timeout exception.
    // We can infer from the logs about the fact that container shutdown timed out or not for additional inference.
    if (!hasContainerShutdown && containerException == null) {
        containerException = new TimeoutException(
                "Container shutdown timed out after " + taskShutdownMs + " ms.");
    }

    return hasContainerShutdown;
}

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

/**
 * Generic wait function.// w w w.  j  a  v a 2 s. c o m
 */
public static <T> T waitForState(Supplier<T> supplier, Predicate<T> predicate, long waitIterationSleepMillis,
        long waitIterationCount, Runnable cleanup, String timeoutMessage) throws Throwable {
    for (int i = 0; i < waitIterationCount; i++) {
        T t = supplier.get();
        if (predicate.test(t)) {
            return t;
        }
        Thread.sleep(waitIterationSleepMillis);
    }

    if (cleanup != null) {
        cleanup.run();
    }

    logger.warn(timeoutMessage);
    throw new TimeoutException(timeoutMessage);
}

From source file:org.cloudifysource.esc.driver.provisioning.openstack.OpenStackCloudifyDriver.java

@Override
public MachineDetails[] startManagementMachines(final ManagementProvisioningContext context,
        final long duration, final TimeUnit unit) throws TimeoutException, CloudProvisioningException {

    if (duration < 0) {
        throw new TimeoutException("Starting a new machine timed out");
    }/*  w ww . j  a v a2s. co m*/

    final long endTime = System.currentTimeMillis() + unit.toMillis(duration);

    logger.fine("DefaultCloudProvisioning: startMachine - management == " + management);

    // first check if management already exists
    final MachineDetails[] existingManagementServers = this.getExistingManagementServers();
    if (existingManagementServers.length > 0) {
        final String serverDescriptions = this.createExistingServersDescription(this.serverNamePrefix,
                existingManagementServers);
        throw new CloudProvisioningException(
                "Found existing servers matching group " + this.serverNamePrefix + ": " + serverDescriptions);
    }

    // Create management secgroups and rules
    this.initManagementSecurityGroups();

    // Create management networks
    if (networkHelper.useManagementNetwork()) {
        this.createManagementNetworkAndSubnets();
    }

    // launch the management machines
    publishEvent(EVENT_ATTEMPT_START_MGMT_VMS);
    final int numberOfManagementMachines = this.cloud.getProvider().getNumberOfManagementMachines();
    final MachineDetails[] createdMachines = this.doStartManagementMachines(endTime,
            numberOfManagementMachines);
    publishEvent(EVENT_MGMT_VMS_STARTED);
    return createdMachines;
}