Example usage for java.util.concurrent ExecutionException getMessage

List of usage examples for java.util.concurrent ExecutionException getMessage

Introduction

In this page you can find the example usage for java.util.concurrent ExecutionException getMessage.

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:voldemort.restclient.R2Store.java

@Override
public void put(ByteArray key, Versioned<byte[]> value, byte[] transform) throws VoldemortException {
    RestResponse response = null;/*from  w w w .  j  a  va2s .c  o  m*/

    try {
        byte[] payload = value.getValue();

        // Create the REST request with this byte array
        String base64Key = RestUtils.encodeVoldemortKey(key.get());
        RestRequestBuilder rb = new RestRequestBuilder(
                new URI(this.restBootstrapURL + "/" + getName() + "/" + base64Key));

        // Create a HTTP POST request
        rb.setMethod(POST);
        rb.setEntity(payload);
        rb.setHeader(CONTENT_TYPE, "binary");
        rb.setHeader(CONTENT_LENGTH, "" + payload.length);
        String timeoutStr = Long
                .toString(this.config.getTimeoutConfig().getOperationTimeout(VoldemortOpCode.PUT_OP_CODE));
        rb.setHeader(RestMessageHeaders.X_VOLD_REQUEST_TIMEOUT_MS, timeoutStr);
        rb.setHeader(RestMessageHeaders.X_VOLD_REQUEST_ORIGIN_TIME_MS,
                String.valueOf(System.currentTimeMillis()));
        if (this.routingTypeCode != null) {
            rb.setHeader(RestMessageHeaders.X_VOLD_ROUTING_TYPE_CODE, this.routingTypeCode);
        }
        if (this.zoneId != INVALID_ZONE_ID) {
            rb.setHeader(RestMessageHeaders.X_VOLD_ZONE_ID, String.valueOf(this.zoneId));
        }

        // Serialize the Vector clock
        VectorClock vc = (VectorClock) value.getVersion();

        // If the given Vector clock is empty, we'll let the receiver of
        // this request fetch the existing vector clock and increment before
        // doing the put.
        if (vc != null) {
            String serializedVC = null;
            if (!vc.getEntries().isEmpty()) {
                serializedVC = RestUtils.getSerializedVectorClock(vc);
            }

            if (serializedVC != null && serializedVC.length() > 0) {
                rb.setHeader(RestMessageHeaders.X_VOLD_VECTOR_CLOCK, serializedVC);
            }
        }

        RestRequest request = rb.build();
        Future<RestResponse> f = client.restRequest(request);

        // This will block
        response = f.get();

        String serializedUpdatedVC = response.getHeader(RestMessageHeaders.X_VOLD_VECTOR_CLOCK);
        if (serializedUpdatedVC == null || serializedUpdatedVC.length() == 0) {
            if (logger.isDebugEnabled()) {
                logger.debug("Received empty vector clock in the response");
            }
        } else {
            VectorClock updatedVC = RestUtils.deserializeVectorClock(serializedUpdatedVC);
            VectorClock originalVC = (VectorClock) value.getVersion();
            originalVC.copyFromVectorClock(updatedVC);
        }

        final ByteString entity = response.getEntity();
        if (entity == null) {
            if (logger.isDebugEnabled()) {
                logger.debug("Empty response !");
            }
        }
    } catch (ExecutionException e) {
        if (e.getCause() instanceof RestException) {
            RestException exception = (RestException) e.getCause();
            if (logger.isDebugEnabled()) {
                logger.debug("REST EXCEPTION STATUS : " + exception.getResponse().getStatus());
            }

            int httpErrorStatus = exception.getResponse().getStatus();
            if (httpErrorStatus == BAD_REQUEST.getCode()) {
                throw new VoldemortException("Bad request: " + e.getMessage(), e);
            } else if (httpErrorStatus == PRECONDITION_FAILED.getCode()) {
                throw new ObsoleteVersionException(e.getMessage());
            } else if (httpErrorStatus == REQUEST_TIMEOUT.getCode()
                    || httpErrorStatus == INTERNAL_SERVER_ERROR.getCode()) {
                throw new InsufficientOperationalNodesException(e.getMessage());
            }
        }
        throw new VoldemortException("Unknown HTTP request execution exception: " + e.getMessage(), e);

    } catch (InterruptedException e) {
        if (logger.isDebugEnabled()) {
            logger.debug("Operation interrupted : " + e.getMessage());
        }
        throw new VoldemortException("Unknown Voldemort exception: " + e.getMessage());
    } catch (URISyntaxException e) {
        throw new VoldemortException("Illegal HTTP URL" + e.getMessage());
    }
}

From source file:voldemort.restclient.R2Store.java

@Override
public boolean delete(ByteArray key, Version version) throws VoldemortException {
    try {/*  w  w  w  .  java  2  s  . co m*/
        // Create the REST request with this byte array
        String base64Key = RestUtils.encodeVoldemortKey(key.get());
        RestRequestBuilder rb = new RestRequestBuilder(
                new URI(this.restBootstrapURL + "/" + getName() + "/" + base64Key));
        // Create a HTTP POST request
        rb.setMethod(DELETE);
        rb.setHeader(CONTENT_LENGTH, "0");
        String timeoutStr = Long
                .toString(this.config.getTimeoutConfig().getOperationTimeout(VoldemortOpCode.DELETE_OP_CODE));
        rb.setHeader(RestMessageHeaders.X_VOLD_REQUEST_TIMEOUT_MS, timeoutStr);
        rb.setHeader(RestMessageHeaders.X_VOLD_REQUEST_ORIGIN_TIME_MS,
                String.valueOf(System.currentTimeMillis()));
        if (this.routingTypeCode != null) {
            rb.setHeader(RestMessageHeaders.X_VOLD_ROUTING_TYPE_CODE, this.routingTypeCode);
        }
        if (this.zoneId != INVALID_ZONE_ID) {
            rb.setHeader(RestMessageHeaders.X_VOLD_ZONE_ID, String.valueOf(this.zoneId));
        }
        // Serialize the Vector clock
        VectorClock vc = (VectorClock) version;

        // If the given Vector clock is empty, we'll let the receiver of
        // this request fetch the existing vector clock and increment
        // before
        // doing the put.
        if (vc != null && vc.getEntries().size() != 0) {
            String serializedVC = null;
            if (!vc.getEntries().isEmpty()) {
                serializedVC = RestUtils.getSerializedVectorClock(vc);
            }

            if (serializedVC != null && serializedVC.length() > 0) {
                rb.setHeader(RestMessageHeaders.X_VOLD_VECTOR_CLOCK, serializedVC);
            }
        }

        RestRequest request = rb.build();
        Future<RestResponse> f = client.restRequest(request);

        // This will block
        RestResponse response = f.get();
        final ByteString entity = response.getEntity();
        if (entity == null) {
            if (logger.isDebugEnabled()) {
                logger.debug("Empty response !");
            }
        }

    } catch (ExecutionException e) {
        if (e.getCause() instanceof RestException) {
            RestException exception = (RestException) e.getCause();
            if (logger.isDebugEnabled()) {
                logger.debug("REST EXCEPTION STATUS : " + exception.getResponse().getStatus());
            }
            if (exception.getResponse().getStatus() == NOT_FOUND.getCode()) {
                return false;
            }
        } else {
            throw new VoldemortException("Unknown HTTP request execution exception: " + e.getMessage(), e);
        }
    } catch (InterruptedException e) {
        if (logger.isDebugEnabled()) {
            logger.debug("Operation interrupted : " + e.getMessage());
        }
        throw new VoldemortException("Operation Interrupted: " + e.getMessage(), e);
    } catch (URISyntaxException e) {
        throw new VoldemortException("Illegal HTTP URL" + e.getMessage(), e);
    }
    return true;
}

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);/*from   w  w w. j  av  a 2s.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.apache.nifi.remote.util.SiteToSiteRestApiClient.java

/**
 * <p>/*from  w  w  w.  ja v  a  2 s .com*/
 * Initiate a transaction for sending data.
 * </p>
 *
 * <p>
 * If a proxy server requires auth, the proxy server returns 407 response with available auth schema such as basic or digest.
 * Then client has to resend the same request with its credential added.
 * This mechanism is problematic for sending data from NiFi.
 * </p>
 *
 * <p>
 * In order to resend a POST request with auth param,
 * NiFi has to either read flow-file contents to send again, or keep the POST body somewhere.
 * If we store that in memory, it would causes OOM, or storing it on disk slows down performance.
 * Rolling back processing session would be overkill.
 * Reading flow-file contents only when it's ready to send in a streaming way is ideal.
 * </p>
 *
 * <p>
 * Additionally, the way proxy authentication is done is vary among Proxy server software.
 * Some requires 407 and resend cycle for every requests, while others keep a connection between a client and
 * the proxy server, then consecutive requests skip auth steps.
 * The problem is, that how should we behave is only told after sending a request to the proxy.
 * </p>
 *
 * In order to handle above concerns correctly and efficiently, this method do the followings:
 *
 * <ol>
 * <li>Send a GET request to controller resource, to initiate an HttpAsyncClient. The instance will be used for further requests.
 *      This is not required by the Site-to-Site protocol, but it can setup proxy auth state safely.</li>
 * <li>Send a POST request to initiate a transaction. While doing so, it captures how a proxy server works.
 * If 407 and resend cycle occurs here, it implies that we need to do the same thing again when we actually send the data.
 * Because if the proxy keeps using the same connection and doesn't require an auth step, it doesn't do so here.</li>
 * <li>Then this method stores whether the final POST request should wait for the auth step.
 * So that {@link #openConnectionForSend} can determine when to produce contents.</li>
 * </ol>
 *
 * <p>
 * The above special sequence is only executed when a proxy instance is set, and its username is set.
 * </p>
 *
 * @param post a POST request to establish transaction
 * @return POST request response
 * @throws IOException thrown if the post request failed
 */
private HttpResponse initiateTransactionForSend(final HttpPost post) throws IOException {
    if (shouldCheckProxyAuth()) {
        final CloseableHttpAsyncClient asyncClient = getHttpAsyncClient();
        final HttpGet get = createGetControllerRequest();
        final Future<HttpResponse> getResult = asyncClient.execute(get, null);
        try {
            final HttpResponse getResponse = getResult.get(readTimeoutMillis, TimeUnit.MILLISECONDS);
            logger.debug("Proxy auth check has done. getResponse={}", getResponse.getStatusLine());
        } catch (final ExecutionException e) {
            logger.debug("Something has happened at get controller requesting thread for proxy auth check. {}",
                    e.getMessage());
            throw toIOException(e);
        } catch (TimeoutException | InterruptedException e) {
            throw new IOException(e);
        }
    }

    final HttpAsyncRequestProducer asyncRequestProducer = new HttpAsyncRequestProducer() {
        private boolean requestHasBeenReset = false;

        @Override
        public HttpHost getTarget() {
            return URIUtils.extractHost(post.getURI());
        }

        @Override
        public HttpRequest generateRequest() throws IOException, HttpException {
            final BasicHttpEntity entity = new BasicHttpEntity();
            post.setEntity(entity);
            return post;
        }

        @Override
        public void produceContent(ContentEncoder encoder, IOControl ioctrl) throws IOException {
            encoder.complete();
            if (shouldCheckProxyAuth() && requestHasBeenReset) {
                logger.debug("Produced content again, assuming the proxy server requires authentication.");
                proxyAuthRequiresResend.set(true);
            }
        }

        @Override
        public void requestCompleted(HttpContext context) {
            debugProxyAuthState(context);
        }

        @Override
        public void failed(Exception ex) {
            final String msg = String.format("Failed to create transaction for %s", post.getURI());
            logger.error(msg, ex);
            eventReporter.reportEvent(Severity.WARNING, EVENT_CATEGORY, msg);
        }

        @Override
        public boolean isRepeatable() {
            return true;
        }

        @Override
        public void resetRequest() throws IOException {
            requestHasBeenReset = true;
        }

        @Override
        public void close() throws IOException {
        }
    };

    final Future<HttpResponse> responseFuture = getHttpAsyncClient().execute(asyncRequestProducer,
            new BasicAsyncResponseConsumer(), null);
    final HttpResponse response;
    try {
        response = responseFuture.get(readTimeoutMillis, TimeUnit.MILLISECONDS);

    } catch (final ExecutionException e) {
        logger.debug("Something has happened at initiate transaction requesting thread. {}", e.getMessage());
        throw toIOException(e);
    } catch (TimeoutException | InterruptedException e) {
        throw new IOException(e);
    }
    return response;
}

From source file:com.hortonworks.registries.schemaregistry.client.SchemaRegistryClient.java

@Override
public SchemaIdVersion addSchemaVersion(final String schemaName, final SchemaVersion schemaVersion)
        throws InvalidSchemaException, IncompatibleSchemaException, SchemaNotFoundException {

    try {//www  .  j  a va  2s  . c o  m
        return schemaTextCache.get(buildSchemaTextEntry(schemaVersion, schemaName),
                () -> doAddSchemaVersion(schemaName, schemaVersion));
    } catch (ExecutionException e) {
        Throwable cause = e.getCause();
        LOG.error("Encountered error while adding new version [{}] of schema [{}] and error [{}]",
                schemaVersion, schemaName, e);
        if (cause != null) {
            if (cause instanceof InvalidSchemaException)
                throw (InvalidSchemaException) cause;
            else if (cause instanceof IncompatibleSchemaException) {
                throw (IncompatibleSchemaException) cause;
            } else if (cause instanceof SchemaNotFoundException) {
                throw (SchemaNotFoundException) cause;
            } else {
                throw new RuntimeException(cause.getMessage(), cause);
            }
        } else {
            throw new RuntimeException(e.getMessage(), e);
        }
    }
}

From source file:com.ibm.og.s3.v4.AwsChunkedEncodingInputStream.java

private byte[] createSignedChunk(final byte[] chunkData) {
    final StringBuilder chunkHeader = new StringBuilder();
    // chunk-size
    chunkHeader.append(Integer.toHexString(chunkData.length));

    byte[] chunkDigest;
    if (this.digestCache != null) {
        try {/*  w  w w.jav a 2  s.  c  om*/
            chunkDigest = this.digestCache.get((long) chunkData.length);
        } catch (final ExecutionException e) {
            throw new RuntimeException(e);
        }
    } else {
        chunkDigest = this.sha256.digest(chunkData);
    }

    // sig-extension
    final String chunkStringToSign = CHUNK_STRING_TO_SIGN_PREFIX + "\n" + this.dateTime + "\n" + this.keyPath
            + "\n" + this.priorChunkSignature + "\n" + AbstractAWSSigner.EMPTY_STRING_SHA256_HEX + "\n"
            + BinaryUtils.toHex(chunkDigest);

    final String chunkSignature = BinaryUtils
            .toHex(this.aws4Signer.signWithMac(chunkStringToSign, this.hmacSha256));
    this.priorChunkSignature = chunkSignature;
    chunkHeader.append(CHUNK_SIGNATURE_HEADER).append(chunkSignature).append(CRLF);
    try {
        final byte[] header = chunkHeader.toString().getBytes(UTF8);
        final byte[] trailer = CRLF.getBytes(UTF8);
        final byte[] signedChunk = new byte[header.length + chunkData.length + trailer.length];
        System.arraycopy(header, 0, signedChunk, 0, header.length);
        System.arraycopy(chunkData, 0, signedChunk, header.length, chunkData.length);
        System.arraycopy(trailer, 0, signedChunk, header.length + chunkData.length, trailer.length);
        return signedChunk;
    } catch (final Exception e) {
        throw new AmazonClientException("Unable to sign the chunked data. " + e.getMessage(), e);
    }
}

From source file:org.apache.pulsar.functions.worker.rest.api.ComponentImpl.java

private void updateRequest(final FunctionMetaData functionMetaData) {

    // Submit to FMT
    FunctionMetaDataManager functionMetaDataManager = worker().getFunctionMetaDataManager();

    CompletableFuture<RequestResult> completableFuture = functionMetaDataManager
            .updateFunction(functionMetaData);

    RequestResult requestResult = null;/*from   w w  w. ja va2 s. co m*/
    try {
        requestResult = completableFuture.get();
        if (!requestResult.isSuccess()) {
            throw new RestException(Status.BAD_REQUEST, requestResult.getMessage());
        }
    } catch (ExecutionException e) {
        throw new RestException(Status.INTERNAL_SERVER_ERROR, e.getMessage());
    } catch (InterruptedException e) {
        throw new RestException(Status.REQUEST_TIMEOUT, e.getMessage());
    }

}

From source file:org.openengsb.core.services.internal.deployer.connector.ConnectorDeployerService.java

private boolean doInstall(File artifact) {
    final ConnectorFile configFile;
    try {// w w  w . j  a v a2  s .  co m
        configFile = oldConfigs.get(artifact);
    } catch (ExecutionException e) {
        LOGGER.error("severe error when installing artifact", e);
        return false;
    }
    configFile.update(artifact);
    final Map<String, Object> properties = new Hashtable<String, Object>(configFile.getProperties());

    if (properties.get(Constants.SERVICE_RANKING) == null && ConnectorFile.isRootService(artifact)) {
        properties.put(Constants.SERVICE_RANKING, -1);
    }
    LOGGER.info("Loading instance {}", configFile.getName());

    final String name = FilenameUtils.removeExtension(artifact.getName());

    final Map<String, String> attributes = configFile.getAttributes();

    if (!haveDomainProvider(configFile.getDomainType())) {
        LOGGER.info("installing {} delayed. Waiting for DomainProvider", artifact);
        return false;
    }
    if (!haveConnectorFactory(configFile.getDomainType(), configFile.getConnectorType())) {
        LOGGER.info("installing {} delayed. Waiting for ConnectorFactory", artifact);
        return false;
    }
    try {
        SecurityContext.executeWithSystemPermissions(new Callable<Object>() {
            @Override
            public Object call() throws Exception {
                ConnectorDescription connectorDescription = new ConnectorDescription(configFile.getDomainType(),
                        configFile.getConnectorType(), attributes, properties);
                try {
                    serviceManager.createWithId(name, connectorDescription);
                } catch (IllegalArgumentException e) {
                    if (e.getMessage().contains("connector already exists")) {
                        return null;
                    }
                    throw e;
                }
                return null;
            }
        });
    } catch (ExecutionException e) {
        LOGGER.info("installing {} delayed", artifact);
        LOGGER.debug("installing {} failed because of Exception", artifact, e);
        return false;
    }
    return true;
}

From source file:com.streamsets.pipeline.stage.origin.jdbc.cdc.oracle.OracleCDCSource.java

private int addRecordsToQueue(LocalDateTime commitTimestamp, String commitScn, String xid)
        throws InterruptedException {
    TransactionIdKey key = new TransactionIdKey(xid);
    int seq = 0;/*from   w ww . j a va  2  s  .com*/
    bufferedRecordsLock.lock();
    HashQueue<RecordSequence> records;
    try {
        records = bufferedRecords.getOrDefault(key, EMPTY_LINKED_HASHSET);
        records.completeInserts();
        bufferedRecords.remove(key);
    } finally {
        bufferedRecordsLock.unlock();
    }
    final List<FutureWrapper> parseFutures = new ArrayList<>();
    while (!records.isEmpty()) {
        RecordSequence r = records.remove();
        if (configBean.keepOriginalQuery) {
            r.headers.put(QUERY_KEY, r.sqlString);
        }
        final Future<Record> recordFuture = parsingExecutor
                .submit(() -> generateRecord(r.sqlString, r.headers, r.opCode));
        parseFutures.add(new FutureWrapper(recordFuture, r.sqlString, r.seq));
    }
    records.close();
    LinkedList<RecordOffset> recordOffsets = new LinkedList<>();
    for (FutureWrapper recordFuture : parseFutures) {
        try {
            Record record = recordFuture.future.get();
            if (record != null) {
                final RecordOffset recordOffset = new RecordOffset(record,
                        new Offset(VERSION_UNCOMMITTED, commitTimestamp, commitScn, recordFuture.seq, xid));

                // Is this a record generated by a rollback? If it is find the previous record that matches this row id and
                // remove it from the queue.
                if (recordOffset.record.getHeader().getAttribute(ROLLBACK).equals(ONE)) {
                    String rowId = recordOffset.record.getHeader().getAttribute(ROWID_KEY);
                    Iterator<RecordOffset> reverseIter = recordOffsets.descendingIterator();
                    while (reverseIter.hasNext()) {
                        if (reverseIter.next().record.getHeader().getAttribute(ROWID_KEY).equals(rowId)) {
                            reverseIter.remove();
                            break;
                        }
                    }
                } else {
                    recordOffsets.add(recordOffset);
                }
            }
        } catch (ExecutionException e) {
            LOG.error("{}:{}", JDBC_405.getMessage(), e.getMessage(), e);
            final Throwable cause = e.getCause();
            if (cause instanceof UnparseableSQLException) {
                unparseable.offer(recordFuture.sql);
            } else {
                otherErrors.offer(new ErrorAndCause(JDBC_405, cause));
            }
        }
    }

    for (RecordOffset ro : recordOffsets) {
        try {
            seq = ro.offset.sequence;
            while (!recordQueue.offer(ro, 1, TimeUnit.SECONDS)) {
                if (getContext().isStopped()) {
                    return seq;
                }
            }
            LOG.debug(GENERATED_RECORD, ro.record, ro.record.getHeader().getAttribute(XID));
        } catch (InterruptedException ex) {
            try {
                errorRecordHandler.onError(JDBC_405, ex);
            } catch (StageException stageException) {
                addToStageExceptionsQueue(stageException);
            }
        }
    }
    return seq;
}

From source file:net.yacy.cora.protocol.http.HTTPClient.java

private void execute(final HttpUriRequest httpUriRequest, final boolean concurrent) throws IOException {
    final HttpClientContext context = HttpClientContext.create();
    context.setRequestConfig(reqConfBuilder.build());
    if (this.host != null)
        context.setTargetHost(new HttpHost(this.host));

    setHeaders(httpUriRequest);/*  w  w  w . j a v a2s. co m*/
    // statistics
    storeConnectionInfo(httpUriRequest);
    // execute the method; some asserts confirm that that the request can be send with Content-Length and is therefore not terminated by EOF
    if (httpUriRequest instanceof HttpEntityEnclosingRequest) {
        final HttpEntityEnclosingRequest hrequest = (HttpEntityEnclosingRequest) httpUriRequest;
        final HttpEntity entity = hrequest.getEntity();
        assert entity != null;
        //assert !entity.isChunked();
        //assert entity.getContentLength() >= 0;
        assert !hrequest.expectContinue();
    }

    final String initialThreadName = Thread.currentThread().getName();
    Thread.currentThread().setName("HTTPClient-" + httpUriRequest.getURI());
    final long time = System.currentTimeMillis();
    try {

        if (concurrent) {
            FutureTask<CloseableHttpResponse> t = new FutureTask<CloseableHttpResponse>(
                    new Callable<CloseableHttpResponse>() {
                        @Override
                        public CloseableHttpResponse call() throws ClientProtocolException, IOException {
                            final CloseableHttpClient client = clientBuilder.build();
                            CloseableHttpResponse response = client.execute(httpUriRequest, context);
                            return response;
                        }
                    });
            executor.execute(t);
            try {
                this.httpResponse = t.get(this.timeout, TimeUnit.MILLISECONDS);
            } catch (ExecutionException e) {
                throw e.getCause();
            } catch (Throwable e) {
            }
            try {
                t.cancel(true);
            } catch (Throwable e) {
            }
            if (this.httpResponse == null)
                throw new IOException("timout to client after " + this.timeout + "ms" + " for url "
                        + httpUriRequest.getURI().toString());
        } else {
            final CloseableHttpClient client = clientBuilder.build();
            this.httpResponse = client.execute(httpUriRequest, context);
        }
        this.httpResponse.setHeader(HeaderFramework.RESPONSE_TIME_MILLIS,
                Long.toString(System.currentTimeMillis() - time));
    } catch (final Throwable e) {
        ConnectionInfo.removeConnection(httpUriRequest.hashCode());
        httpUriRequest.abort();
        if (this.httpResponse != null)
            this.httpResponse.close();
        //e.printStackTrace();
        throw new IOException(
                "Client can't execute: " + (e.getCause() == null ? e.getMessage() : e.getCause().getMessage())
                        + " duration=" + Long.toString(System.currentTimeMillis() - time) + " for url "
                        + httpUriRequest.getURI().toString());
    } finally {
        /* Restore the thread initial name */
        Thread.currentThread().setName(initialThreadName);
    }
}