List of usage examples for org.apache.commons.lang3.exception ExceptionUtils getRootCauseMessage
public static String getRootCauseMessage(final Throwable th)
From source file:com.qwazr.server.ServerException.java
public static ServerException of(String message, final Throwable throwable) { if (throwable instanceof ServerException) return (ServerException) throwable; int status = 500; final int serverExceptionPos = ExceptionUtils.indexOfType(throwable, ServerException.class); if (serverExceptionPos != -1) return (ServerException) ExceptionUtils.getThrowableList(throwable).get(serverExceptionPos); final int webApplicationExceptionPos = ExceptionUtils.indexOfType(throwable, WebApplicationException.class); if (webApplicationExceptionPos != -1) status = ((WebApplicationException) ExceptionUtils.getThrowableList(throwable) .get(webApplicationExceptionPos)).getResponse().getStatus(); if (StringUtils.isBlank(message)) { message = throwable.getMessage(); if (StringUtils.isBlank(message)) message = ExceptionUtils.getRootCauseMessage(throwable); if (StringUtils.isBlank(message)) message = "Internal server error"; }/* ww w . j ava 2 s . c o m*/ return new ServerException(status, message, throwable); }
From source file:br.com.modoagil.asr.rest.AirSafetyReportWebService.java
/** * Busca por relatrios de preveno que possuam o local informado * * @param local/*from w ww .ja v a 2 s . c o m*/ * local a ser pesquisado nos relatrios de preveno * @return {@link Response} */ @ResponseBody @RequestMapping(value = WebServicesURL.URL_RELPREV_FIND_LOCAL + "/{local}", method = { GET, POST }, produces = APPLICATION_JSON) public Response<AirSafetyReport> findRelPrevByLocal(@PathVariable("local") final String local) { Response<AirSafetyReport> response; getLogger().debug("listando relatrios de preveno por local '" + local + "'"); try { final List<AirSafetyReport> dataList = getRepository().findByLocalIgnoreCase(local); response = new ResponseBuilder<AirSafetyReport>().success(true).data(dataList) .message(String.format(ResponseMessages.LIST_MESSAGE, dataList.size())).status(HttpStatus.OK) .build(); getLogger().debug("sucesso ao listar relatrios de preveno por local '" + local + "'"); } catch (final Exception e) { final String message = ExceptionUtils.getRootCauseMessage(e); response = new ResponseBuilder<AirSafetyReport>().success(false).message(message) .status(HttpStatus.BAD_REQUEST).build(); getLogger().error("erro ao listar relatrios de preveno por local '" + local + "'", e); } return response; }
From source file:com.xpn.xwiki.internal.store.hibernate.query.HqlQueryUtils.java
/** * @param statementString the SQL statement to check * @return true if the passed SQL statement is allowed *//*from ww w . j ava 2s.c o m*/ public static boolean isSafe(String statementString) { try { // TODO: should probably use a more specific Hql parser // FIXME: Workaround https://github.com/JSQLParser/JSqlParser/issues/163 (Support class syntax in HQL query) String cleanedStatement = statementString; cleanedStatement = FROM_DOC.matcher(cleanedStatement).replaceAll(FROM_REPLACEMENT); cleanedStatement = FROM_OBJECT.matcher(cleanedStatement).replaceAll(FROM_REPLACEMENT); cleanedStatement = FROM_RCS.matcher(cleanedStatement).replaceAll(FROM_REPLACEMENT); cleanedStatement = FROM_VERSION.matcher(cleanedStatement).replaceAll(FROM_REPLACEMENT); Statement statement = CCJSqlParserUtil.parse(cleanedStatement); if (statement instanceof Select) { Select select = (Select) statement; SelectBody selectBody = select.getSelectBody(); if (selectBody instanceof PlainSelect) { PlainSelect plainSelect = (PlainSelect) selectBody; Map<String, String> tables = getTables(plainSelect); for (SelectItem selectItem : plainSelect.getSelectItems()) { if (!isSelectItemAllowed(selectItem, tables)) { return false; } } return true; } } } catch (JSQLParserException e) { // We can't parse it so lets say it's not safe LOGGER.warn("Failed to parse request [{}] ([{}]). Considering it not safe.", statementString, ExceptionUtils.getRootCauseMessage(e)); } return false; }
From source file:gov.nih.nci.firebird.selenium2.pages.util.FirebirdTableUtils.java
public static <T extends TableListing> List<T> transformDataTableRows(final AbstractLoadableComponent<?> parent, WebElement table, Class<T> tableListingClass) { try {//from w w w .j a v a2 s. c o m final Constructor<T> constructor = getConstructor(parent, tableListingClass); Function<WebElement, T> transformation = new Function<WebElement, T>() { @Override public T apply(WebElement row) { try { if (constructor.getParameterTypes().length == 2) { return constructor.newInstance(parent, row); } else { return constructor.newInstance(row); } } catch (Exception e) { fail(ExceptionUtils.getRootCauseMessage(e)); } return null; } }; return JQueryUtils.transformDataTableRows(table, transformation); } catch (Exception e) { fail(ExceptionUtils.getRootCauseMessage(e)); } return null; }
From source file:br.com.modoagil.asr.rest.support.GenericWebService.java
/** * Persisti um objeto/*from w w w .j a v a 2s . c om*/ * * @param entity * objeto a ser persistido * @return {@link Response} resposta do processamento */ @ResponseBody @RequestMapping(value = WebServicesURL.URL_CREATE, method = POST, consumes = APPLICATION_JSON, produces = APPLICATION_JSON) public final Response<E> create(@Valid @RequestBody final E entity) { Response<E> response; this.getLogger().debug("criando objeto"); try { final E persistedEntity = this.getRepository().save(entity); this.afterCreate(persistedEntity); this.getLogger().debug("objeto " + persistedEntity.toString() + " criado com sucesso"); response = new ResponseBuilder<E>().success(true).data(persistedEntity) .message(ResponseMessages.CREATE_MESSAGE).status(HttpStatus.OK).build(); } catch (final Exception e) { final String message = ExceptionUtils.getRootCauseMessage(e); response = this.handlingCatchedExceptions(e, message); this.getLogger().error("problema ao criar objeto " + entity.toString() + ": " + message, e); } return response; }
From source file:com.xpn.xwiki.internal.pdf.FOPXSLFORenderer.java
private Configuration loadConfiguration() { Configuration configuration = null; try (InputStream fopConfigurationFile = FOPXSLFORenderer.class.getResourceAsStream("/fop-config.xml")) { if (fopConfigurationFile != null) { configuration = new DefaultConfigurationBuilder().build(fopConfigurationFile); }// w w w .j av a 2 s.c om } catch (Exception e) { this.logger.warn("Wrong FOP configuration: " + ExceptionUtils.getRootCauseMessage(e)); } configuration = maybeExtendConfiguration(configuration); return configuration; }
From source file:com.xpn.xwiki.internal.objects.classes.UsedValuesListQueryBuilder.java
private boolean canView(ListClass listClass, String value, long count) { // We can't check all the documents where this value occurs so we check just one of them, chosen randomly. long offset = ThreadLocalRandom.current().nextLong(count); String statement = String.format( "select obj.name from BaseObject as obj, %2$s " + "where obj.className = :className and obj.name <> :templateName " + "and prop.id.id = obj.id and prop.id.name = :propertyName and %1$s = :propertyValue", getSelectColumnAndFromTable(listClass)); try {//from ww w .j av a 2 s . c o m Query query = this.queryManager.createQuery(statement, Query.HQL); bindParameterValues(query, listClass); query.bindValue("propertyValue", value); query.setWiki(listClass.getReference().extractReference(EntityType.WIKI).getName()); query.setOffset((int) offset).setLimit(1); List<?> results = query.execute(); if (results.size() > 0) { DocumentReference documentReference = this.documentReferenceResolver .resolve((String) results.get(0)); if (this.authorization.hasAccess(Right.VIEW, documentReference)) { return true; } } } catch (QueryException e) { this.logger.warn( "Failed to check if the list value is viewable. Root cause is [{}]." + " Continue assuming the value is not viewable.", ExceptionUtils.getRootCauseMessage(e)); } return false; }
From source file:com.xpn.xwiki.web.DeleteAttachmentAction.java
/** * {@inheritDoc}/* w ww. j a va 2s . co m*/ * * @see com.xpn.xwiki.web.XWikiAction#action(com.xpn.xwiki.XWikiContext) */ @Override public boolean action(XWikiContext context) throws XWikiException { // CSRF prevention if (!csrfTokenCheck(context)) { return false; } XWikiRequest request = context.getRequest(); XWikiResponse response = context.getResponse(); XWikiDocument doc = context.getDoc(); XWikiAttachment attachment = null; XWiki xwiki = context.getWiki(); String filename; // Delete from the trash if (request.getParameter("trashId") != null) { long trashId = NumberUtils.toLong(request.getParameter("trashId")); DeletedAttachment da = xwiki.getAttachmentRecycleBinStore().getDeletedAttachment(trashId, context, true); // If the attachment hasn't been previously deleted (i.e. it's not in the deleted attachment store) then // don't try to delete it and instead redirect to the attachment list. if (da != null) { com.xpn.xwiki.api.DeletedAttachment daapi = new com.xpn.xwiki.api.DeletedAttachment(da, context); if (!daapi.canDelete()) { throw new XWikiException(XWikiException.MODULE_XWIKI_ACCESS, XWikiException.ERROR_XWIKI_ACCESS_DENIED, "You are not allowed to delete an attachment from the trash " + "immediately after it has been deleted from the wiki"); } if (!da.getDocName().equals(doc.getFullName())) { throw new XWikiException(XWikiException.MODULE_XWIKI_APP, XWikiException.ERROR_XWIKI_APP_URL_EXCEPTION, "The specified trash entry does not match the current document"); } // TODO: Add a confirmation check xwiki.getAttachmentRecycleBinStore().deleteFromRecycleBin(trashId, context, true); } sendRedirect(response, Utils.getRedirect("attach", context)); return false; } if (context.getMode() == XWikiContext.MODE_PORTLET) { filename = request.getParameter("filename"); } else { // Note: We use getRequestURI() because the spec says the server doesn't decode it, as // we want to use our own decoding. String requestUri = request.getRequestURI(); filename = Util.decodeURI(requestUri.substring(requestUri.lastIndexOf("/") + 1), context); } XWikiDocument newdoc = doc.clone(); // An attachment can be indicated either using an id, or using the filename. if (request.getParameter("id") != null) { int id = NumberUtils.toInt(request.getParameter("id")); if (newdoc.getAttachmentList().size() > id) { attachment = newdoc.getAttachmentList().get(id); } } else { attachment = newdoc.getAttachment(filename); } // No such attachment if (attachment == null) { response.setStatus(HttpServletResponse.SC_NOT_FOUND); VelocityContext vcontext = (VelocityContext) context.get("vcontext"); if (vcontext != null) { vcontext.put("message", context.getMessageTool().get("core.action.deleteAttachment.failed", filename)); vcontext.put("details", context.getMessageTool().get("platform.core.action.deleteAttachment.noAttachment")); } return true; } newdoc.setAuthor(context.getUser()); // Set "deleted attachment" as the version comment. ArrayList<String> params = new ArrayList<String>(); params.add(filename); if (attachment.isImage(context)) { newdoc.setComment(context.getMessageTool().get("core.comment.deleteImageComment", params)); } else { newdoc.setComment(context.getMessageTool().get("core.comment.deleteAttachmentComment", params)); } try { newdoc.deleteAttachment(attachment, context); // Needed to counter a side effect: the attachment is deleted from the newdoc.originalDoc as well newdoc.setOriginalDocument(doc); // Also save the document and attachment metadata context.getWiki().saveDocument(newdoc, context); } catch (Exception ex) { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); VelocityContext vcontext = (VelocityContext) context.get("vcontext"); if (vcontext != null) { vcontext.put("message", context.getMessageTool().get("core.action.deleteAttachment.failed", filename)); vcontext.put("details", ExceptionUtils.getRootCauseMessage(ex)); } return true; } // forward to attach page String redirect = Utils.getRedirect("attach", context); sendRedirect(response, redirect); return false; }
From source file:com.thinkbiganalytics.feedmgr.sla.ServiceLevelAgreementModelTransform.java
public static com.thinkbiganalytics.metadata.rest.model.sla.ServiceLevelAgreement toModel( ServiceLevelAgreement domain, boolean deep) { com.thinkbiganalytics.metadata.rest.model.sla.ServiceLevelAgreement sla = new com.thinkbiganalytics.metadata.rest.model.sla.ServiceLevelAgreement( domain.getId().toString(), domain.getName(), domain.getDescription()); if (domain.getSlaChecks() != null) { List<ServiceLevelAgreementCheck> checks = new ArrayList<>(); sla.setSlaChecks(checks);/*from w ww .java 2 s .co m*/ for (com.thinkbiganalytics.metadata.sla.spi.ServiceLevelAgreementCheck check : domain.getSlaChecks()) { ServiceLevelAgreementCheck restModel = new ServiceLevelAgreementCheck(); restModel.setCronSchedule(check.getCronSchedule()); if (deep) { try { restModel.setActionConfigurations(check.getActionConfigurations()); } catch (Exception e) { if (ExceptionUtils.getRootCause(e) instanceof ClassNotFoundException) { String msg = ExceptionUtils.getRootCauseMessage(e); //get just the simpleClassName stripping the package info msg = StringUtils.substringAfterLast(msg, "."); sla.addSlaCheckError("Unable to find the SLA Action Configurations of type: " + msg + ". Check with an administrator to ensure the correct plugin is installed with this SLA configuration. "); } else { throw new RuntimeException(e); } } } checks.add(restModel); } } if (deep) { if (domain.getObligationGroups().size() == 1 && domain.getObligationGroups().get(0).getCondition() == ObligationGroup.Condition.REQUIRED) { for (Obligation domainOb : domain.getObligations()) { com.thinkbiganalytics.metadata.rest.model.sla.Obligation ob = toModel(domainOb, true); sla.addObligation(ob); } } else { for (ObligationGroup domainGroup : domain.getObligationGroups()) { com.thinkbiganalytics.metadata.rest.model.sla.ObligationGroup group = new com.thinkbiganalytics.metadata.rest.model.sla.ObligationGroup( domainGroup.getCondition().toString()); for (Obligation domainOb : domainGroup.getObligations()) { com.thinkbiganalytics.metadata.rest.model.sla.Obligation ob = toModel(domainOb, true); group.addObligation(ob); } sla.addGroup(group); } } } return sla; }
From source file:br.com.modoagil.asr.rest.AirSafetyReportWebService.java
/** * Busca por relatrios de preveno que possuam a descrio informada * * @param descricao//www .j a v a 2 s. c o m * descrio a ser pesquisada nos relatrios de preveno * @return {@link Response} */ @ResponseBody @RequestMapping(value = WebServicesURL.URL_RELPREV_FIND_DESCRICAO + "/{descricao}", method = { GET, POST }, produces = APPLICATION_JSON) public Response<AirSafetyReport> findRelPrevByDescricao(@PathVariable("descricao") final String descricao) { Response<AirSafetyReport> response; getLogger().debug("listando relatrios de preveno por descrio '" + descricao + "'"); try { final List<AirSafetyReport> dataList = getRepository() .findByDescricaoSituacaoPerigosaContainsIgnoreCase(descricao); response = new ResponseBuilder<AirSafetyReport>().success(true).data(dataList) .message(String.format(ResponseMessages.LIST_MESSAGE, dataList.size())).status(HttpStatus.OK) .build(); getLogger().debug("sucesso ao listar relatrios de preveno por descrio '" + descricao + "'"); } catch (final Exception e) { final String message = ExceptionUtils.getRootCauseMessage(e); response = new ResponseBuilder<AirSafetyReport>().success(false).message(message) .status(HttpStatus.BAD_REQUEST).build(); getLogger().error("erro ao listar relatrios de preveno por descrio '" + descricao + "'", e); } return response; }