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.xpn.xwiki.internal.objects.classes.ExplicitlyAllowedValuesDBListQueryBuilder.java

@Override
public Query build(DBListClass dbListClass) throws QueryException {
    String statement = dbListClass.getSql();
    DocumentReference authorReference = dbListClass.getOwnerDocument().getAuthorReference();
    if (this.authorizationManager.hasAccess(Right.SCRIPT, authorReference, dbListClass.getReference())) {
        String namespace = this.entityReferenceSerializer.serialize(dbListClass.getDocumentReference());
        try {/*from  w w w . j  a v a 2s .  c o m*/
            statement = this.authorExecutor.call(() -> {
                return evaluateVelocityCode(dbListClass.getSql(), namespace);
            }, authorReference);
        } catch (Exception e) {
            this.logger.warn(
                    "Failed to evaluate the Velocity code from the query [{}]."
                            + " Root cause is [{}]. Continuing with the raw query.",
                    statement, ExceptionUtils.getRootCauseMessage(e));
        }
    }

    Query query = this.secureQueryManager.createQuery(statement, Query.HQL);
    query.setWiki(dbListClass.getOwnerDocument().getDocumentReference().getWikiReference().getName());
    return query;
}

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

/**
 * Lista todos os objetos contantes na base de dados
 *
 * @return {@link Response} resposta do processamento
 *//* w  ww .j a v  a2 s.co  m*/
@ResponseBody
@RequestMapping(value = WebServicesURL.URL_LIST, method = { GET, POST }, produces = APPLICATION_JSON)
public final Response<E> list() {
    Response<E> response;
    this.getLogger().debug("listando objetos");
    try {
        final List<E> dataList = this.getRepository().findAll();
        final Integer dataListSize = dataList.size();
        final String message = dataListSize > 0 ? String.format(ResponseMessages.LIST_MESSAGE, dataListSize)
                : ResponseMessages.NOTFOUND_LIST_MESSAGE;
        response = new ResponseBuilder<E>().success(true).data(dataList).message(message).status(HttpStatus.OK)
                .build();
        this.getLogger().debug(message);
    } 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("erro ao listar objetos " + message, e);
    }
    return response;
}

From source file:com.xpn.xwiki.internal.query.ConfiguredQueryExecutorProvider.java

/**
 * Switch the queryExecutor based on what main store is being used. This is called lazily because the XWikiContext
 * might not yet exist when this class is instantiated.
 *//*from   ww w.j a  v  a2  s . c  om*/
private void init() {
    final XWikiContext context;
    try {
        context = (XWikiContext) this.exec.getContext().getProperty("xwikicontext");
    } catch (NullPointerException e) {
        this.logger.warn("The QueryExecutor was called without an XWikiContext available. "
                + "This means the old core (and likely the storage engine) is probably "
                + "not yet initialized. The default QueryExecutor will be returned.", e);
        return;
    }

    final String storeName = context.getWiki().Param("xwiki.store.main.hint", "default");
    try {
        this.queryExecutor = this.manager.getInstance(QueryExecutor.class, storeName);
    } catch (ComponentLookupException e) {
        this.logger.warn(
                "Could not find a QueryExecutor with hint [{}] which is the hint for the storage engine, "
                        + "defined in your XWiki configuration under the [xwiki.store.main.hint] property. "
                        + "The default QueryExecutor will be used instead. Reason: [{}]",
                storeName, ExceptionUtils.getRootCauseMessage(e));
    }

    this.initialized = true;
}

From source file:co.cask.cdap.master.startup.MasterStartupTool.java

public boolean canStartMaster() {
    List<CheckRunner.Failure> failures = checkRunner.runChecks();
    if (!failures.isEmpty()) {
        for (CheckRunner.Failure failure : failures) {
            LOG.error("{} failed: {}", failure.getName(), failure.getException().getMessage());
            if (failure.getException().getCause() != null) {
                LOG.error("  Root cause: {}",
                        ExceptionUtils.getRootCauseMessage(failure.getException().getCause()));
            }/*  www . ja v  a2  s . c o m*/
        }
        LOG.error("Errors detected while starting up master. "
                + "Please check the logs, address all errors, then try again.");
        return false;
    }
    return true;
}

From source file:com.hpe.caf.worker.testing.ProcessorDeliveryHandler.java

private String buildFailedMessage(TestItem testItem, Throwable throwable) {
    StringBuilder sb = new StringBuilder();
    sb.append("Test case failed.");
    TestCaseInfo info = testItem.getTestCaseInformation();
    if (info != null) {
        sb.append(" Test case id: " + info.getTestCaseId());
        sb.append("\nTest case description: " + info.getDescription());
        sb.append("\nTest case comments: " + info.getComments());
        sb.append("\nTest case associated tickets: " + info.getAssociatedTickets());
        sb.append("\n");
    }/*from ww  w .ja  v a  2  s.co  m*/
    sb.append("Message: " + ExceptionUtils.getMessage(throwable));
    sb.append("\n");
    sb.append("Root cause message: " + ExceptionUtils.getRootCauseMessage(throwable));

    sb.append("\nStack trace:\n");
    sb.append(ExceptionUtils.getStackTrace(throwable));
    return sb.toString();
}

From source file:com.haulmont.cuba.web.widgets.CubaFileUpload.java

protected void setUploadingErrorHandler() {
    setErrorHandler(event -> {/*from   w ww .j  av a  2 s .co  m*/
        //noinspection ThrowableResultOfMethodCallIgnored
        Throwable ex = event.getThrowable();
        String rootCauseMessage = ExceptionUtils.getRootCauseMessage(ex);
        Logger log = LoggerFactory.getLogger(CubaFileUpload.class);
        if (StringUtils.contains(rootCauseMessage, "The multipart stream ended unexpectedly")
                || StringUtils.contains(rootCauseMessage, "Unexpected EOF read on the socket")) {
            log.warn("Unable to upload file, it seems upload canceled or network error occurred");
        } else {
            log.error("Unexpected error in CubaFileUpload", ex);
        }

        if (isUploading) {
            endUpload();
        }
    });
}

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

@Override
public Builder parseJwt(JwtConfiguration configuration, String jwt)
        throws InvalidJwtConfigurationException, AuthenticationException {

    ObjectUtils.argumentNotNull(configuration, "JwtConfiguration must be not null");
    ObjectUtils.argumentNotNull(jwt, "JWT token must be not null");

    // decode and get claims

    Claims claims = null;//w w w .  ja  v  a2  s. c o m

    try {

        JwtParser parser = Jwts.parser();

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

    // build Authentication

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

    // process claims
    claims.forEach((n, v) -> {
        if (AuthenticationClaims.CLAIM_NAME_PERMISSIONS.equals(n)) {
            if (configuration.isIncludePermissions()) {
                @SuppressWarnings("unchecked")
                Collection<String> permissions = (Collection<String>) v;
                if (permissions != null) {
                    permissions.forEach(p -> auth.withPermission(Permission.create(p)));
                }
            }
        } else {
            if (configuration.isIncludeDetails()) {
                auth.withParameter(n, v);
            }
        }
    });

    return auth;
}

From source file:com.cognifide.aet.worker.impl.CollectorDispatcherImpl.java

private String getCause(AETException e) {
    String cause = e.getMessage();
    if (StringUtils.isBlank(cause)) {
        cause = ExceptionUtils.getRootCauseMessage(e);
    }/*from  w w w  .j ava  2s  . c  om*/
    if (StringUtils.isBlank(cause)) {
        cause = ExceptionUtils.getStackTrace(e);
    }
    return cause;
}

From source file:com.xpn.xwiki.web.UploadAction.java

/**
 * {@inheritDoc}//from  w ww  .  j ava  2s .c  o  m
 * 
 * @see XWikiAction#action(XWikiContext)
 */
@Override
public boolean action(XWikiContext context) throws XWikiException {
    XWikiResponse response = context.getResponse();
    Object exception = context.get("exception");
    boolean ajax = ((Boolean) context.get("ajax")).booleanValue();
    // check Exception File upload is large
    if (exception != null) {
        if (exception instanceof XWikiException) {
            XWikiException exp = (XWikiException) exception;
            if (exp.getCode() == XWikiException.ERROR_XWIKI_APP_FILE_EXCEPTION_MAXSIZE) {
                response.setStatus(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE);
                ((VelocityContext) context.get("vcontext")).put("message",
                        "core.action.upload.failure.maxSize");
                context.put("message", "fileuploadislarge");
                return true;
            }
        }
    }

    // CSRF prevention
    if (!csrfTokenCheck(context)) {
        return false;
    }

    XWikiDocument doc = context.getDoc().clone();

    // The document is saved for each attachment in the group.
    FileUploadPlugin fileupload = (FileUploadPlugin) context.get("fileuploadplugin");
    Map<String, String> fileNames = new HashMap<String, String>();
    List<String> wrongFileNames = new ArrayList<String>();
    Map<String, String> failedFiles = new HashMap<String, String>();
    for (String fieldName : fileupload.getFileItemNames(context)) {
        try {
            if (fieldName.startsWith(FILE_FIELD_NAME)) {
                String fileName = getFileName(fieldName, fileupload, context);
                if (fileName != null) {
                    fileNames.put(fileName, fieldName);
                }
            }
        } catch (Exception ex) {
            wrongFileNames.add(fileupload.getFileName(fieldName, context));
        }
    }

    for (Entry<String, String> file : fileNames.entrySet()) {
        try {
            uploadAttachment(file.getValue(), file.getKey(), fileupload, doc, context);
        } catch (Exception ex) {
            LOGGER.warn("Saving uploaded file failed", ex);
            failedFiles.put(file.getKey(), ExceptionUtils.getRootCauseMessage(ex));
        }
    }

    LOGGER.debug("Found files to upload: " + fileNames);
    LOGGER.debug("Failed attachments: " + failedFiles);
    LOGGER.debug("Wrong attachment names: " + wrongFileNames);
    if (ajax) {
        try {
            response.getOutputStream().println("ok");
        } catch (IOException ex) {
            LOGGER.error("Unhandled exception writing output:", ex);
        }
        return false;
    }
    // Forward to the attachment page
    if (failedFiles.size() > 0 || wrongFileNames.size() > 0) {
        ((VelocityContext) context.get("vcontext")).put("message", "core.action.upload.failure");
        ((VelocityContext) context.get("vcontext")).put("failedFiles", failedFiles);
        ((VelocityContext) context.get("vcontext")).put("wrongFileNames", wrongFileNames);
        return true;
    }
    String redirect = fileupload.getFileItemAsString("xredirect", context);
    if (StringUtils.isEmpty(redirect)) {
        redirect = context.getDoc().getURL("attach", true, context);
    }
    sendRedirect(response, redirect);
    return false;
}

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

/**
 * Consulta objeto pelo id/* w ww .j  ava2 s . c  o  m*/
 *
 * @param id
 *            identificado do objeto a ser consultado
 * @return {@link Response} resposta do processamento
 */
@ResponseBody
@RequestMapping(value = WebServicesURL.URL_FIND, method = { GET, POST }, produces = APPLICATION_JSON)
public final Response<E> find(@PathVariable("id") final Long id) {
    Response<E> response;
    this.getLogger().debug("consultando objeto de id " + id);
    try {
        final E entity = this.getRepository().findOne(id);
        String message = String.format(ResponseMessages.FIND_MESSAGE, id);
        Boolean success = true;
        HttpStatus status = HttpStatus.OK;
        if (entity == null) {
            message = String.format(ResponseMessages.NOTFOUND_MESSAGE, id);
            success = false;
            status = HttpStatus.NOT_FOUND;
        }
        response = new ResponseBuilder<E>().success(success).data(entity).message(message).status(status)
                .build();
        this.getLogger().debug(message);
    } 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 consultar objeto: " + message, e);
    }
    return response;
}