Example usage for com.google.common.util.concurrent SimpleTimeLimiter callWithTimeout

List of usage examples for com.google.common.util.concurrent SimpleTimeLimiter callWithTimeout

Introduction

In this page you can find the example usage for com.google.common.util.concurrent SimpleTimeLimiter callWithTimeout.

Prototype

@Override
    public <T> T callWithTimeout(Callable<T> callable, long timeoutDuration, TimeUnit timeoutUnit,
            boolean amInterruptible) throws Exception 

Source Link

Usage

From source file:org.glukit.dexcom.sync.tasks.IsReceiverOnThisPortRunner.java

public boolean isReceiver(String portName) {
    ExecutorService executor = Executors.newSingleThreadExecutor();
    final SerialPort serialPort = new SerialPort(portName);
    try {//from  w  w w . ja v  a2 s.  c o  m

        SimpleTimeLimiter timeout = new SimpleTimeLimiter(executor);
        Boolean result = timeout.callWithTimeout(new Callable<Boolean>() {
            @Override
            public Boolean call() throws Exception {
                return isFirmware(serialPort);
            }
        }, 5, TimeUnit.SECONDS, true);

        return result;
    } catch (Exception e) {
        LOGGER.info("Receiver not running on this port since we had an exception while checking.", e);
        return false;
    } finally {
        executor.shutdown();
        if (serialPort.isOpened()) {
            try {
                LOGGER.debug(format("Closing port %s", serialPort.getPortName()));
                serialPort.closePort();
            } catch (SerialPortException e) {
                LOGGER.warn("Error closing port, ignoring.", e);
            }
        }
    }
}

From source file:net.i2cat.netconf.messageQueue.MessageQueue.java

/**
 * Wait for a new message with the id <code>messageId</code> to arrive in the queue.
 *
 * @param messageId a string identifying the message to consume.
 * @param timeout a long indicating the length of the timeout in milliseconds. If zero or less, no timeout.
 * @throws Exception an UncheckedTimeoutException if there is no message with <code>messageId</code> after waiting for the specified timeout.
 * @return//  w  w  w. jav  a  2  s. c om
 */
public RPCElement blockingConsumeById(String messageId, long timeout) throws Exception {

    final String messageIdFinal = messageId;
    Callable<RPCElement> consumeCaller = new Callable<RPCElement>() {
        public RPCElement call() throws Exception {
            RPCElement element;
            synchronized (queue) {
                while ((element = consumeById(messageIdFinal)) == null) {
                    try {
                        log.debug("Waiting (" + messageIdFinal + ")...");
                        queue.wait();
                    } catch (InterruptedException e) {
                        // Do nothing. It's probably a timeout.
                    }
                }
            }
            return element;
        }
    };

    if (timeout <= 0) {
        return consumeCaller.call();
    }

    SimpleTimeLimiter timeLimiter = new SimpleTimeLimiter();

    try {
        return timeLimiter.callWithTimeout(consumeCaller, timeout, TimeUnit.MILLISECONDS, true);
    } catch (UncheckedTimeoutException e) {
        log.debug("BlockingConsumeById(messageId=" + messageId + ") failed due to timeout.", e);
        throw e;
    } catch (Exception e) {
        log.debug("BlockingConsumeById(messageId=" + messageId + ") failed.", e);
        throw e;
    }
}

From source file:org.zanata.workflow.ClientWorkFlow.java

@SuppressFBWarnings(value = "GBU_GUAVA_BETA_CLASS_USAGE", justification = "field SimpleTimeLimiter")
public List<String> callWithTimeout(final File workingDirectory, String command) {
    log.info("=== about to call ===\n{}", command);
    if (!workingDirectory.isDirectory()) {
        throw new RuntimeException("working directory does not exist: " + workingDirectory);
    }/*from   w  ww  .  j  a  v  a 2 s.  c  o m*/
    final List<String> commands = Lists.newArrayList(Splitter.on(" ").split(command));
    SimpleTimeLimiter timeLimiter = new SimpleTimeLimiter();
    Callable<List<String>> work = () -> {
        Process process = ClientWorkFlow.invokeClient(workingDirectory, commands);
        process.waitFor();
        List<String> output = ClientWorkFlow.getOutput(process);
        logOutputLines(output);
        return output;
    };
    try {
        return timeLimiter.callWithTimeout(work, timeoutDuration, TimeUnit.SECONDS, true);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.apache.phoenix.tool.PhoenixCanaryTool.java

@Override
public int run(String[] args) throws Exception {

    try {//from  www .  j a  v  a  2  s . c om
        Namespace cArgs = parseArgs(args);
        if (cArgs == null) {
            LOG.error("Argument parsing failed.");
            throw new RuntimeException("Argument parsing failed");
        }

        final String hostName = cArgs.getString("hostname");
        final String port = cArgs.getString("port");
        final String timeout = cArgs.getString("timeout");
        final String conString = cArgs.getString("constring");
        final String testSchemaName = cArgs.getString("testschema");
        final String testTableName = cArgs.getString("testtable");
        final String logSinkClass = cArgs.getString("logsinkclass");

        TEST_TABLE_NAME = testTableName;
        TEST_SCHEMA_NAME = testSchemaName;
        FQ_TABLE_NAME = testSchemaName + "." + testTableName;

        // Check if at least one from host+port or con string is provided.
        if ((hostName == null || port == null) && conString == null) {
            throw new RuntimeException("Provide at least one from host+port or constring");
        }

        int timeoutVal = Integer.parseInt(timeout);

        // Dynamically load a class for sink
        sink = (Sink) ClassLoader.getSystemClassLoader().loadClass(logSinkClass).newInstance();

        long startTime = System.currentTimeMillis();

        String connectionURL = (conString != null) ? conString
                : "jdbc:phoenix:thin:serialization=PROTOBUF;url=" + hostName + ":" + port;

        appInfo.setTestName("appInfo");
        appInfo.setMiscellaneous(connectionURL);

        Properties connProps = new Properties();
        connProps.setProperty("phoenix.schema.mapSystemTablesToNamespace", "true");
        connProps.setProperty("phoenix.schema.isNamespaceMappingEnabled", "true");

        try {
            connection = DriverManager.getConnection(connectionURL, connProps);
        } catch (Exception e) {
            LOG.info("Namespace mapping cannot be set. Using default schema");
            USE_NAMESPACE = false;
            connection = DriverManager.getConnection(connectionURL);
            TEST_SCHEMA_NAME = null;
            FQ_TABLE_NAME = TEST_TABLE_NAME;
        }

        SimpleTimeLimiter limiter = new SimpleTimeLimiter();

        limiter.callWithTimeout(new Callable<Void>() {

            public Void call() {

                sink.clearResults();

                // Execute tests

                LOG.info("Starting PrepareTest");
                sink.updateResults(new PrepareTest().runTest(connection));

                if (USE_NAMESPACE) {
                    LOG.info("Starting CreateSchemaTest");
                    sink.updateResults(new CreateSchemaTest().runTest(connection));
                }

                LOG.info("Starting CreateTableTest");
                sink.updateResults(new CreateTableTest().runTest(connection));

                LOG.info("Starting UpsertTableTest");
                sink.updateResults(new UpsertTableTest().runTest(connection));

                LOG.info("Starting ReadTableTest");
                sink.updateResults(new ReadTableTest().runTest(connection));

                LOG.info("Starting DeleteTableTest");
                sink.updateResults(new DeleteTableTest().runTest(connection));

                if (USE_NAMESPACE) {
                    LOG.info("Starting DeleteSchemaTest");
                    sink.updateResults(new DeleteSchemaTest().runTest(connection));
                }
                return null;
            }
        }, timeoutVal, TimeUnit.SECONDS, true);

        long estimatedTime = System.currentTimeMillis() - startTime;

        appInfo.setExecutionTime(estimatedTime);
        appInfo.setSuccessful(true);

    } catch (Exception e) {
        LOG.error(Throwables.getStackTraceAsString(e));
        appInfo.setMessage(Throwables.getStackTraceAsString(e));
        appInfo.setSuccessful(false);

    } finally {
        sink.updateResults(appInfo);
        sink.publishResults();
        connection.close();
    }

    return 0;
}