Example usage for org.apache.commons.lang3.exception ExceptionUtils getRootCause

List of usage examples for org.apache.commons.lang3.exception ExceptionUtils getRootCause

Introduction

In this page you can find the example usage for org.apache.commons.lang3.exception ExceptionUtils getRootCause.

Prototype

public static Throwable getRootCause(final Throwable throwable) 

Source Link

Document

Introspects the Throwable to obtain the root cause.

This method walks through the exception chain to the last element, "root" of the tree, using #getCause(Throwable) , and returns that exception.

From version 2.2, this method handles recursive cause structures that might otherwise cause infinite loops.

Usage

From source file:org.apache.sling.commons.messaging.mail.internal.SimpleMailServiceIT.java

@Test
public void sendWithoutAuthentication() throws Exception {
    final Dictionary<String, Object> properties = MailBuilderConfigurations.minimal();
    createFactoryConfiguration(FACTORY_PID, properties);
    final MessageService messageService = getService(MessageService.class);
    final CompletableFuture<Result> future = messageService.send("simple test message",
            "recipient@example.net");
    try {/*from  w w  w. ja v a  2s.  c  o  m*/
        future.get();
    } catch (Exception e) {
        logger.info(e.getMessage(), e);
        assertTrue(ExceptionUtils.getRootCause(e) instanceof AuthenticationFailedException);
    }
}

From source file:org.apache.solr.cloud.autoscaling.ExecutePlanAction.java

static CollectionAdminRequest.RequestStatusResponse waitForTaskToFinish(SolrCloudManager dataProvider,
        String requestId, long duration, TimeUnit timeUnit) throws IOException, InterruptedException {
    long timeoutSeconds = timeUnit.toSeconds(duration);
    RequestStatusState state = RequestStatusState.NOT_FOUND;
    CollectionAdminRequest.RequestStatusResponse statusResponse = null;
    for (int i = 0; i < timeoutSeconds; i++) {
        try {//from  www .  java 2 s  . co m
            statusResponse = (CollectionAdminRequest.RequestStatusResponse) dataProvider
                    .request(CollectionAdminRequest.requestStatus(requestId));
            state = statusResponse.getRequestStatus();
            if (state == RequestStatusState.COMPLETED || state == RequestStatusState.FAILED) {
                log.info("Task with requestId={} finished with state={} in {}s", requestId, state, i * 5);
                dataProvider.request(CollectionAdminRequest.deleteAsyncId(requestId));
                return statusResponse;
            } else if (state == RequestStatusState.NOT_FOUND) {
                // the request for this id was never actually submitted! no harm done, just bail out
                log.warn("Task with requestId={} was not found on overseer", requestId);
                dataProvider.request(CollectionAdminRequest.deleteAsyncId(requestId));
                return statusResponse;
            }
        } catch (Exception e) {
            Throwable rootCause = ExceptionUtils.getRootCause(e);
            if (rootCause instanceof IllegalStateException
                    && rootCause.getMessage().contains("Connection pool shut down")) {
                throw e;
            }
            if (rootCause instanceof TimeoutException
                    && rootCause.getMessage().contains("Could not connect to ZooKeeper")) {
                throw e;
            }
            if (rootCause instanceof SolrServerException) {
                throw e;
            }
            log.error("Unexpected Exception while querying status of requestId=" + requestId, e);
        }
        if (i > 0 && i % 5 == 0) {
            log.debug("Task with requestId={} still not complete after {}s. Last state={}", requestId, i * 5,
                    state);
        }
        TimeUnit.SECONDS.sleep(5);
    }
    log.debug("Task with requestId={} did not complete within 5 minutes. Last state={}", requestId, state);
    return statusResponse;
}

From source file:org.apache.solr.cloud.autoscaling.ScheduledTriggers.java

private void waitForPendingTasks(AutoScaling.Trigger newTrigger, List<TriggerAction> actions)
        throws AlreadyClosedException {
    DistribStateManager stateManager = dataProvider.getDistribStateManager();
    try {/*www  .j a  v  a 2 s.c o m*/

        for (TriggerAction action : actions) {
            if (action instanceof ExecutePlanAction) {
                String parentPath = ZkStateReader.SOLR_AUTOSCALING_TRIGGER_STATE_PATH + "/"
                        + newTrigger.getName() + "/" + action.getName();
                if (!stateManager.hasData(parentPath)) {
                    break;
                }
                List<String> children = stateManager.listData(parentPath);
                if (children != null) {
                    for (String child : children) {
                        String path = parentPath + '/' + child;
                        VersionedData data = stateManager.getData(path, null);
                        if (data != null) {
                            Map map = (Map) Utils.fromJSON(data.getData());
                            String requestid = (String) map.get("requestid");
                            try {
                                log.debug("Found pending task with requestid={}", requestid);
                                RequestStatusResponse statusResponse = waitForTaskToFinish(dataProvider,
                                        requestid, ExecutePlanAction.DEFAULT_TASK_TIMEOUT_SECONDS,
                                        TimeUnit.SECONDS);
                                if (statusResponse != null) {
                                    RequestStatusState state = statusResponse.getRequestStatus();
                                    if (state == RequestStatusState.COMPLETED
                                            || state == RequestStatusState.FAILED
                                            || state == RequestStatusState.NOT_FOUND) {
                                        stateManager.removeData(path, -1);
                                    }
                                }
                            } catch (Exception e) {
                                if (dataProvider.isClosed()) {
                                    throw e; // propagate the abort to the caller
                                }
                                Throwable rootCause = ExceptionUtils.getRootCause(e);
                                if (rootCause instanceof IllegalStateException
                                        && rootCause.getMessage().contains("Connection pool shut down")) {
                                    throw e;
                                }
                                if (rootCause instanceof TimeoutException
                                        && rootCause.getMessage().contains("Could not connect to ZooKeeper")) {
                                    throw e;
                                }
                                log.error("Unexpected exception while waiting for pending task with requestid: "
                                        + requestid + " to finish", e);
                            }
                        }
                    }
                }
            }
        }
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, "Thread interrupted", e);
    } catch (Exception e) {
        if (dataProvider.isClosed()) {
            throw new AlreadyClosedException("The Solr instance has been shutdown");
        }
        // we catch but don't rethrow because a failure to wait for pending tasks
        // should not keep the actions from executing
        log.error("Unexpected exception while waiting for pending tasks to finish", e);
    }
}

From source file:org.apache.syncope.core.rest.cxf.RestServiceExceptionMapper.java

@Override
public Response toResponse(final Exception ex) {
    LOG.error("Exception thrown", ex);

    ResponseBuilder builder;/*from   w  w w.  j a v  a  2s .co  m*/

    if (ex instanceof AccessDeniedException) {
        // leaves the default exception processing to Spring Security
        builder = null;
    } else if (ex instanceof SyncopeClientException) {
        SyncopeClientException sce = (SyncopeClientException) ex;
        builder = sce.isComposite() ? getSyncopeClientCompositeExceptionResponse(sce.asComposite())
                : getSyncopeClientExceptionResponse(sce);
    } else if (ex instanceof DelegatedAdministrationException
            || ExceptionUtils.getRootCause(ex) instanceof DelegatedAdministrationException) {

        builder = builder(ClientExceptionType.DelegatedAdministration, ExceptionUtils.getRootCauseMessage(ex));
    } else if (ex instanceof EntityExistsException || ex instanceof DuplicateException
            || ex instanceof PersistenceException && ex.getCause() instanceof EntityExistsException) {

        builder = builder(ClientExceptionType.EntityExists,
                getJPAMessage(ex instanceof PersistenceException ? ex.getCause() : ex));
    } else if (ex instanceof DataIntegrityViolationException || ex instanceof JpaSystemException) {
        builder = builder(ClientExceptionType.DataIntegrityViolation, getJPAMessage(ex));
    } else if (ex instanceof ConnectorException) {
        builder = builder(ClientExceptionType.ConnectorException, ExceptionUtils.getRootCauseMessage(ex));
    } else if (ex instanceof NotFoundException) {
        builder = builder(ClientExceptionType.NotFound, ExceptionUtils.getRootCauseMessage(ex));
    } else {
        builder = processInvalidEntityExceptions(ex);
        if (builder == null) {
            builder = processBadRequestExceptions(ex);
        }
        // process JAX-RS validation errors
        if (builder == null && ex instanceof ValidationException) {
            builder = builder(validationEM.toResponse((ValidationException) ex))
                    .header(RESTHeaders.ERROR_CODE, ClientExceptionType.RESTValidation.name())
                    .header(RESTHeaders.ERROR_INFO, ClientExceptionType.RESTValidation
                            .getInfoHeaderValue(ExceptionUtils.getRootCauseMessage(ex)));

            ErrorTO error = new ErrorTO();
            error.setStatus(ClientExceptionType.RESTValidation.getResponseStatus().getStatusCode());
            error.setType(ClientExceptionType.RESTValidation);
            error.getElements().add(ExceptionUtils.getRootCauseMessage(ex));

            builder.entity(error);
        }
        // ...or just report as InternalServerError
        if (builder == null) {
            builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR).header(RESTHeaders.ERROR_INFO,
                    ClientExceptionType.Unknown.getInfoHeaderValue(ExceptionUtils.getRootCauseMessage(ex)));

            ErrorTO error = new ErrorTO();
            error.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
            error.setType(ClientExceptionType.Unknown);
            error.getElements().add(ExceptionUtils.getRootCauseMessage(ex));

            builder.entity(error);
        }
    }

    return builder == null ? null : builder.build();
}

From source file:org.apache.syncope.core.rest.cxf.RestServiceExceptionMapper.java

private String getJPAMessage(final Throwable ex) {
    Throwable throwable = ExceptionUtils.getRootCause(ex);
    String message = null;//w  w w  .  j  av a 2  s .com
    if (throwable instanceof SQLException) {
        String messageKey = EXCEPTION_CODE_MAP.get(((SQLException) throwable).getSQLState());
        if (messageKey != null) {
            message = env.getProperty("errMessage." + messageKey);
        }
    }

    return message == null ? (ex.getCause() == null) ? ex.getMessage() : ex.getCause().getMessage() : message;
}

From source file:org.apache.syncope.ext.scimv2.cxf.SCIMExceptionMapper.java

@Override
public Response toResponse(final Exception ex) {
    LOG.error("Exception thrown", ex);

    ResponseBuilder builder;/* w w  w .  ja v  a 2 s  . c  o  m*/

    if (ex instanceof AccessDeniedException || ex instanceof ForbiddenException
            || ex instanceof NotAuthorizedException) {

        // leaves the default exception processing
        builder = null;
    } else if (ex instanceof NotFoundException) {
        return Response
                .status(Response.Status.NOT_FOUND).entity(new SCIMError(null,
                        Response.Status.NOT_FOUND.getStatusCode(), ExceptionUtils.getRootCauseMessage(ex)))
                .build();
    } else if (ex instanceof SyncopeClientException) {
        SyncopeClientException sce = (SyncopeClientException) ex;
        builder = builder(sce.getType(), ExceptionUtils.getRootCauseMessage(ex));
    } else if (ex instanceof DelegatedAdministrationException
            || ExceptionUtils.getRootCause(ex) instanceof DelegatedAdministrationException) {

        builder = builder(ClientExceptionType.DelegatedAdministration, ExceptionUtils.getRootCauseMessage(ex));
    } else if (ENTITYEXISTS_EXCLASS.isAssignableFrom(ex.getClass()) || ex instanceof DuplicateException
            || PERSISTENCE_EXCLASS.isAssignableFrom(ex.getClass())
                    && ENTITYEXISTS_EXCLASS.isAssignableFrom(ex.getCause().getClass())) {

        builder = builder(ClientExceptionType.EntityExists, ExceptionUtils.getRootCauseMessage(ex));
    } else if (ex instanceof DataIntegrityViolationException
            || JPASYSTEM_EXCLASS.isAssignableFrom(ex.getClass())) {
        builder = builder(ClientExceptionType.DataIntegrityViolation, ExceptionUtils.getRootCauseMessage(ex));
    } else if (CONNECTOR_EXCLASS.isAssignableFrom(ex.getClass())) {
        builder = builder(ClientExceptionType.ConnectorException, ExceptionUtils.getRootCauseMessage(ex));
    } else {
        builder = processInvalidEntityExceptions(ex);
        if (builder == null) {
            builder = processBadRequestExceptions(ex);
        }
        // process JAX-RS validation errors
        if (builder == null && ex instanceof ValidationException) {
            builder = builder(ClientExceptionType.RESTValidation, ExceptionUtils.getRootCauseMessage(ex));
        }
        // ...or just report as InternalServerError
        if (builder == null) {
            builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR)
                    .entity(ExceptionUtils.getRootCauseMessage(ex));
        }
    }

    return builder == null ? null : builder.build();
}

From source file:org.apache.tinkerpop.gremlin.server.handler.HttpGremlinEndpointHandler.java

@Override
public void channelRead(final ChannelHandlerContext ctx, final Object msg) {
    if (msg instanceof FullHttpRequest) {
        final FullHttpRequest req = (FullHttpRequest) msg;

        if ("/favicon.ico".equals(req.getUri())) {
            sendError(ctx, NOT_FOUND, "Gremlin Server doesn't have a favicon.ico");
            ReferenceCountUtil.release(msg);
            return;
        }/*w  w w.  j a v  a 2  s .  co m*/

        if (is100ContinueExpected(req)) {
            ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE));
        }

        if (req.getMethod() != GET && req.getMethod() != POST) {
            sendError(ctx, METHOD_NOT_ALLOWED, METHOD_NOT_ALLOWED.toString());
            ReferenceCountUtil.release(msg);
            return;
        }

        final Quartet<String, Map<String, Object>, String, Map<String, String>> requestArguments;
        try {
            requestArguments = getRequestArguments(req);
        } catch (IllegalArgumentException iae) {
            sendError(ctx, BAD_REQUEST, iae.getMessage());
            ReferenceCountUtil.release(msg);
            return;
        }

        final String acceptString = Optional.ofNullable(req.headers().get("Accept")).orElse("application/json");
        final Pair<String, MessageTextSerializer> serializer = chooseSerializer(acceptString);
        if (null == serializer) {
            sendError(ctx, BAD_REQUEST,
                    String.format("no serializer for requested Accept header: %s", acceptString));
            ReferenceCountUtil.release(msg);
            return;
        }

        final String origin = req.headers().get(ORIGIN);
        final boolean keepAlive = isKeepAlive(req);

        // not using the req any where below here - assume it is safe to release at this point.
        ReferenceCountUtil.release(msg);

        try {
            logger.debug("Processing request containing script [{}] and bindings of [{}] on {}",
                    requestArguments.getValue0(), requestArguments.getValue1(),
                    Thread.currentThread().getName());
            final ChannelPromise promise = ctx.channel().newPromise();
            final AtomicReference<Object> resultHolder = new AtomicReference<>();
            promise.addListener(future -> {
                // if failed then the error was already written back to the client as part of the eval future
                // processing of the exception
                if (future.isSuccess()) {
                    logger.debug(
                            "Preparing HTTP response for request with script [{}] and bindings of [{}] with result of [{}] on [{}]",
                            requestArguments.getValue0(), requestArguments.getValue1(), resultHolder.get(),
                            Thread.currentThread().getName());
                    final FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK,
                            (ByteBuf) resultHolder.get());
                    response.headers().set(CONTENT_TYPE, serializer.getValue0());
                    response.headers().set(CONTENT_LENGTH, response.content().readableBytes());

                    // handle cors business
                    if (origin != null)
                        response.headers().set(ACCESS_CONTROL_ALLOW_ORIGIN, origin);

                    if (!keepAlive) {
                        ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
                    } else {
                        response.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
                        ctx.writeAndFlush(response);
                    }
                }
            });

            final Timer.Context timerContext = evalOpTimer.time();

            final Bindings bindings;
            try {
                bindings = createBindings(requestArguments.getValue1(), requestArguments.getValue3());
            } catch (IllegalStateException iae) {
                sendError(ctx, BAD_REQUEST, iae.getMessage());
                ReferenceCountUtil.release(msg);
                return;
            }

            // provide a transform function to serialize to message - this will force serialization to occur
            // in the same thread as the eval. after the CompletableFuture is returned from the eval the result
            // is ready to be written as a ByteBuf directly to the response.  nothing should be blocking here.
            final CompletableFuture<Object> evalFuture = gremlinExecutor.eval(requestArguments.getValue0(),
                    requestArguments.getValue2(), bindings, FunctionUtils.wrapFunction(o -> {
                        // stopping the timer here is roughly equivalent to where the timer would have been stopped for
                        // this metric in other contexts.  we just want to measure eval time not serialization time.
                        timerContext.stop();

                        logger.debug(
                                "Transforming result of request with script [{}] and bindings of [{}] with result of [{}] on [{}]",
                                requestArguments.getValue0(), requestArguments.getValue1(), o,
                                Thread.currentThread().getName());
                        final ResponseMessage responseMessage = ResponseMessage.build(UUID.randomUUID())
                                .code(ResponseStatusCode.SUCCESS).result(IteratorUtils.asList(o)).create();

                        // http server is sessionless and must handle commit on transactions. the commit occurs
                        // before serialization to be consistent with how things work for websocket based
                        // communication.  this means that failed serialization does not mean that you won't get
                        // a commit to the database
                        attemptCommit(requestArguments.getValue3(), graphManager,
                                settings.strictTransactionManagement);

                        try {
                            return Unpooled.wrappedBuffer(serializer.getValue1()
                                    .serializeResponseAsString(responseMessage).getBytes(UTF8));
                        } catch (Exception ex) {
                            logger.warn(String.format("Error during serialization for %s", responseMessage),
                                    ex);
                            throw ex;
                        }
                    }));

            evalFuture.exceptionally(t -> {
                sendError(ctx, INTERNAL_SERVER_ERROR,
                        String.format("Error encountered evaluating script: %s", requestArguments.getValue0()),
                        Optional.of(t));
                promise.setFailure(t);
                return null;
            });

            evalFuture.thenAcceptAsync(r -> {
                // now that the eval/serialization is done in the same thread - complete the promise so we can
                // write back the HTTP response on the same thread as the original request
                resultHolder.set(r);
                promise.setSuccess();
            }, gremlinExecutor.getExecutorService());
        } catch (Exception ex) {
            // tossed to exceptionCaught which delegates to sendError method
            final Throwable t = ExceptionUtils.getRootCause(ex);
            throw new RuntimeException(null == t ? ex : t);
        }
    }
}

From source file:org.ballerinalang.swagger.cmd.SwaggerCmd.java

private void generateFromSwagger(String targetLanguage) {
    CodeGenerator generator = new CodeGenerator();
    generator.setApiPackage(apiPackage);

    try {//ww  w .j  a v a2 s.  co  m
        generator.generate(GenType.valueOf(targetLanguage), argList.get(1), output);
    } catch (Exception e) {
        String causeMessage = "";
        Throwable rootCause = ExceptionUtils.getRootCause(e);

        if (rootCause != null) {
            causeMessage = rootCause.getMessage();
        }
        throw LauncherUtils.createUsageException("Error occurred when generating " + targetLanguage + " for "
                + "swagger file at " + argList.get(1) + ". " + e.getMessage() + ". " + causeMessage);
    }
}

From source file:org.ballerinalang.swagger.code.generator.cmd.SwaggerCmd.java

private void generateFromSwagger(String targetLanguage) {
    Generate generate = new Generate();
    generate.setSpec(argList.get(1)); //set swagger specification
    generate.setLang(targetLanguage);//from ww w  . j av  a 2 s  .  c  om
    generate.setOutput(output);
    generate.setApiPackage(apiPackage);
    try {
        generate.run();
    } catch (Exception e) {
        String causeMessage = "";
        Throwable rootCause = ExceptionUtils.getRootCause(e);
        if (rootCause != null) {
            causeMessage = rootCause.getMessage();
        }
        throw LauncherUtils.createUsageException("Error occurred when generating " + targetLanguage + " for "
                + "swagger file at " + argList.get(1) + ". " + e.getMessage() + ". " + causeMessage);
    }
}

From source file:org.craftercms.commons.validation.rest.ValidationAwareRestExceptionHandlers.java

@Override
protected ResponseEntity<Object> handleHttpMessageNotReadable(HttpMessageNotReadableException ex,
        HttpHeaders headers, HttpStatus status, WebRequest webRequest) {
    Throwable cause = ExceptionUtils.getRootCause(ex);
    if (cause instanceof UnrecognizedPropertyException) {
        UnrecognizedPropertyException upe = (UnrecognizedPropertyException) cause;
        String field = upe.getPropertyName();

        ValidationResult result = new ValidationResult();
        result.addError(field,// ww  w. j  a va  2  s  .  co m
                ValidationUtils.getErrorMessage(errorMessageBundle, FIELD_UNRECOGNIZED_ERROR_CODE));

        return handleExceptionInternal(ex, result, new HttpHeaders(), HttpStatus.BAD_REQUEST, webRequest);
    } else {
        String message = ValidationUtils.getErrorMessage(errorMessageBundle, INVALID_REQUEST_BODY_ERROR_CODE);

        return handleExceptionInternal(ex, message, new HttpHeaders(), HttpStatus.BAD_REQUEST, webRequest);
    }
}