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.kie.server.remote.rest.jbpm.search.TaskSearchResource.java

@POST
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public Response getHumanTasksWithFilters(@Context HttpHeaders headers,
        @QueryParam("page") @DefaultValue("0") Integer page,
        @QueryParam("pageSize") @DefaultValue("10") Integer pageSize, String payload) {

    String type = getContentType(headers);
    // no container id available so only  used to transfer conversation id if given by client.
    Header conversationIdHeader = buildConversationIdHeader("", context, headers);
    try {/*from  ww  w .ja  va2  s .  co  m*/
        TaskInstanceList result = taskQueryServiceBase.getHumanTasksWithFilters(page, pageSize, payload, type);

        logger.debug("Returning result of task instance search: {}", result);

        return createCorrectVariant(result, headers, Response.Status.OK, conversationIdHeader);

    } catch (Exception e) {
        Throwable root = ExceptionUtils.getRootCause(e);
        if (root == null) {
            root = e;
        }
        if (HttpStatusCodeException.BAD_REQUEST.contains(root.getClass())
                || e instanceof DataSetLookupException) {

            logger.error("{}", MessageFormat.format(BAD_REQUEST, root.getMessage()), e);
            return badRequest(MessageFormat.format(BAD_REQUEST, root.getMessage()), getVariant(headers),
                    conversationIdHeader);
        } else {

            logger.error("{}", MessageFormat.format(UNEXPECTED_ERROR, e.getMessage()), e);
            return internalServerError(MessageFormat.format(UNEXPECTED_ERROR, e.getMessage()),
                    getVariant(headers), conversationIdHeader);
        }
    }
}

From source file:org.kie.server.services.jbpm.JbpmKieServerExtension.java

@SuppressWarnings("unchecked")
@Override//w  ww.j  av a 2s  . c o  m
public void createContainer(String id, KieContainerInstance kieContainerInstance,
        Map<String, Object> parameters) {
    List<Message> messages = (List<Message>) parameters.get(KieServerConstants.KIE_SERVER_PARAM_MESSAGES);
    try {
        KieModuleMetaData metaData = (KieModuleMetaData) parameters
                .get(KieServerConstants.KIE_SERVER_PARAM_MODULE_METADATA);
        if (metaData.getProcesses() == null || metaData.getProcesses().isEmpty()) {
            logger.info("Container {} does not include processes, {} skipped", id, this);
            return;
        }

        boolean hasStatefulSession = false;
        boolean hasDefaultSession = false;
        // let validate if they are any stateful sessions defined and in case there are not, skip this container
        InternalKieContainer kieContainer = (InternalKieContainer) kieContainerInstance.getKieContainer();
        Collection<String> kbaseNames = kieContainer.getKieBaseNames();
        Collection<String> ksessionNames = new ArrayList<String>();
        for (String kbaseName : kbaseNames) {
            ksessionNames = kieContainer.getKieSessionNamesInKieBase(kbaseName);

            for (String ksessionName : ksessionNames) {
                KieSessionModel model = kieContainer.getKieSessionModel(ksessionName);
                if (model.getType().equals(KieSessionModel.KieSessionType.STATEFUL)) {
                    hasStatefulSession = true;
                }

                if (model.isDefault()) {
                    hasDefaultSession = true;
                }
            }
        }
        if (!hasStatefulSession) {
            logger.info("Container {} does not define stateful ksession thus cannot be handled by extension {}",
                    id, this);
            return;
        }
        ReleaseId releaseId = kieContainerInstance.getKieContainer().getReleaseId();

        KModuleDeploymentUnit unit = new CustomIdKmoduleDeploymentUnit(id, releaseId.getGroupId(),
                releaseId.getArtifactId(), releaseId.getVersion());

        if (!hasDefaultSession) {
            unit.setKbaseName(kbaseNames.iterator().next());
            unit.setKsessionName(ksessionNames.iterator().next());
        }
        // override defaults if config options are given
        KieServerConfig config = new KieServerConfig(kieContainerInstance.getResource().getConfigItems());

        String runtimeStrategy = config.getConfigItemValue(KieServerConstants.PCFG_RUNTIME_STRATEGY);
        if (runtimeStrategy != null && !runtimeStrategy.isEmpty()) {
            unit.setStrategy(RuntimeStrategy.valueOf(runtimeStrategy));
        }
        String mergeMode = config.getConfigItemValue(KieServerConstants.PCFG_MERGE_MODE);
        if (mergeMode != null && !mergeMode.isEmpty()) {
            unit.setMergeMode(MergeMode.valueOf(mergeMode));
        }
        String ksession = config.getConfigItemValue(KieServerConstants.PCFG_KIE_SESSION);
        unit.setKsessionName(ksession);
        String kbase = config.getConfigItemValue(KieServerConstants.PCFG_KIE_BASE);
        unit.setKbaseName(kbase);

        // reuse kieContainer to avoid unneeded bootstrap
        unit.setKieContainer(kieContainer);

        addAsyncHandler(unit, kieContainer);

        if (System.getProperty(KieServerConstants.CFG_JBPM_TASK_CLEANUP_LISTENER, "true")
                .equalsIgnoreCase("true")) {
            logger.debug("Registering TaskCleanUpProcessEventListener");
            addTaskCleanUpProcessListener(unit, kieContainer);
        }

        if (System.getProperty(KieServerConstants.CFG_JBPM_TASK_BAM_LISTENER, "true")
                .equalsIgnoreCase("true")) {
            logger.debug("Registering BAMTaskEventListener");
            addTaskBAMEventListener(unit, kieContainer);
        }

        if (System.getProperty(KieServerConstants.CFG_JBPM_PROCESS_IDENTITY_LISTENER, "true")
                .equalsIgnoreCase("true")) {
            logger.debug("Registering IdentityProviderAwareProcessListener");
            addProcessIdentityProcessListener(unit, kieContainer);
        }

        deploymentService.deploy(unit);
        // in case it was deployed successfully pass all known classes to marshallers (jaxb, json etc)
        DeployedUnit deployedUnit = deploymentService.getDeployedUnit(unit.getIdentifier());
        Set<Class<?>> customClasses = new HashSet<Class<?>>(deployedUnit.getDeployedClasses());
        // add custom classes that come from extension itself
        customClasses.add(DocumentImpl.class);
        kieContainerInstance.addExtraClasses(customClasses);

        // add any query result mappers from kjar
        List<String> addedMappers = QueryMapperRegistry.get()
                .discoverAndAddMappers(kieContainer.getClassLoader());
        if (addedMappers != null && !addedMappers.isEmpty()) {
            containerMappers.put(id, addedMappers);
        }
        // add any query param builder factories
        QueryParamBuilderManager.get().discoverAndAddQueryFactories(id, kieContainer.getClassLoader());

        // add any query definition found in kjar
        Enumeration<URL> queryDefinitionsFiles = kieContainer.getClassLoader()
                .getResources("query-definitions.json");
        while (queryDefinitionsFiles.hasMoreElements()) {

            URL definitionsURL = queryDefinitionsFiles.nextElement();
            InputStream qdStream = definitionsURL.openStream();

            loadAndRegisterQueryDefinitions(qdStream,
                    kieContainerInstance.getMarshaller(MarshallingFormat.JSON), id);
        }

        logger.debug("Container {} created successfully by extension {}", id, this);
    } catch (Exception e) {
        Throwable root = ExceptionUtils.getRootCause(e);
        if (root == null) {
            root = e;
        }
        messages.add(new Message(Severity.ERROR, "Error when creating container " + id + " by extension " + this
                + " due to " + root.getMessage()));
        logger.error("Error when creating container {} by extension {}", id, this, e);
    }
}

From source file:org.languagetool.server.LanguageToolHttpHandler.java

@Override
public void handle(HttpExchange httpExchange) throws IOException {
    long startTime = System.currentTimeMillis();
    String remoteAddress = null;/*from  w  w w  . ja v  a2s. c  om*/
    Map<String, String> parameters = new HashMap<>();
    int reqId = reqCounter.incrementRequestCount();
    ServerMetricsCollector.getInstance().logRequest();
    boolean incrementHandleCount = false;
    try {
        URI requestedUri = httpExchange.getRequestURI();
        if (requestedUri.getRawPath().startsWith("/v2/")) {
            // healthcheck should come before other limit checks (requests per time etc.), to be sure it works: 
            String pathWithoutVersion = requestedUri.getRawPath().substring("/v2/".length());
            if (pathWithoutVersion.equals("healthcheck")) {
                if (workQueueFull(httpExchange, parameters,
                        "Healthcheck failed: There are currently too many parallel requests.")) {
                    ServerMetricsCollector.getInstance().logFailedHealthcheck();
                    return;
                } else {
                    String ok = "OK";
                    httpExchange.getResponseHeaders().set("Content-Type", "text/plain");
                    httpExchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, ok.getBytes(ENCODING).length);
                    httpExchange.getResponseBody().write(ok.getBytes(ENCODING));
                    ServerMetricsCollector.getInstance().logResponse(HttpURLConnection.HTTP_OK);
                    return;
                }
            }
        }
        String referrer = httpExchange.getRequestHeaders().getFirst("Referer");
        String origin = httpExchange.getRequestHeaders().getFirst("Origin"); // Referer can be turned off with meta tags, so also check this
        for (String ref : config.getBlockedReferrers()) {
            String errorMessage = null;
            if (ref != null && !ref.isEmpty()) {
                if (referrer != null && siteMatches(referrer, ref)) {
                    errorMessage = "Error: Access with referrer " + referrer + " denied.";
                } else if (origin != null && siteMatches(origin, ref)) {
                    errorMessage = "Error: Access with origin " + origin + " denied.";
                }
            }
            if (errorMessage != null) {
                sendError(httpExchange, HttpURLConnection.HTTP_FORBIDDEN, errorMessage);
                logError(errorMessage, HttpURLConnection.HTTP_FORBIDDEN, parameters, httpExchange);
                ServerMetricsCollector.getInstance().logResponse(HttpURLConnection.HTTP_FORBIDDEN);
                return;
            }
        }
        String origAddress = httpExchange.getRemoteAddress().getAddress().getHostAddress();
        String realAddressOrNull = getRealRemoteAddressOrNull(httpExchange);
        remoteAddress = realAddressOrNull != null ? realAddressOrNull : origAddress;
        reqCounter.incrementHandleCount(remoteAddress, reqId);
        incrementHandleCount = true;
        // According to the Javadoc, "Closing an exchange without consuming all of the request body is
        // not an error but may make the underlying TCP connection unusable for following exchanges.",
        // so we consume the request now, even before checking for request limits:
        parameters = getRequestQuery(httpExchange, requestedUri);
        if (requestLimiter != null) {
            try {
                requestLimiter.checkAccess(remoteAddress, parameters, httpExchange.getRequestHeaders());
            } catch (TooManyRequestsException e) {
                String errorMessage = "Error: Access from " + remoteAddress + " denied: " + e.getMessage();
                int code = HttpURLConnection.HTTP_FORBIDDEN;
                sendError(httpExchange, code, errorMessage);
                // already logged vai DatabaseAccessLimitLogEntry
                logError(errorMessage, code, parameters, httpExchange, false);
                return;
            }
        }
        if (errorRequestLimiter != null && !errorRequestLimiter.wouldAccessBeOkay(remoteAddress, parameters,
                httpExchange.getRequestHeaders())) {
            String textSizeMessage = getTextOrDataSizeMessage(parameters);
            String errorMessage = "Error: Access from " + remoteAddress + " denied - too many recent timeouts. "
                    + textSizeMessage + " Allowed maximum timeouts: " + errorRequestLimiter.getRequestLimit()
                    + " per " + errorRequestLimiter.getRequestLimitPeriodInSeconds() + " seconds";
            int code = HttpURLConnection.HTTP_FORBIDDEN;
            sendError(httpExchange, code, errorMessage);
            logError(errorMessage, code, parameters, httpExchange);
            return;
        }
        if (workQueueFull(httpExchange, parameters,
                "Error: There are currently too many parallel requests. Please try again later.")) {
            ServerMetricsCollector.getInstance()
                    .logRequestError(ServerMetricsCollector.RequestErrorType.QUEUE_FULL);
            return;
        }
        if (allowedIps == null || allowedIps.contains(origAddress)) {
            if (requestedUri.getRawPath().startsWith("/v2/")) {
                ApiV2 apiV2 = new ApiV2(textCheckerV2, config.getAllowOriginUrl());
                String pathWithoutVersion = requestedUri.getRawPath().substring("/v2/".length());
                apiV2.handleRequest(pathWithoutVersion, httpExchange, parameters, errorRequestLimiter,
                        remoteAddress, config);
            } else if (requestedUri.getRawPath().endsWith("/Languages")) {
                throw new IllegalArgumentException(
                        "You're using an old version of our API that's not supported anymore. Please see https://languagetool.org/http-api/migration.php");
            } else if (requestedUri.getRawPath().equals("/")) {
                throw new IllegalArgumentException(
                        "Missing arguments for LanguageTool API. Please see " + API_DOC_URL);
            } else if (requestedUri.getRawPath().contains("/v2/")) {
                throw new IllegalArgumentException(
                        "You have '/v2/' in your path, but not at the root. Try an URL like 'http://server/v2/...' ");
            } else if (requestedUri.getRawPath().equals("/favicon.ico")) {
                sendError(httpExchange, HttpURLConnection.HTTP_NOT_FOUND, "Not found");
            } else {
                throw new IllegalArgumentException(
                        "This is the LanguageTool API. You have not specified any parameters. Please see "
                                + API_DOC_URL);
            }
        } else {
            String errorMessage = "Error: Access from " + StringTools.escapeXML(origAddress) + " denied";
            sendError(httpExchange, HttpURLConnection.HTTP_FORBIDDEN, errorMessage);
            throw new RuntimeException(errorMessage);
        }
    } catch (Exception e) {
        String response;
        int errorCode;
        boolean textLoggingAllowed = false;
        boolean logStacktrace = true;
        Throwable rootCause = ExceptionUtils.getRootCause(e);
        if (e instanceof TextTooLongException || rootCause instanceof TextTooLongException) {
            errorCode = HttpURLConnection.HTTP_ENTITY_TOO_LARGE;
            response = e.getMessage();
            logStacktrace = false;
        } else if (e instanceof ErrorRateTooHighException || rootCause instanceof ErrorRateTooHighException) {
            errorCode = HttpURLConnection.HTTP_BAD_REQUEST;
            response = ExceptionUtils.getRootCause(e).getMessage();
            logStacktrace = false;
        } else if (hasCause(e, AuthException.class)) {
            errorCode = HttpURLConnection.HTTP_FORBIDDEN;
            response = e.getMessage();
            logStacktrace = false;
        } else if (e instanceof IllegalArgumentException || rootCause instanceof IllegalArgumentException) {
            errorCode = HttpURLConnection.HTTP_BAD_REQUEST;
            response = e.getMessage();
        } else if (e instanceof PathNotFoundException || rootCause instanceof PathNotFoundException) {
            errorCode = HttpURLConnection.HTTP_NOT_FOUND;
            response = e.getMessage();
        } else if (e instanceof TimeoutException || rootCause instanceof TimeoutException) {
            errorCode = HttpURLConnection.HTTP_INTERNAL_ERROR;
            response = "Checking took longer than " + config.getMaxCheckTimeMillis() / 1000.0f
                    + " seconds, which is this server's limit. "
                    + "Please make sure you have selected the proper language or consider submitting a shorter text.";
        } else {
            response = "Internal Error: " + e.getMessage();
            errorCode = HttpURLConnection.HTTP_INTERNAL_ERROR;
            textLoggingAllowed = true;
        }
        long endTime = System.currentTimeMillis();
        logError(remoteAddress, e, errorCode, httpExchange, parameters, textLoggingAllowed, logStacktrace,
                endTime - startTime);
        sendError(httpExchange, errorCode, "Error: " + response);

    } finally {
        httpExchange.close();
        if (incrementHandleCount) {
            reqCounter.decrementHandleCount(reqId);
        }
    }
}

From source file:org.languagetool.server.LanguageToolHttpHandler.java

private void logError(String remoteAddress, Exception e, int errorCode, HttpExchange httpExchange,
        Map<String, String> params, boolean textLoggingAllowed, boolean logStacktrace, long runtimeMillis) {
    String message = "An error has occurred: '" + e.getMessage() + "', sending HTTP code " + errorCode + ". ";
    message += "Access from " + remoteAddress + ", ";
    message += "HTTP user agent: " + getHttpUserAgent(httpExchange) + ", ";
    message += "User agent param: " + params.get("useragent") + ", ";
    if (params.get("v") != null) {
        message += "v: " + params.get("v") + ", ";
    }//  www.  j  ava  2s. c o m
    message += "Referrer: " + getHttpReferrer(httpExchange) + ", ";
    message += "language: " + params.get("language") + ", ";
    message += "h: " + reqCounter.getHandleCount() + ", ";
    message += "r: " + reqCounter.getRequestCount() + ", ";
    if (params.get("username") != null) {
        message += "user: " + params.get("username") + ", ";
    }
    if (params.get("apiKey") != null) {
        message += "apiKey: " + params.get("apiKey") + ", ";
    }
    message += "time: " + runtimeMillis + ", ";
    String text = params.get("text");
    if (text != null) {
        message += "text length: " + text.length() + ", ";
    }
    message += "m: " + ServerTools.getMode(params) + ", ";
    if (params.containsKey("instanceId")) {
        message += "iID: " + params.get("instanceId") + ", ";
    }
    if (logStacktrace) {
        message += "Stacktrace follows:";
        message += ExceptionUtils.getStackTrace(e);
        print(message, System.err);
    } else {
        message += "(no stacktrace logged)";
        print(message, System.err);
    }

    if (!(e instanceof TextTooLongException || e instanceof TooManyRequestsException
            || ExceptionUtils.getRootCause(e) instanceof ErrorRateTooHighException
            || e.getCause() instanceof TimeoutException)) {
        if (config.isVerbose() && text != null && textLoggingAllowed) {
            print("Exception was caused by this text (" + text.length() + " chars, showing up to 500):\n"
                    + StringUtils.abbreviate(text, 500), System.err);
            logToDatabase(params, message + StringUtils.abbreviate(text, 500));
        } else {
            logToDatabase(params, message);
        }
    }
}

From source file:org.languagetool.server.TextChecker.java

void checkText(AnnotatedText aText, HttpExchange httpExchange, Map<String, String> parameters,
        ErrorRequestLimiter errorRequestLimiter, String remoteAddress) throws Exception {
    checkParams(parameters);/*ww w  .j av  a2  s.co m*/
    long timeStart = System.currentTimeMillis();
    UserLimits limits = ServerTools.getUserLimits(parameters, config);

    // logging information
    String agent = parameters.get("useragent") != null ? parameters.get("useragent") : "-";
    Long agentId = null, userId = null;
    if (logger.isLogging()) {
        DatabaseAccess db = DatabaseAccess.getInstance();
        agentId = db.getOrCreateClientId(parameters.get("useragent"));
        userId = limits.getPremiumUid();
    }
    String referrer = httpExchange.getRequestHeaders().getFirst("Referer");
    String userAgent = httpExchange.getRequestHeaders().getFirst("User-Agent");

    if (aText.getPlainText().length() > limits.getMaxTextLength()) {
        String msg = "limit: " + limits.getMaxTextLength() + ", size: " + aText.getPlainText().length();
        logger.log(new DatabaseAccessLimitLogEntry("MaxCharacterSizeExceeded", logServerId, agentId, userId,
                msg, referrer, userAgent));
        ServerMetricsCollector.getInstance()
                .logRequestError(ServerMetricsCollector.RequestErrorType.MAX_TEXT_SIZE);
        throw new TextTooLongException(
                "Your text exceeds the limit of " + limits.getMaxTextLength() + " characters (it's "
                        + aText.getPlainText().length() + " characters). Please submit a shorter text.");
    }
    UserConfig userConfig = new UserConfig(
            limits.getPremiumUid() != null ? getUserDictWords(limits.getPremiumUid()) : Collections.emptyList(),
            new HashMap<>(), config.getMaxSpellingSuggestions());

    // NOTE: at the moment, feedback for A/B-Tests is only delivered from this client, so only run tests there
    if (agent != null && agent.equals("ltorg")) {
        userConfig.setAbTest(config.getAbTest());
    }

    //print("Check start: " + text.length() + " chars, " + langParam);
    boolean autoDetectLanguage = getLanguageAutoDetect(parameters);
    List<String> preferredVariants = getPreferredVariants(parameters);
    if (parameters.get("noopLanguages") != null && !autoDetectLanguage) {
        ServerMetricsCollector.getInstance()
                .logRequestError(ServerMetricsCollector.RequestErrorType.INVALID_REQUEST);
        throw new IllegalArgumentException(
                "You can specify 'noopLanguages' only when also using 'language=auto'");
    }
    List<String> noopLangs = parameters.get("noopLanguages") != null
            ? Arrays.asList(parameters.get("noopLanguages").split(","))
            : Collections.emptyList();
    List<String> preferredLangs = parameters.get("preferredLanguages") != null
            ? Arrays.asList(parameters.get("preferredLanguages").split(","))
            : Collections.emptyList();
    DetectedLanguage detLang = getLanguage(aText.getPlainText(), parameters, preferredVariants, noopLangs,
            preferredLangs);
    Language lang = detLang.getGivenLanguage();
    Integer count = languageCheckCounts.get(lang.getShortCodeWithCountryAndVariant());
    if (count == null) {
        count = 1;
    } else {
        count++;
    }
    //print("Starting check: " + aText.getPlainText().length() + " chars, #" + count);
    String motherTongueParam = parameters.get("motherTongue");
    Language motherTongue = motherTongueParam != null ? Languages.getLanguageForShortCode(motherTongueParam)
            : null;
    boolean useEnabledOnly = "yes".equals(parameters.get("enabledOnly"))
            || "true".equals(parameters.get("enabledOnly"));
    List<Language> altLanguages = new ArrayList<>();
    if (parameters.get("altLanguages") != null) {
        String[] altLangParams = parameters.get("altLanguages").split(",\\s*");
        for (String langCode : altLangParams) {
            Language altLang = Languages.getLanguageForShortCode(langCode);
            altLanguages.add(altLang);
            if (altLang.hasVariant() && !altLang.isVariant()) {
                ServerMetricsCollector.getInstance()
                        .logRequestError(ServerMetricsCollector.RequestErrorType.INVALID_REQUEST);
                throw new IllegalArgumentException("You specified altLanguage '" + langCode
                        + "', but for this language you need to specify a variant, e.g. 'en-GB' instead of just 'en'");
            }
        }
    }
    List<String> enabledRules = getEnabledRuleIds(parameters);

    List<String> disabledRules = getDisabledRuleIds(parameters);
    List<CategoryId> enabledCategories = getCategoryIds("enabledCategories", parameters);
    List<CategoryId> disabledCategories = getCategoryIds("disabledCategories", parameters);

    if ((disabledRules.size() > 0 || disabledCategories.size() > 0) && useEnabledOnly) {
        ServerMetricsCollector.getInstance()
                .logRequestError(ServerMetricsCollector.RequestErrorType.INVALID_REQUEST);
        throw new IllegalArgumentException(
                "You cannot specify disabled rules or categories using enabledOnly=true");
    }
    if (enabledRules.isEmpty() && enabledCategories.isEmpty() && useEnabledOnly) {
        ServerMetricsCollector.getInstance()
                .logRequestError(ServerMetricsCollector.RequestErrorType.INVALID_REQUEST);
        throw new IllegalArgumentException(
                "You must specify enabled rules or categories when using enabledOnly=true");
    }

    boolean useQuerySettings = enabledRules.size() > 0 || disabledRules.size() > 0
            || enabledCategories.size() > 0 || disabledCategories.size() > 0;
    boolean allowIncompleteResults = "true".equals(parameters.get("allowIncompleteResults"));
    boolean enableHiddenRules = "true".equals(parameters.get("enableHiddenRules"));
    JLanguageTool.Mode mode = ServerTools.getMode(parameters);
    String callback = parameters.get("callback");
    QueryParams params = new QueryParams(altLanguages, enabledRules, disabledRules, enabledCategories,
            disabledCategories, useEnabledOnly, useQuerySettings, allowIncompleteResults, enableHiddenRules,
            mode, callback);

    Long textSessionId = null;
    try {
        if (parameters.containsKey("textSessionId")) {
            String textSessionIdStr = parameters.get("textSessionId");
            if (textSessionIdStr.contains(":")) { // transitioning to new format used in chrome addon
                // format: "{random number in 0..99999}:{unix time}"
                long random, timestamp;
                int sepPos = textSessionIdStr.indexOf(':');
                random = Long.valueOf(textSessionIdStr.substring(0, sepPos));
                timestamp = Long.valueOf(textSessionIdStr.substring(sepPos + 1));
                // use random number to choose a slice in possible range of values
                // then choose position in slice by timestamp
                long maxRandom = 100000;
                long randomSegmentSize = (Long.MAX_VALUE - maxRandom) / maxRandom;
                long segmentOffset = random * randomSegmentSize;
                if (timestamp > randomSegmentSize) {
                    print(String.format("Could not transform textSessionId '%s'", textSessionIdStr));
                }
                textSessionId = segmentOffset + timestamp;
            } else {
                textSessionId = Long.valueOf(textSessionIdStr);
            }

            userConfig.setTextSessionId(textSessionId);
        }
    } catch (NumberFormatException ex) {
        print("Could not parse textSessionId '" + parameters.get("textSessionId") + "' as long: "
                + ex.getMessage());
    }
    int textSize = aText.getPlainText().length();

    List<RuleMatch> ruleMatchesSoFar = Collections.synchronizedList(new ArrayList<>());

    Future<List<RuleMatch>> future = executorService.submit(new Callable<List<RuleMatch>>() {
        @Override
        public List<RuleMatch> call() throws Exception {
            // use to fake OOM in thread for testing:
            /*if (Math.random() < 0.1) {
              throw new OutOfMemoryError();
            }*/
            return getRuleMatches(aText, lang, motherTongue, parameters, params, userConfig,
                    f -> ruleMatchesSoFar.add(f));
        }
    });
    String incompleteResultReason = null;
    List<RuleMatch> matches;
    try {
        if (limits.getMaxCheckTimeMillis() < 0) {
            matches = future.get();
        } else {
            matches = future.get(limits.getMaxCheckTimeMillis(), TimeUnit.MILLISECONDS);
        }
    } catch (ExecutionException e) {
        future.cancel(true);
        if (ExceptionUtils.getRootCause(e) instanceof ErrorRateTooHighException) {
            ServerMetricsCollector.getInstance()
                    .logRequestError(ServerMetricsCollector.RequestErrorType.TOO_MANY_ERRORS);
            logger.log(new DatabaseCheckErrorLogEntry("ErrorRateTooHigh", logServerId, agentId, userId, lang,
                    detLang.getDetectedLanguage(), textSize, "matches: " + ruleMatchesSoFar.size()));
        }
        if (params.allowIncompleteResults
                && ExceptionUtils.getRootCause(e) instanceof ErrorRateTooHighException) {
            print(e.getMessage() + " - returning " + ruleMatchesSoFar.size()
                    + " matches found so far. Detected language: " + detLang);
            matches = new ArrayList<>(ruleMatchesSoFar); // threads might still be running, so make a copy
            incompleteResultReason = "Results are incomplete: " + ExceptionUtils.getRootCause(e).getMessage();
        } else if (e.getCause() != null && e.getCause() instanceof OutOfMemoryError) {
            throw (OutOfMemoryError) e.getCause();
        } else {
            throw new RuntimeException(e.getMessage() + ", detected: " + detLang, e);
        }
    } catch (TimeoutException e) {
        boolean cancelled = future.cancel(true);
        Path loadFile = Paths.get("/proc/loadavg"); // works in Linux only(?)
        String loadInfo = loadFile.toFile().exists() ? Files.readAllLines(loadFile).toString() : "(unknown)";
        if (errorRequestLimiter != null) {
            errorRequestLimiter.logAccess(remoteAddress, httpExchange.getRequestHeaders(), parameters);
        }
        String message = "Text checking took longer than allowed maximum of " + limits.getMaxCheckTimeMillis()
                + " milliseconds (cancelled: " + cancelled + ", lang: "
                + lang.getShortCodeWithCountryAndVariant() + ", detected: " + detLang + ", #" + count + ", "
                + aText.getPlainText().length() + " characters of text" + ", mode: "
                + mode.toString().toLowerCase() + ", h: " + reqCounter.getHandleCount() + ", r: "
                + reqCounter.getRequestCount() + ", system load: " + loadInfo + ")";
        if (params.allowIncompleteResults) {
            print(message + " - returning " + ruleMatchesSoFar.size() + " matches found so far");
            matches = new ArrayList<>(ruleMatchesSoFar); // threads might still be running, so make a copy
            incompleteResultReason = "Results are incomplete: text checking took longer than allowed maximum of "
                    + String.format(Locale.ENGLISH, "%.2f", limits.getMaxCheckTimeMillis() / 1000.0)
                    + " seconds";
        } else {
            ServerMetricsCollector.getInstance()
                    .logRequestError(ServerMetricsCollector.RequestErrorType.MAX_CHECK_TIME);
            logger.log(new DatabaseCheckErrorLogEntry("MaxCheckTimeExceeded", logServerId, agentId,
                    limits.getPremiumUid(), lang, detLang.getDetectedLanguage(), textSize,
                    "load: " + loadInfo));
            throw new RuntimeException(message, e);
        }
    }

    setHeaders(httpExchange);

    List<RuleMatch> hiddenMatches = new ArrayList<>();
    if (config.getHiddenMatchesServer() != null && params.enableHiddenRules
            && config.getHiddenMatchesLanguages().contains(lang)) {
        if (config.getHiddenMatchesServerFailTimeout() > 0 && lastHiddenMatchesServerTimeout != -1
                && System.currentTimeMillis() - lastHiddenMatchesServerTimeout < config
                        .getHiddenMatchesServerFailTimeout()) {
            ServerMetricsCollector.getInstance().logHiddenServerStatus(false);
            print("Warn: Skipped querying hidden matches server at " + config.getHiddenMatchesServer()
                    + " because of recent error/timeout (timeout=" + config.getHiddenMatchesServerFailTimeout()
                    + "ms).");
        } else {
            ResultExtender resultExtender = new ResultExtender(config.getHiddenMatchesServer(),
                    config.getHiddenMatchesServerTimeout());
            try {
                long start = System.currentTimeMillis();
                List<RemoteRuleMatch> extensionMatches = resultExtender
                        .getExtensionMatches(aText.getPlainText(), parameters);
                hiddenMatches = resultExtender.getFilteredExtensionMatches(matches, extensionMatches);
                long end = System.currentTimeMillis();
                print("Hidden matches: " + extensionMatches.size() + " -> " + hiddenMatches.size() + " in "
                        + (end - start) + "ms for " + lang.getShortCodeWithCountryAndVariant());
                ServerMetricsCollector.getInstance().logHiddenServerStatus(true);
                lastHiddenMatchesServerTimeout = -1;
            } catch (Exception e) {
                ServerMetricsCollector.getInstance().logHiddenServerStatus(false);
                print("Warn: Failed to query hidden matches server at " + config.getHiddenMatchesServer() + ": "
                        + e.getClass() + ": " + e.getMessage());
                lastHiddenMatchesServerTimeout = System.currentTimeMillis();
            }
        }
    }
    int compactMode = Integer.parseInt(parameters.getOrDefault("c", "0"));
    String response = getResponse(aText, detLang, motherTongue, matches, hiddenMatches, incompleteResultReason,
            compactMode);
    if (params.callback != null) {
        // JSONP - still needed today for the special case of hosting your own on-premise LT without SSL
        // and using it from a local MS Word (not Online Word) - issue #89 in the add-in repo:
        response = params.callback + "(" + response + ");";
    }
    String messageSent = "sent";
    String languageMessage = lang.getShortCodeWithCountryAndVariant();
    try {
        httpExchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, response.getBytes(ENCODING).length);
        httpExchange.getResponseBody().write(response.getBytes(ENCODING));
        ServerMetricsCollector.getInstance().logResponse(HttpURLConnection.HTTP_OK);
    } catch (IOException exception) {
        // the client is disconnected
        messageSent = "notSent: " + exception.getMessage();
    }
    if (motherTongue != null) {
        languageMessage += " (mother tongue: " + motherTongue.getShortCodeWithCountryAndVariant() + ")";
    }
    if (autoDetectLanguage) {
        languageMessage += "[auto]";
    }
    languageCheckCounts.put(lang.getShortCodeWithCountryAndVariant(), count);
    int computationTime = (int) (System.currentTimeMillis() - timeStart);
    String version = parameters.get("v") != null ? ", v:" + parameters.get("v") : "";
    print("Check done: " + aText.getPlainText().length() + " chars, " + languageMessage + ", #" + count + ", "
            + referrer + ", " + matches.size() + " matches, " + computationTime + "ms, agent:" + agent + version
            + ", " + messageSent + ", q:" + (workQueue != null ? workQueue.size() : "?") + ", h:"
            + reqCounter.getHandleCount() + ", dH:" + reqCounter.getDistinctIps() + ", m:"
            + mode.toString().toLowerCase());

    int matchCount = matches.size();
    Map<String, Integer> ruleMatchCount = new HashMap<>();
    for (RuleMatch match : matches) {
        String ruleId = match.getRule().getId();
        ruleMatchCount.put(ruleId, ruleMatchCount.getOrDefault(ruleId, 0) + 1);
    }

    ServerMetricsCollector.getInstance().logCheck(lang, computationTime, textSize, matchCount, mode, agent,
            ruleMatchCount);

    if (!config.isSkipLoggingChecks()) {
        DatabaseCheckLogEntry logEntry = new DatabaseCheckLogEntry(userId, agentId, logServerId, textSize,
                matchCount, lang, detLang.getDetectedLanguage(), computationTime, textSessionId,
                mode.toString());
        logEntry.setRuleMatches(new DatabaseRuleMatchLogEntry(
                config.isSkipLoggingRuleMatches() ? Collections.emptyMap() : ruleMatchCount));
        logger.log(logEntry);
    }
}

From source file:org.mayocat.shop.billing.internal.SendEmailsWhenOrderIsPaid.java

/**
 * Actually sends a notification email/*from   w  ww .j  a v a2  s .c  o  m*/
 *
 * @param template the mail template
 * @param context the mail JSON context
 */
private void sendNotificationMail(MailTemplate template, Map<String, Object> context, Tenant tenant) {
    try {
        mailTemplateService.sendTemplateMail(template, context, tenant);
    } catch (MailException e) {
        logger.error("Failed to send order paid email", ExceptionUtils.getRootCause(e));
    }
}

From source file:org.openmrs.module.openconceptlab.updater.Updater.java

public static String getErrorMessage(Throwable e) {
    String message = e.getMessage();
    Throwable rootCause = ExceptionUtils.getRootCause(e);
    if (rootCause == null) {
        rootCause = e;//ww w .j a v  a  2s  .  co  m
    }

    String[] stackFrames = ExceptionUtils.getStackFrames(rootCause);
    int endIndex = stackFrames.length > 5 ? 5 : stackFrames.length;
    message += "\n caused by: " + StringUtils.join(stackFrames, "\n", 0, endIndex);

    if (message.length() > 1024) {
        return message.substring(0, 1024);
    } else {
        return message;
    }
}

From source file:org.primefaces.extensions.component.ajaxerrorhandler.AjaxExceptionHandler.java

private void handlePartialResponseError(final FacesContext context, final Throwable t) {
    if (context.getResponseComplete()) {
        return; // don't write anything if the response is complete
    }/*  w w w  . j  a v a2 s. co m*/

    if (!context.getExternalContext().isResponseCommitted()) {
        context.getExternalContext().responseReset();
    }

    try {
        Throwable rootCause = ExceptionUtils.getRootCause(t);

        // Workaround for ViewExpiredException if UIViewRoot was not restored ...
        if (context.getViewRoot() == null) {
            try {
                String uri = ((HttpServletRequest) context.getExternalContext().getRequest()).getRequestURI();
                UIViewRoot viewRoot = context.getApplication().getViewHandler().createView(context, uri);
                context.setViewRoot(viewRoot);

                // Workaround for Mojarra : if  UIViewRoot == null (VIEW is lost in session), throwed is  IllegalArgumentException instead of 'ViewExpiredException'
                if (rootCause == null && t instanceof IllegalArgumentException) {
                    rootCause = new javax.faces.application.ViewExpiredException(uri);
                }

                // buildView - create component tree in view ...
                // todo: add CONTEXT-PARAM for set this feature BUILD VIEW
                String viewId = viewRoot.getViewId();
                ViewDeclarationLanguage vdl = context.getApplication().getViewHandler()
                        .getViewDeclarationLanguage(context, viewId);
                vdl.buildView(context, viewRoot);
            } catch (Exception tt) {
                LOGGER.log(Level.SEVERE, tt.getMessage(), tt);
            }
        }

        String errorName = (rootCause == null) ? t.getClass().getCanonicalName()
                : rootCause.getClass().getCanonicalName();
        LOGGER.log(Level.SEVERE, "" + t.getMessage(), t);

        ExternalContext extContext = context.getExternalContext();

        extContext.addResponseHeader("Content-Type",
                "text/xml; charset=" + extContext.getRequestCharacterEncoding());
        extContext.addResponseHeader("Cache-Control", "no-cache");
        extContext.setResponseCharacterEncoding(extContext.getRequestCharacterEncoding());
        extContext.setResponseContentType("text/xml");

        PartialResponseWriter writer = context.getPartialViewContext().getPartialResponseWriter();

        writer.startDocument();

        writer.startElement("error", null);

        // Node <error-name>
        writer.startElement("error-name", null);
        writer.write(errorName);
        writer.endElement("error-name");

        // Node <error-message>
        writer.startElement("error-message", null);
        writer.startCDATA();
        String message = rootCause != null && rootCause.getMessage() != null ? rootCause.getMessage()
                : t.getMessage();
        if (message == null)
            message = "";
        writer.write(message);
        writer.endCDATA();
        writer.endElement("error-message");

        // Node <error-stacktrace>
        writer.startElement("error-stacktrace", null);
        writer.startCDATA();
        String stackTrace = ExceptionUtils.getStackTrace(rootCause == null ? t : rootCause);
        if (stackTrace == null)
            stackTrace = "";
        writer.write(stackTrace);
        writer.endCDATA();
        writer.endElement("error-stacktrace");

        // Node <error-stacktrace>
        writer.startElement("error-hostname", null);
        writer.write(getHostname());
        writer.endElement("error-hostname");

        UIViewRoot root = context.getViewRoot();
        AjaxErrorHandlerVisitCallback visitCallback = new AjaxErrorHandlerVisitCallback(errorName);
        if (root != null)
            root.visitTree(VisitContext.createVisitContext(context), visitCallback);

        UIComponent titleFacet = visitCallback.findCurrentTitleFacet();
        if (titleFacet != null) {
            writer.startElement("updateTitle", null);
            writer.startCDATA();

            try {
                context.setResponseWriter(writer);
                titleFacet.encodeAll(context);
            } catch (Exception e) {
                LOGGER.log(Level.WARNING, "Rendering titleUpdate in AjaxExceptionHandler throws exception!", e);
                writer.write("<exception />");
            }

            writer.endCDATA();
            writer.endElement("updateTitle");
        }

        UIComponent bodyFacet = visitCallback.findCurrentBodyFacet();
        if (bodyFacet != null) {
            writer.startElement("updateBody", null);
            writer.startCDATA();

            try {
                context.setResponseWriter(writer);
                bodyFacet.encodeAll(context);
            } catch (Exception e) {
                LOGGER.log(Level.WARNING, "Rendering bodyUpdate in AjaxExceptionHandler throws exception!", e);
                writer.write("<exception />");
            }

            writer.endCDATA();
            writer.endElement("updateBody");
        }

        List<UIComponent> customContent = visitCallback.findCurrentChildren();
        if (customContent != null && customContent.size() > 0) {
            writer.startElement("updateCustomContent", null);
            writer.startCDATA();

            try {
                context.setResponseWriter(writer);
                for (UIComponent component : customContent) {
                    component.encodeAll(context);
                }
            } catch (Exception e) {
                LOGGER.log(Level.WARNING,
                        "Rendering updateCustomContent in AjaxExceptionHandler throws exception!", e);
                writer.write("<exception />");
            }

            writer.endCDATA();
            writer.endElement("updateCustomContent");
        }

        /*
        // Update state - is ignored, because ajaxerrorhandler.js is not ready for this update ...
        if (!context.getViewRoot().isTransient()) {
           // Get the view state and write it to the response..
           writer.startElement("updateViewState", null);
           writer.startCDATA();
           try {
              String state = context.getApplication().getStateManager().getViewState(context);
              writer.write(state);
           } catch (Exception e) {
              LOGGER.log(Level.WARNING, "Rendering updateViewState in AjaxExceptionHandler throws exception!", e);
              writer.write("<exception />");
           }
                
           writer.endCDATA();
           writer.endElement("updateViewState");
        }
         */

        writer.endElement("error");

        writer.endDocument();
        context.responseComplete();
    } catch (IOException e) {
        if (LOGGER.isLoggable(Level.SEVERE)) {
            LOGGER.log(Level.SEVERE, e.getMessage(), e);
        }
    }
}

From source file:org.sherlok.PipelineLoader.java

/** Just loads that pipeline. No caching. */
UimaPipeline load(PipelineDef pipelineDef) throws SherlokException {

    pipelineDef.validate("could not validate pipeline wit Id '" + pipelineDef.getId() + "',"); // just to make sure...

    // 3. create a list of engines (and their bundles) to resolve
    List<EngineDef> engineDefsUsedInP = list();
    Set<BundleDef> bundleDefsToResolve = set();
    for (String pengineId : pipelineDef.getEnginesFromScript()) {
        EngineDef en = controller.getEngineDef(pengineId);
        if (en == null) {
            throw new SherlokException();
        }//from   w  ww . ja  va  2  s  . c om
        validateNotNull(en, "could not find engine '" + pengineId + "' as defined in pipeline '"
                + pipelineDef.getId() + "'");
        BundleDef b = en.getBundle();
        validateNotNull(b, "could not find bundle '" + b + "' that is required by engine '" + en + "'");
        LOG.trace("adding engineDef '{}' with bundleDef '{}'", en, b);
        engineDefsUsedInP.add(en);
        bundleDefsToResolve.add(b);
    }

    // 4. solve (download) bundle dependencies
    try {
        solveDependencies(pipelineDef.getName(), pipelineDef.getVersion(), bundleDefsToResolve,
                engineDefsUsedInP.size());
    } catch (ArtifactResolutionException e) {
        throw new SherlokException("Failed to resolve solve pipeline dependencies")
                .setObject(pipelineDef.getId()).setDetails(e.getMessage());
    } catch (DependencyCollectionException e) {
        throw new SherlokException("Failed to collect pipeline dependencies").setObject(pipelineDef.getId())
                .setDetails(e.getMessage());
    } catch (Exception e) {
        throw new RuntimeException(e); // should not happen
    }

    // 5. create UimaPipeline
    UimaPipeline uimaPipeline;
    try {
        uimaPipeline = new UimaPipeline(pipelineDef, engineDefsUsedInP);
    } catch (IOException | UIMAException e) {// other SherlokErrors catched
        LOG.warn("could not initialize UIMA pipeline", e);

        Throwable rootCause = ExceptionUtils.getRootCause(e);
        if (rootCause instanceof RutaParseRuntimeException) {
            throw new SherlokException(rootCause.getMessage()).setObject(pipelineDef.toString())
                    .setDetails(rootCause.getStackTrace());
        } else {
            throw new SherlokException("could not initialize UIMA pipeline").setObject(pipelineDef.toString())
                    .setDetails(e.getStackTrace());
        }
    }

    return uimaPipeline;
}

From source file:org.wso2.carbon.uuf.core.App.java

/**
 * Renders the relevant page for the given request.
 *
 * @param request  HTTP request//from www.j a  va2 s .  c o  m
 * @param response HTTP response
 * @return HTML from page rendering
 * @throws PageRedirectException if a redirection for another page/URL is needed
 * @throws HttpErrorException    if some other HTTP error occurred
 */
public String renderPage(HttpRequest request, HttpResponse response) {
    RequestLookup requestLookup = createRequestLookup(request, response);
    API api = new API(sessionManager, authorizer, requestLookup);
    Theme theme = getRenderingTheme(api);
    try {
        return renderPageUri(request.getUriWithoutContextPath(), null, requestLookup, api, theme);
    } catch (SessionNotFoundException e) {
        String loginPageUri = configuration.getLoginPageUri().orElseThrow(() -> e);
        // Redirect to the login page.
        throw new PageRedirectException(requestLookup.getContextPath() + loginPageUri, e);
    } catch (PageRedirectException e) {
        throw e;
    } catch (PageNotFoundException e) {
        // See https://googlewebmastercentral.blogspot.com/2010/04/to-slash-or-not-to-slash.html
        // If the tailing '/' is extra or a it is missing, then send 301 with corrected URL.
        String uriWithoutContextPath = request.getUriWithoutContextPath();
        String correctedUriWithoutContextPath = uriWithoutContextPath.endsWith("/")
                ? uriWithoutContextPath.substring(0, uriWithoutContextPath.length() - 1)
                : (uriWithoutContextPath + "/");
        if (hasPage(correctedUriWithoutContextPath)) {
            if (request.isGetRequest()) {
                // Redirecting to the correct page.
                String correctedUri = request.getContextPath() + correctedUriWithoutContextPath;
                if (request.getQueryString() != null) {
                    correctedUri = correctedUri + '?' + request.getQueryString();
                }
                throw new PageRedirectException(correctedUri, e);
            } else {
                // If GET, we correct, since this can be an end-user error. But if POST it's the responsibility of
                // the dev to use correct URL. Because HTTP POST redirect is not well supported.
                // See : https://softwareengineering.stackexchange.com/q/99894
                String message = e.getMessage() + " Retry with correct URI ending "
                        + correctedUriWithoutContextPath;
                return renderErrorPage(new PageNotFoundException(message, e), request, response, theme);
            }
        } else {
            return renderErrorPage(e, request, response, theme);
        }
    } catch (HttpErrorException e) {
        return renderErrorPage(e, request, response, theme);
    } catch (PluginExecutionException e) {
        LOGGER.error("An error occurred while executing a plugin.", e);
        return renderErrorPage(new HttpErrorException(STATUS_INTERNAL_SERVER_ERROR, e.getMessage(), e), request,
                response, theme);
    } catch (RenderingException e) {
        LOGGER.error("An error occurred while rendering page for request '{}'.", request, e);
        String message = (e.getCause() != null) ? ExceptionUtils.getRootCause(e).getMessage() : e.getMessage();
        return renderErrorPage(new HttpErrorException(STATUS_INTERNAL_SERVER_ERROR, message, e), request,
                response, theme);
    }
}