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:com.sophia.charts.export.converter.ChartConverter.java

public String requestServer(String params)
        throws ChartConverterException, TimeoutException, NoSuchElementException, PoolException {
    Server server = null;/*from w w  w .  j  a  v a2 s . co m*/

    try {
        server = (Server) serverPool.borrowObject();
        String response = server.request(params);

        return response;
    } catch (SocketTimeoutException ste) {
        throw new TimeoutException(ste.getMessage());
    } catch (TimeoutException te) {
        throw new TimeoutException(te.getMessage());
    } catch (PoolException nse) {
        logger.error("POOL EXHAUSTED!!");
        throw new PoolException(nse.getMessage());
    } catch (Exception e) {
        logger.debug(e.getMessage());
        throw new ChartConverterException("Error converting SVG" + e.getMessage());
    } finally {
        try {
            serverPool.returnObject(server, true);
        } catch (Exception e) {
            logger.error("Exception while returning server to pool: " + e.getMessage());
        }
    }
}

From source file:org.apache.sentry.service.thrift.SentryServiceIntegrationBase.java

public static void startSentryService() throws Exception {
    server.start();//w w  w . j ava 2 s  . c o  m
    final long start = System.currentTimeMillis();
    while (!server.isRunning()) {
        Thread.sleep(1000);
        if (System.currentTimeMillis() - start > 60000L) {
            throw new TimeoutException("Server did not start after 60 seconds");
        }
    }
}

From source file:org.rifidi.edge.adapter.awid.awid2010.communication.AwidEndpoint.java

/**
 * Receive a message. This method blocks until the message is received or
 * until the given amount of time has expired.
 * /*from w  w w .j  a v a 2 s  . co m*/
 * @param timeout
 *            the time to wait for a response in milliseconds
 * @return The next message from the reader
 * @throws IOException
 * @throws TimeoutException
 *             if the timeout has expired while waiting.
 */
public ByteMessage receiveMessage(int timeout) throws IOException, TimeoutException {
    try {
        if (timeout <= 0) {
            logger.warn("Timeout is less than 0");
        }
        ByteMessage response = messageQueue.poll(timeout, TimeUnit.MILLISECONDS);
        if (response != null) {
            return response;
        } else
            throw new TimeoutException("Timed out while waiting for a response");
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        throw new IOException();
    }
}

From source file:org.uiautomation.ios.mobileSafari.DefaultMessageHandler.java

@Override
public JSONObject getResponse(int id) throws TimeoutException {
    long timeout = 5 * 1000;
    // TODO handle stop() in there
    long end = System.currentTimeMillis() + timeout;
    while (true) {

        if (System.currentTimeMillis() > end) {
            throw new TimeoutException("timeout waiting for a response for request id : " + id);
        }/*from  w ww  . j a v a2 s .co m*/
        try {
            Thread.sleep(10);
            for (JSONObject o : responses) {
                if (o.optInt("id") == id) {
                    // responses.remove(o);
                    return o;
                }
            }
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();

        }

    }
}

From source file:com.liferay.arquillian.DeployerServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {

    try {//from  w w  w  .ja va  2 s .  c  om
        InputStream bundleInputStream = getUploadedBundleInputStream(request);

        BundleContext bundleContext = _bundle.getBundleContext();

        Bundle newBundle = bundleContext.installBundle(_deployerServletInstallLocation, bundleInputStream);

        newBundle.start();

        Filter bundleContextFilter = bundleContext
                .createFilter("(&(objectClass=com.liferay.httpservice.internal.servlet."
                        + "BundleServletContext)(bundle.id=" + newBundle.getBundleId() + "))");

        ServiceTracker servletContextServiceTracker = new ServiceTracker(bundleContext, bundleContextFilter,
                null);

        servletContextServiceTracker.open();

        ServletContext servletContext = (ServletContext) servletContextServiceTracker
                .waitForService(_installTimeout);

        Servlet arquillianServletRunner = waitForServlet(servletContext, "ArquillianServletRunner",
                _installTimeout);

        if (arquillianServletRunner == null) {
            throw new TimeoutException(
                    "The arquillian servlet runner is taking more than " + _installTimeout + " to deploy");
        }

        response.setStatus(HttpServletResponse.SC_OK);
        response.setContentType(TEXT);
        response.setHeader(_contextPathHeader, servletContext.getContextPath());
    } catch (Exception e) {
        signalError(e, response);
    } finally {
        ServletOutputStream outputStream = response.getOutputStream();

        outputStream.flush();
    }
}

From source file:com.highcharts.export.converter.SVGConverter.java

public String requestServer(String params)
        throws SVGConverterException, TimeoutException, NoSuchElementException, PoolException {
    Server server = null;//  ww  w.  j a va 2 s . co  m

    try {
        server = (Server) serverPool.borrowObject();
        String response = server.request(params);

        return response;
    } catch (SocketTimeoutException ste) {
        logger.error(ste);
        throw new TimeoutException(ste.getMessage());
    } catch (TimeoutException te) {
        logger.error(te);
        throw new TimeoutException(te.getMessage());
    } catch (PoolException nse) {
        logger.error("POOL EXHAUSTED!!");
        throw new PoolException(nse.getMessage());
    } catch (Exception e) {
        logger.error(e);
        throw new SVGConverterException("Error converting SVG" + e.getMessage());
    } finally {
        try {
            serverPool.returnObject(server, true);
        } catch (Exception e) {
            logger.error("Exception while returning server to pool: " + e.getMessage());
        }
    }
}

From source file:com.highcharts.export.converter.SVGConverter.java

public String requestServer(String params)
        throws SVGConverterException, TimeoutException, NoSuchElementException, PoolException {
    Server server = null;// w w  w  .ja v a  2  s.  com

    try {
        server = (Server) serverPool.borrowObject();
        String response = server.request(params);

        return response;
    } catch (SocketTimeoutException ste) {
        logger.error(ste);
        throw new TimeoutException(ste.getMessage());
    } catch (TimeoutException te) {
        logger.error(te);
        throw new TimeoutException(te.getMessage());
    } catch (PoolException nse) {
        logger.error("POOL EXHAUSTED!!");
        throw new PoolException(nse.getMessage());
    } catch (Exception e) {
        logger.error(e);
        throw new SVGConverterException("Error converting SVG: " + e.getMessage());
    } finally {
        try {
            serverPool.returnObject(server, true);
        } catch (Exception e) {
            logger.error("Exception while returning server to pool: " + e.getMessage());
        }
    }
}

From source file:org.openspaces.grid.gsm.rebalancing.RebalancingUtils.java

static Collection<FutureStatelessProcessingUnitInstance> incrementNumberOfStatelessInstancesAsync(
        final ProcessingUnit pu, final GridServiceContainer[] containers, final Log logger, final long duration,
        final TimeUnit timeUnit) {

    if (pu.getMaxInstancesPerVM() != 1) {
        throw new IllegalArgumentException("Only one instance per VM is allowed");
    }/*from w  w  w .j  a  v  a  2s .  c o m*/

    List<GridServiceContainer> unusedContainers = getUnusedContainers(pu, containers);

    final Admin admin = pu.getAdmin();
    final Map<GridServiceContainer, FutureStatelessProcessingUnitInstance> futureInstances = new HashMap<GridServiceContainer, FutureStatelessProcessingUnitInstance>();

    final AtomicInteger targetNumberOfInstances = new AtomicInteger(pu.getNumberOfInstances());

    final long start = System.currentTimeMillis();
    final long end = start + timeUnit.toMillis(duration);

    for (GridServiceContainer container : unusedContainers) {
        final GridServiceContainer targetContainer = container;
        futureInstances.put(container, new FutureStatelessProcessingUnitInstance() {

            AtomicReference<Throwable> throwable = new AtomicReference<Throwable>();
            ProcessingUnitInstance newInstance;

            public boolean isTimedOut() {
                return System.currentTimeMillis() > end;
            }

            public boolean isDone() {

                end();

                return isTimedOut() || throwable.get() != null || newInstance != null;
            }

            public ProcessingUnitInstance get()
                    throws ExecutionException, IllegalStateException, TimeoutException {

                end();

                if (getException() != null) {
                    throw getException();
                }

                if (newInstance == null) {
                    if (isTimedOut()) {
                        throw new TimeoutException("Relocation timeout");
                    }
                    throw new IllegalStateException("Async operation is not done yet.");
                }

                return newInstance;
            }

            public Date getTimestamp() {
                return new Date(start);
            }

            public ExecutionException getException() {

                end();
                Throwable t = throwable.get();
                if (t != null) {
                    return new ExecutionException(t.getMessage(), t);
                }
                return null;
            }

            public GridServiceContainer getTargetContainer() {
                return targetContainer;
            }

            public ProcessingUnit getProcessingUnit() {
                return pu;
            }

            public String getFailureMessage() throws IllegalStateException {
                if (isTimedOut()) {
                    return "deployment timeout of processing unit " + pu.getName() + " on "
                            + gscToString(targetContainer);
                }

                if (getException() != null) {
                    return getException().getMessage();
                }

                throw new IllegalStateException("Relocation has not encountered any failure.");
            }

            private void end() {

                if (!targetContainer.isDiscovered()) {
                    throwable.set(new RemovedContainerProcessingUnitDeploymentException(pu, targetContainer));
                }

                else if (throwable.get() != null || newInstance != null) {
                    //do nothing. idempotent method
                }

                else {
                    incrementInstance();

                    ProcessingUnitInstance[] instances = targetContainer
                            .getProcessingUnitInstances(pu.getName());

                    if (instances.length > 0) {
                        newInstance = instances[0];
                    }
                }
            }

            private void incrementInstance() {
                final String uuid = "[incrementUid:" + UUID.randomUUID().toString() + "] ";
                int numberOfInstances = pu.getNumberOfInstances();
                int maxNumberOfInstances = getContainersOnMachines(pu).length;
                if (numberOfInstances < maxNumberOfInstances) {
                    if (targetNumberOfInstances.get() == numberOfInstances + 1) {
                        if (logger.isInfoEnabled()) {
                            logger.info("Waiting for pu.numberOfInstances to increment from "
                                    + numberOfInstances + " to " + targetNumberOfInstances.get() + ". "
                                    + "Number of relevant containers " + maxNumberOfInstances);
                        }
                    } else if (admin.getGridServiceManagers().getSize() > 1
                            && !((InternalProcessingUnit) pu).isBackupGsmInSync()) {
                        if (logger.isInfoEnabled()) {
                            logger.info("Waiting for backup gsm to sync with active gsm");
                        }
                    } else {
                        targetNumberOfInstances.set(numberOfInstances + 1);
                        if (logger.isInfoEnabled()) {
                            logger.info(uuid + " Planning to increment pu.numberOfInstances from "
                                    + numberOfInstances + " to " + targetNumberOfInstances.get() + ". "
                                    + "Number of relevant containers " + maxNumberOfInstances);
                        }
                        ((InternalAdmin) admin).scheduleAdminOperation(new Runnable() {
                            public void run() {
                                try {
                                    // this is an async operation 
                                    // pu.getNumberOfInstances() still shows the old value.
                                    pu.incrementInstance();
                                    if (logger.isInfoEnabled()) {
                                        logger.info(uuid + " pu.incrementInstance() called");
                                    }
                                } catch (AdminException e) {
                                    throwable.set(e);
                                } catch (Throwable e) {
                                    logger.error(uuid + " Unexpected Exception: " + e.getMessage(), e);
                                    throwable.set(e);
                                }
                            }
                        });
                    }
                }
            }
        });

    }

    return futureInstances.values();

}

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

/************
 * Returns the decrypted password./*from   ww w.  j  a  v  a  2 s .  co  m*/
 *
 * @param node
 *            the compute node.
 * @param context
 *            the compute context.
 * @param end
 *            the operation end time.
 * @param pemFile
 *            the private key file used to decrypt the password.
 * @return the decrypted password.
 * @throws InterruptedException .
 * @throws TimeoutException .
 * @throws CloudProvisioningException .
 */
public LoginCredentials getPassword(final NodeMetadata node, final ComputeServiceContext context,
        final long end, final File pemFile)
        throws InterruptedException, TimeoutException, CloudProvisioningException {
    final EC2Client api = (EC2Client) context.getProviderSpecificContext().getApi();
    final Location zone = node.getLocation();
    final Location region = zone.getParent();
    final String id = node.getId();

    String key;
    try {
        key = FileUtils.readFileToString(pemFile);
    } catch (final IOException e) {
        throw new CloudProvisioningException("Failed to read key file: " + pemFile, e);
    }

    final String amiId = id.split("/")[1];
    while (System.currentTimeMillis() < end) {
        logger.fine("Reading Windows password");

        final PasswordData passwordData = api.getWindowsServices().getPasswordDataInRegion(region.getId(),
                amiId);

        if (passwordData == null || passwordData.getPasswordData() == null
                || passwordData.getPasswordData().isEmpty()) {
            Thread.sleep(PASSWORD_POLLING_INTERVAL_MILLIS);
        } else {
            final String encryptedPassword = passwordData.getPasswordData();

            LoginCredentials credentials;
            try {
                credentials = decryptPasswordData(encryptedPassword, key);
            } catch (final NoSuchAlgorithmException e) {
                throw new CloudProvisioningException("Failed to decrypt windows password: " + e.getMessage(),
                        e);
            } catch (final CertificateException e) {
                throw new CloudProvisioningException("Failed to decrypt windows password: " + e.getMessage(),
                        e);
            } catch (final IOException e) {
                throw new CloudProvisioningException("Failed to decrypt windows password: " + e.getMessage(),
                        e);
            }
            return credentials;

        }
    }

    throw new TimeoutException("Failed to retrieve EC2 Windows password in the allocated time");

}