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

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

Introduction

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

Prototype

public static String getRootCauseMessage(final Throwable th) 

Source Link

Document

Gets a short message summarising the root cause exception.

Usage

From source file:com.holonplatform.auth.jwt.internal.DefaultJwtAuthenticator.java

@SuppressWarnings("unchecked")
@Override/* w ww .ja v a2s . c o  m*/
public Authentication authenticate(BearerAuthenticationToken authenticationToken)
        throws AuthenticationException {

    // check configuration
    if (getConfiguration() == null) {
        throw new UnexpectedAuthenticationException(
                "JWT authenticator not correctly configured: missing JWTConfiguration");
    }

    // validate
    if (authenticationToken == null) {
        throw new UnexpectedAuthenticationException("Null authentication token");
    }

    // Get JWT token
    String jwt = (String) authenticationToken.getCredentials();
    if (jwt == null) {
        throw new UnexpectedAuthenticationException("Missing JWT token");
    }

    // decode and get claims

    Claims claims = null;

    try {

        JwtParser parser = Jwts.parser();

        if (getConfiguration().getSignatureAlgorithm() != JwtSignatureAlgorithm.NONE) {
            // Token expected to be signed (JWS)
            if (getConfiguration().getSignatureAlgorithm().isSymmetric()) {
                parser = parser.setSigningKey(getConfiguration().getSharedKey()
                        .orElseThrow(() -> new UnexpectedAuthenticationException(
                                "JWT authenticator not correctly configured: missing shared key for symmetric signature algorithm ["
                                        + getConfiguration().getSignatureAlgorithm().getDescription()
                                        + "] - JWT configuration: [" + getConfiguration() + "]")));
            } else {
                parser = parser.setSigningKey(getConfiguration().getPublicKey()
                        .orElseThrow(() -> new UnexpectedAuthenticationException(
                                "JWT authenticator not correctly configured: missing public key for asymmetric signature algorithm ["
                                        + getConfiguration().getSignatureAlgorithm().getDescription()
                                        + "] - JWT configuration: [" + getConfiguration() + "]")));
            }
            claims = parser.parseClaimsJws(jwt).getBody();
        } else {
            // not signed (JWT)
            claims = parser.parseClaimsJwt(jwt).getBody();
        }

    } catch (@SuppressWarnings("unused") ExpiredJwtException eje) {
        throw new ExpiredCredentialsException("Expired JWT token");
    } catch (@SuppressWarnings("unused") MalformedJwtException | UnsupportedJwtException mje) {
        throw new InvalidTokenException("Malformed or unsupported JWT token");
    } catch (@SuppressWarnings("unused") SignatureException sje) {
        throw new InvalidTokenException("Invalid JWT token signature");
    } catch (Exception e) {
        throw new UnexpectedAuthenticationException(ExceptionUtils.getRootCauseMessage(e), e);
    }

    // check claims
    if (claims == null) {
        throw new UnexpectedAuthenticationException("No valid claims found in JWT token");
    }

    String principalName = claims.getSubject();
    if (principalName == null) {
        throw new UnknownAccountException("No principal id (subject) found in JWT token");
    }

    // check required claims
    Collection<String> required = getRequiredClaims();
    if (required != null && !required.isEmpty()) {
        for (String claim : required) {
            Object value = claims.get(claim);
            if (value == null) {
                throw new InvalidTokenException("Missing required JWT claim: " + claim);
            }
        }
    }

    // check issuer

    Collection<String> issuers = getIssuers();
    if (issuers != null && !issuers.isEmpty()) {
        String tokenIssuer = claims.getIssuer();
        if (tokenIssuer == null) {
            throw new InvalidTokenException("Missing required JWT Issuer");
        }

        if (!issuers.contains(tokenIssuer)) {
            throw new InvalidTokenException("JWT Issuer mismatch");
        }
    }

    // build Authentication

    Authentication.Builder auth = Authentication.builder(principalName).scheme("Bearer").root(false);

    // set claims as details
    claims.forEach((n, v) -> {
        if (AuthenticationClaims.CLAIM_NAME_PERMISSIONS.equals(n)) {
            Collection<String> permissions = (Collection<String>) v;
            if (permissions != null) {
                permissions.forEach(p -> auth.withPermission(Permission.create(p)));
            }
        } else {
            auth.withParameter(n, v);
        }
    });

    return auth.build();
}

From source file:br.com.modoagil.asr.rest.support.GenericWebService.java

/**
 * Atualiza o estado de um objeto persistido
 *
 * @param entity//from   w  w w  .j  a v a  2  s  .c  o m
 *            entidade a ser atualizada
 * @return {@link Response} resposta do processamento
 */
@ResponseBody
@RequestMapping(value = WebServicesURL.URL_UPDATE, method = PUT, consumes = APPLICATION_JSON, produces = APPLICATION_JSON)
public final Response<E> update(@Valid @RequestBody final E entity) {
    Response<E> response;
    this.getLogger().debug("atualizando objeto " + entity.toString());
    final E oldEntity = this.getRepository().findOne(entity.getId());
    if (oldEntity != null) {
        try {
            final E persistedEntity = this.getRepository().save(entity);
            this.afterUpdate(persistedEntity);
            response = new ResponseBuilder<E>().success(true).data(persistedEntity)
                    .message(String.format(ResponseMessages.UPDATE_MESSAGE, entity.getId()))
                    .status(HttpStatus.OK).build();
            this.getLogger().debug("objeto " + persistedEntity.toString() + " atualizado com sucesso");
        } catch (final Exception e) {
            final String message = ExceptionUtils.getRootCauseMessage(e);
            response = this.handlingCatchedExceptions(e, message);
            this.getLogger().error("problema ao atualizar objeto " + entity.toString() + ": " + message, e);
        }
    } else {
        response = new ResponseBuilder<E>().success(false).data(entity)
                .message(String.format(ResponseMessages.NOTFOUND_UPDATE_MESSAGE, entity.getId()))
                .status(HttpStatus.NOT_FOUND).build();
    }
    return response;
}

From source file:br.com.modoagil.asr.rest.support.GenericWebService.java

/**
 * Exclui um objeto persistido//from w w w  .j av a  2  s.  co  m
 *
 * @param id
 *            id da entidade a ser removida
 * @return {@link Response} resposta do processamento
 */
@ResponseBody
@RequestMapping(value = WebServicesURL.URL_DELETE, method = DELETE, produces = APPLICATION_JSON)
public final Response<E> delete(@PathVariable("id") final Long id) {
    Response<E> response;
    this.getLogger().debug("excluindo objeto de id " + id);
    final E entity = this.getRepository().findOne(id);
    if (entity != null) {
        try {
            this.beforeDelete(entity);
            this.getRepository().delete(entity);
            response = new ResponseBuilder<E>().success(true).data(entity)
                    .message(String.format(ResponseMessages.DELETE_MESSAGE, id)).status(HttpStatus.OK).build();
            this.getLogger().debug("objeto " + entity.toString() + " excluido com sucesso");
        } catch (final Exception e) {
            final String message = ExceptionUtils.getRootCauseMessage(e);
            response = new ResponseBuilder<E>().success(false).message(message).status(HttpStatus.BAD_REQUEST)
                    .build();
            this.getLogger().error("problema ao excluir objeto " + entity.toString() + ": " + message, e);
        }
    } else {
        response = new ResponseBuilder<E>().success(false)
                .message(String.format(ResponseMessages.NOTFOUND_DELETE_MESSAGE, id))
                .status(HttpStatus.NOT_FOUND).build();
    }
    return response;
}

From source file:org.apache.drill.exec.work.foreman.Foreman.java

/**
 * Tells the foreman to move to a new state.  Note that
 * @param state/*from  w w w. ja  v  a 2s  . c om*/
 * @return
 */
private synchronized boolean moveToState(QueryState newState, Exception exception) {
    logger.info("State change requested.  {} --> {}", state, newState, exception);
    outside: switch (state) {

    case PENDING:
        // since we're moving out of pending, we can now start accepting other changes in state.
        // This guarantees that the first state change is driven by the original thread.
        acceptExternalEvents.countDown();

        if (newState == QueryState.RUNNING) {
            recordNewState(QueryState.RUNNING);
            return true;
        }

        // fall through to running behavior.
        //
    case RUNNING: {

        switch (newState) {

        case CANCELED: {
            assert exception == null;
            recordNewState(QueryState.CANCELED);
            cancelExecutingFragments();
            QueryResult result = QueryResult.newBuilder() //
                    .setQueryId(queryId) //
                    .setQueryState(QueryState.CANCELED) //
                    .setIsLastChunk(true) //
                    .build();

            // immediately notify client that cancellation is taking place, final clean-up happens when foreman reaches to
            // a terminal state(completed, failed)
            initiatingClient.sendResult(responseListener, new QueryWritableBatch(result), true);
            return true;
        }

        case COMPLETED: {
            assert exception == null;
            recordNewState(QueryState.COMPLETED);
            QueryResult result = QueryResult //
                    .newBuilder() //
                    .setQueryState(QueryState.COMPLETED) //
                    .setQueryId(queryId) //
                    .build();
            cleanup(result);
            return true;
        }

        case FAILED:
            assert exception != null;
            recordNewState(QueryState.FAILED);
            cancelExecutingFragments();
            DrillPBError error = ErrorHelper.logAndConvertError(context.getCurrentEndpoint(),
                    ExceptionUtils.getRootCauseMessage(exception), exception, logger);
            QueryResult result = QueryResult //
                    .newBuilder() //
                    .addError(error) //
                    .setIsLastChunk(true) //
                    .setQueryState(QueryState.FAILED) //
                    .setQueryId(queryId) //
                    .build();
            cleanup(result);
            return true;
        default:
            break outside;

        }
    }

    case CANCELED:
    case COMPLETED:
    case FAILED: {
        // no op.
        logger.warn("Dropping request to move to {} state as query is already at {} state (which is terminal).",
                newState, state, exception);
        return false;
    }

    }

    throw new IllegalStateException(
            String.format("Failure trying to change states: %s --> %s", state.name(), newState.name()));
}

From source file:org.apache.metron.common.field.FieldNameConverters.java

/**
 * Create a new {@link FieldNameConverter}.
 *
 * @param sensorType The type of sensor.
 * @param config The writer configuration.
 * @return/*w  ww .  ja  v a2s .c om*/
 */
public static FieldNameConverter create(String sensorType, WriterConfiguration config) {
    FieldNameConverter result = null;

    // which field name converter has been configured?
    String converterName = config.getFieldNameConverter(sensorType);
    if (StringUtils.isNotBlank(converterName)) {
        try {
            result = FieldNameConverters.valueOf(converterName);

        } catch (IllegalArgumentException e) {
            LOG.error("Invalid field name converter, using default; configured={}, knownValues={}, error={}",
                    converterName, FieldNameConverters.values(), ExceptionUtils.getRootCauseMessage(e));
        }
    }

    if (result == null) {
        // if no converter defined or an invalid converter is defined, default to 'DEDOT'
        result = FieldNameConverters.DEDOT;
    }

    LOG.debug("Created field name converter; sensorType={}, configured={}, class={}", sensorType, converterName,
            ClassUtils.getShortClassName(result, "null"));

    return result;
}

From source file:org.apache.metron.elasticsearch.bulk.ElasticsearchBulkDocumentWriter.java

@Override
public BulkDocumentWriterResults<D> write() {
    BulkDocumentWriterResults<D> results = new BulkDocumentWriterResults<>();
    try {//ww  w  .j  a va2 s . com
        // create an index request for each document
        BulkRequest bulkRequest = new BulkRequest();
        bulkRequest.setRefreshPolicy(refreshPolicy);
        for (Indexable doc : documents) {
            DocWriteRequest request = createRequest(doc.document, doc.index);
            bulkRequest.add(request);
        }

        // submit the request and handle the response
        BulkResponse bulkResponse = client.getHighLevelClient().bulk(bulkRequest);
        handleBulkResponse(bulkResponse, documents, results);

    } catch (IOException e) {
        // assume all documents have failed
        for (Indexable indexable : documents) {
            D failed = indexable.document;
            results.addFailure(failed, e, ExceptionUtils.getRootCauseMessage(e));
        }
        LOG.error("Failed to submit bulk request; all documents failed", e);

    } finally {
        // flush all documents no matter which ones succeeded or failed
        documents.clear();
    }

    LOG.debug("Wrote document(s) to Elasticsearch; batchSize={}, success={}, failed={}", documents.size(),
            results.getSuccesses().size(), results.getFailures().size());
    return results;
}

From source file:org.apache.metron.elasticsearch.dao.ElasticsearchRequestSubmitter.java

/**
 * Submit a search to Elasticsearch.//  ww  w.  j a va  2s .co m
 * @param request A search request.
 * @return The search response.
 */
public SearchResponse submitSearch(SearchRequest request) throws InvalidSearchException {
    LOG.debug("About to submit a search; request={}", ElasticsearchUtils.toJSON(request).orElse("???"));

    // submit the search request
    org.elasticsearch.action.search.SearchResponse esResponse;
    try {
        esResponse = client.search(request).actionGet();
        LOG.debug("Got Elasticsearch response; response={}", esResponse.toString());

    } catch (SearchPhaseExecutionException e) {
        String msg = String.format("Failed to execute search; error='%s', search='%s'",
                ExceptionUtils.getRootCauseMessage(e), ElasticsearchUtils.toJSON(request).orElse("???"));
        LOG.error(msg, e);
        throw new InvalidSearchException(msg, e);
    }

    // check for shard failures
    if (esResponse.getFailedShards() > 0) {
        handleShardFailures(request, esResponse);
    }

    // validate the response status
    if (RestStatus.OK == esResponse.status()) {
        return esResponse;

    } else {
        // the search was not successful
        String msg = String.format("Bad search response; status=%s, timeout=%s, terminatedEarly=%s",
                esResponse.status(), esResponse.isTimedOut(), esResponse.isTerminatedEarly());
        LOG.error(msg);
        throw new InvalidSearchException(msg);
    }
}

From source file:org.apache.metron.elasticsearch.dao.ElasticsearchRequestSubmitter.java

/**
 * Handle individual shard failures that can occur even when the response is OK.  These
 * can indicate misconfiguration of the search indices.
 * @param request The search request.//from   w  ww. j a  va 2s  .  co m
 * @param response  The search response.
 */
private void handleShardFailures(org.elasticsearch.action.search.SearchRequest request,
        org.elasticsearch.action.search.SearchResponse response) {
    /*
     * shard failures are only logged.  the search itself is not failed.  this approach
     * assumes that a user is interested in partial search results, even if the
     * entire search result set cannot be produced.
     *
     * for example, assume the user adds an additional sensor and the telemetry
     * is indexed into a new search index.  if that search index is misconfigured,
     * it can result in partial shard failures.  rather than failing the entire search,
     * we log the error and allow the results to be returned from shards that
     * are correctly configured.
     */
    int errors = ArrayUtils.getLength(response.getShardFailures());
    LOG.error("Search resulted in {}/{} shards failing; errors={}, search={}", response.getFailedShards(),
            response.getTotalShards(), errors, ElasticsearchUtils.toJSON(request).orElse("???"));

    // log each reported failure
    int failureCount = 1;
    for (ShardSearchFailure fail : response.getShardFailures()) {
        String msg = String.format(
                "Shard search failure [%s/%s]; reason=%s, index=%s, shard=%s, status=%s, nodeId=%s",
                failureCount, errors, ExceptionUtils.getRootCauseMessage(fail.getCause()), fail.index(),
                fail.shardId(), fail.status(), fail.shard().getNodeId());
        LOG.error(msg, fail.getCause());
    }
}

From source file:org.apache.metron.rest.controller.RestExceptionHandler.java

@ExceptionHandler(RestException.class)
@ResponseBody/*from www  . jav a2 s  .  c o  m*/
ResponseEntity<?> handleControllerException(HttpServletRequest request, Throwable ex) {
    HttpStatus status = getStatus(request);
    LOG.error("Encountered error: " + ex.getMessage(), ex);
    return new ResponseEntity<>(
            new RestError(status.value(), ex.getMessage(), ExceptionUtils.getRootCauseMessage(ex)), status);
}

From source file:org.apache.metron.stellar.common.utils.StellarProcessorUtils.java

/**
 * Ensure a value can be serialized and deserialized using Java serialization.
 *
 * <p>When a Stellar function is used in a Storm topology there are cases when the result
 * needs to be serializable, like when using the Profiler.  Storm can use either Kryo or
 * basic Java serialization.  It is highly recommended that all Stellar functions return a
 * result that is Java serializable to allow for the broadest possible use of the function.
 *
 * @param value The value to serialize/*from  w  w  w.j av a 2 s .  c om*/
 */
private static void ensureJavaSerializable(Object value, String expression) {

    String msg = String.format("Expression result is not Java serializable. It is highly recommended for all "
            + "functions to return a result that is Java serializable to allow for their broadest possible use. "
            + "expr=%s, value=%s", expression, value);

    try {
        // serialize using java
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        ObjectOutputStream out = new ObjectOutputStream(bytes);
        out.writeObject(value);

        // the serialized bits
        byte[] raw = bytes.toByteArray();
        assertTrue(raw.length > 0);

        // deserialize using java
        ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(raw));
        Object actual = in.readObject();

        // ensure that the round-trip was successful
        assertEquals(msg, value, actual);

    } catch (IOException | ClassNotFoundException e) {

        String error = String.format(
                "Expression result is not Java serializable. It is highly recommended for all "
                        + "functions to return a result that is Java serializable to allow for their broadest possible use. "
                        + "expr=%s, value=%s, error=%s",
                expression, value, ExceptionUtils.getRootCauseMessage(e));
        fail(error);
    }
}