Example usage for java.util.concurrent TimeoutException getMessage

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

Introduction

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

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:org.apache.flink.test.recovery.ProcessFailureBatchRecoveryITCase.java

private void waitUntilNumTaskManagersAreRegistered(ActorRef jobManager, int numExpected, long maxDelay)
        throws Exception {
    final long deadline = System.currentTimeMillis() + maxDelay;
    while (true) {
        long remaining = deadline - System.currentTimeMillis();
        if (remaining <= 0) {
            fail("The TaskManagers did not register within the expected time (" + maxDelay + "msecs)");
        }/*from  w w  w .  j  a v a2 s . com*/

        FiniteDuration timeout = new FiniteDuration(remaining, TimeUnit.MILLISECONDS);

        try {
            Future<?> result = Patterns.ask(jobManager,
                    JobManagerMessages.getRequestNumberRegisteredTaskManager(), new Timeout(timeout));
            Integer numTMs = (Integer) Await.result(result, timeout);
            if (numTMs == numExpected) {
                break;
            }
        } catch (TimeoutException e) {
            // ignore and retry
        } catch (ClassCastException e) {
            fail("Wrong response: " + e.getMessage());
        }
    }
}

From source file:org.apache.hive.hcatalog.templeton.LauncherDelegator.java

public EnqueueBean enqueueController(final String user, final Map<String, Object> userArgs,
        final String callback, final List<String> args)
        throws NotAuthorizedException, BusyException, IOException, QueueException, TooManyRequestsException {

    EnqueueBean bean = null;/*from  w w w  .  ja v a2  s.c  o  m*/
    final TempletonControllerJob controllerJob = getTempletonController();

    if (jobRequest.isThreadPoolEnabled()) {
        JobCallable<EnqueueBean> jobExecuteCallable = getJobSubmitTask(user, userArgs, callback, args,
                controllerJob);
        try {
            bean = jobRequest.execute(jobExecuteCallable);
        } catch (TimeoutException ex) {
            /*
             * Job request got timed out. Job kill should have started. Return to client with
             * QueueException.
             */
            throw new QueueException(ex.getMessage());
        } catch (InterruptedException ex) {
            /*
             * Job request got interrupted. Job kill should have started. Return to client with
             * with QueueException.
             */
            throw new QueueException(ex.getMessage());
        } catch (ExecutionException ex) {
            /*
             * ExecutionException is raised if job execution gets an exception. Return to client
             * with the exception.
             */
            throw new QueueException(ex.getMessage());
        }
    } else {
        LOG.info("No thread pool configured for submit job request. Executing "
                + "the job request in current thread.");

        bean = enqueueJob(user, userArgs, callback, args, controllerJob);
    }

    return bean;
}

From source file:org.apache.tajo.querymaster.DefaultTaskScheduler.java

public void schedule() throws Exception {
    try {//from ww  w .j a  va2s  . com
        final int incompleteTaskNum = scheduledRequests.leafTaskNum() + scheduledRequests.nonLeafTaskNum();
        if (incompleteTaskNum == 0) {
            needWakeup.set(true);
            // all task is done or tasks is not scheduled
            synchronized (schedulingThread) {
                schedulingThread.wait(1000);
            }
        } else {
            LinkedList<TaskRequestEvent> taskRequests = createTaskRequest(incompleteTaskNum);

            if (taskRequests.size() == 0) {
                synchronized (schedulingThread) {
                    schedulingThread.wait(schedulerDelay);
                }
            } else {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Get " + taskRequests.size() + " taskRequestEvents ");
                }

                if (isLeaf) {
                    scheduledRequests.assignToLeafTasks(taskRequests);
                } else {
                    scheduledRequests.assignToNonLeafTasks(taskRequests);
                }
            }
        }
    } catch (TimeoutException e) {
        LOG.error(e.getMessage());
    }
}

From source file:org.apache.tinkerpop.gremlin.server.op.AbstractEvalOpProcessor.java

/**
 * A generalized implementation of the "eval" operation.  It handles script evaluation and iteration of results
 * so as to write {@link ResponseMessage} objects down the Netty pipeline.  It also handles script timeouts,
 * iteration timeouts, metrics and building bindings.  Note that result iteration is delegated to the
 * {@link #handleIterator} method, so those extending this class could override that method for better control
 * over result iteration./*from ww  w . ja v a2  s.  c  o m*/
 *
 * @param context The current Gremlin Server {@link Context}
 * @param gremlinExecutorSupplier A function that returns the {@link GremlinExecutor} to use in executing the
 *                                script evaluation.
 * @param bindingsSupplier A function that returns the {@link Bindings} to provide to the
 *                         {@link GremlinExecutor#eval} method.
 */
protected void evalOpInternal(final Context context, final Supplier<GremlinExecutor> gremlinExecutorSupplier,
        final BindingSupplier bindingsSupplier) throws OpProcessorException {
    final Timer.Context timerContext = evalOpTimer.time();
    final ChannelHandlerContext ctx = context.getChannelHandlerContext();
    final RequestMessage msg = context.getRequestMessage();
    final GremlinExecutor gremlinExecutor = gremlinExecutorSupplier.get();
    final Settings settings = context.getSettings();

    final Map<String, Object> args = msg.getArgs();

    final String script = (String) args.get(Tokens.ARGS_GREMLIN);
    final String language = args.containsKey(Tokens.ARGS_LANGUAGE) ? (String) args.get(Tokens.ARGS_LANGUAGE)
            : null;
    final Bindings bindings = new SimpleBindings();

    // sessionless requests are always transaction managed, but in-session requests are configurable.
    final boolean managedTransactionsForRequest = manageTransactions ? true
            : (Boolean) args.getOrDefault(Tokens.ARGS_MANAGE_TRANSACTION, false);

    final GremlinExecutor.LifeCycle lifeCycle = GremlinExecutor.LifeCycle.build().beforeEval(b -> {
        try {
            b.putAll(bindingsSupplier.get());
        } catch (OpProcessorException ope) {
            // this should bubble up in the GremlinExecutor properly as the RuntimeException will be
            // unwrapped and the root cause thrown
            throw new RuntimeException(ope);
        }
    }).withResult(o -> {
        final Iterator itty = IteratorUtils.asIterator(o);

        logger.debug("Preparing to iterate results from - {} - in thread [{}]", msg,
                Thread.currentThread().getName());

        try {
            handleIterator(context, itty);
        } catch (TimeoutException ex) {
            final String errorMessage = String.format(
                    "Response iteration exceeded the configured threshold for request [%s] - %s", msg,
                    ex.getMessage());
            logger.warn(errorMessage);
            ctx.writeAndFlush(ResponseMessage.build(msg).code(ResponseStatusCode.SERVER_ERROR_TIMEOUT)
                    .statusMessage(errorMessage).create());
            if (managedTransactionsForRequest)
                attemptRollback(msg, context.getGraphManager(), settings.strictTransactionManagement);
        } catch (Exception ex) {
            logger.warn(String.format("Exception processing a script on request [%s].", msg), ex);
            ctx.writeAndFlush(ResponseMessage.build(msg).code(ResponseStatusCode.SERVER_ERROR)
                    .statusMessage(ex.getMessage()).create());
            if (managedTransactionsForRequest)
                attemptRollback(msg, context.getGraphManager(), settings.strictTransactionManagement);
        }
    }).create();

    final CompletableFuture<Object> evalFuture = gremlinExecutor.eval(script, language, bindings, lifeCycle);

    evalFuture.handle((v, t) -> {
        timerContext.stop();

        if (t != null) {
            if (t instanceof OpProcessorException) {
                ctx.writeAndFlush(((OpProcessorException) t).getResponseMessage());
            } else if (t instanceof TimedInterruptTimeoutException) {
                // occurs when the TimedInterruptCustomizerProvider is in play
                final String errorMessage = String.format(
                        "A timeout occurred within the script during evaluation of [%s] - consider increasing the limit given to TimedInterruptCustomizerProvider",
                        msg);
                logger.warn(errorMessage);
                ctx.writeAndFlush(ResponseMessage.build(msg).code(ResponseStatusCode.SERVER_ERROR_TIMEOUT)
                        .statusMessage(
                                "Timeout during script evaluation triggered by TimedInterruptCustomizerProvider")
                        .create());
            } else if (t instanceof TimeoutException) {
                final String errorMessage = String.format(
                        "Response evaluation exceeded the configured threshold for request [%s] - %s", msg,
                        t.getMessage());
                logger.warn(errorMessage, t);
                ctx.writeAndFlush(ResponseMessage.build(msg).code(ResponseStatusCode.SERVER_ERROR_TIMEOUT)
                        .statusMessage(t.getMessage()).create());
            } else {
                logger.warn(String.format("Exception processing a script on request [%s].", msg), t);
                ctx.writeAndFlush(
                        ResponseMessage.build(msg).code(ResponseStatusCode.SERVER_ERROR_SCRIPT_EVALUATION)
                                .statusMessage(t.getMessage()).create());
            }
        }

        return null;
    });
}

From source file:org.apache.tinkerpop.gremlin.server.op.traversal.TraversalOpProcessor.java

private void gatherSideEffect(final Context context) throws OpProcessorException {
    final RequestMessage msg = context.getRequestMessage();
    logger.debug("Side-effect request {} for in thread {}", msg.getRequestId(),
            Thread.currentThread().getName());

    // earlier validation in selection of this op method should free us to cast this without worry
    final Optional<UUID> sideEffect = msg.optionalArgs(Tokens.ARGS_SIDE_EFFECT);
    final Optional<String> sideEffectKey = msg.optionalArgs(Tokens.ARGS_SIDE_EFFECT_KEY);
    final Map<String, String> aliases = (Map<String, String>) msg.optionalArgs(Tokens.ARGS_ALIASES).get();

    final GraphManager graphManager = context.getGraphManager();
    final String traversalSourceName = aliases.entrySet().iterator().next().getValue();
    final TraversalSource g = graphManager.getTraversalSource(traversalSourceName);

    final Timer.Context timerContext = traversalOpTimer.time();
    try {/*from   w  ww. java2s .  c  om*/
        final ChannelHandlerContext ctx = context.getChannelHandlerContext();
        final Graph graph = g.getGraph();

        context.getGremlinExecutor().getExecutorService().submit(() -> {
            try {
                beforeProcessing(graph, context);

                try {
                    final TraversalSideEffects sideEffects = cache.getIfPresent(sideEffect.get());

                    if (null == sideEffects) {
                        final String errorMessage = String.format("Could not find side-effects for %s.",
                                sideEffect.get());
                        logger.warn(errorMessage);
                        ctx.writeAndFlush(ResponseMessage.build(msg).code(ResponseStatusCode.SERVER_ERROR)
                                .statusMessage(errorMessage).create());
                        onError(graph, context);
                        return;
                    }

                    if (!sideEffects.exists(sideEffectKey.get())) {
                        final String errorMessage = String.format(
                                "Could not find side-effect key for %s in %s.", sideEffectKey.get(),
                                sideEffect.get());
                        logger.warn(errorMessage);
                        ctx.writeAndFlush(ResponseMessage.build(msg).code(ResponseStatusCode.SERVER_ERROR)
                                .statusMessage(errorMessage).create());
                        onError(graph, context);
                        return;
                    }

                    handleIterator(context,
                            new SideEffectIterator(sideEffects.get(sideEffectKey.get()), sideEffectKey.get()));
                } catch (TimeoutException ex) {
                    final String errorMessage = String.format(
                            "Response iteration exceeded the configured threshold for request [%s] - %s",
                            msg.getRequestId(), ex.getMessage());
                    logger.warn(errorMessage);
                    ctx.writeAndFlush(ResponseMessage.build(msg).code(ResponseStatusCode.SERVER_ERROR_TIMEOUT)
                            .statusMessage(errorMessage).statusAttributeException(ex).create());
                    onError(graph, context);
                    return;
                } catch (Exception ex) {
                    logger.warn(
                            String.format("Exception processing a side-effect on iteration for request [%s].",
                                    msg.getRequestId()),
                            ex);
                    ctx.writeAndFlush(ResponseMessage.build(msg).code(ResponseStatusCode.SERVER_ERROR)
                            .statusMessage(ex.getMessage()).statusAttributeException(ex).create());
                    onError(graph, context);
                    return;
                }

                onSideEffectSuccess(graph, context);
            } catch (Exception ex) {
                logger.warn(String.format("Exception processing a side-effect on request [%s].",
                        msg.getRequestId()), ex);
                ctx.writeAndFlush(ResponseMessage.build(msg).code(ResponseStatusCode.SERVER_ERROR)
                        .statusMessage(ex.getMessage()).statusAttributeException(ex).create());
                onError(graph, context);
            } finally {
                timerContext.stop();
            }
        });

    } catch (Exception ex) {
        timerContext.stop();
        throw new OpProcessorException("Could not iterate the side-effect instance",
                ResponseMessage.build(msg).code(ResponseStatusCode.SERVER_ERROR).statusMessage(ex.getMessage())
                        .statusAttributeException(ex).create());
    }
}

From source file:org.cloudifysource.dsl.download.ResourceDownloaderTest.java

@Test
public void testTimeout() {
    // Try doGet with very short timeout.
    try {/*w  w  w.  ja v a 2  s. co m*/
        rdf.get(RESOURCE_URL, RESOURCE_DESTINATION, false, 1, TimeUnit.MICROSECONDS);
        Assert.fail("Expected timeout exception.");
    } catch (TimeoutException e) {
        // test passed.
    } catch (ResourceDownloadException e) {
        Assert.fail("Expecting timeout exception. got " + e.getMessage());
    }
}

From source file:org.rhq.core.pc.inventory.ResourceContainerTest.java

public void testInterruptedComponentInvocationContext() throws Exception {
    ResourceContainer resourceContainer = getResourceContainer();
    OperationFacet proxy = resourceContainer.createResourceComponentProxy(OperationFacet.class,
            FacetLockType.WRITE, SECONDS.toMillis(1L), true, false, true);
    try {//from ww  w .ja v  a 2s . co  m
        proxy.invokeOperation("op", new Configuration());
        fail("Expected invokeOperation to throw a TimeoutException");
    } catch (TimeoutException e) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Caught expected TimeoutException: " + e.getMessage());
        }
        MockResourceComponent component = (MockResourceComponent) resourceContainer.getResourceComponent();
        for (int i = 0; i < 5 && !component.caughtInterruptedComponentInvocation(); i++) {
            Thread.sleep(SECONDS.toMillis(2));
        }
        assertTrue(component.caughtInterruptedComponentInvocation());
    }
}

From source file:org.rifidi.edge.adapter.llrp.LLRPReaderSession.java

public String sendLLRPMessage(Document xmlMessage, boolean sendonly) {
    try {//from   w  w w .  ja v a  2  s  . c  o m
        LLRPMessage message = LLRPMessageFactory.createLLRPMessage(xmlMessage);
        LLRPMessage response = null;
        try {
            if (!sendonly) {
                response = this.transact(message);
                return response.toXMLString();
            } else {
                this.send(message);
                return null;
            }
        } catch (TimeoutException e) {
            return e.getMessage();
        }
    } catch (Exception e) {
        return e.getMessage();
    }
}