org.springframework.remoting.httpinvoker.HttpInvokerClientConfiguration Java Examples

The following examples show how to use org.springframework.remoting.httpinvoker.HttpInvokerClientConfiguration. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AuthenticationCommonsHttpInvokerRequestExecutor.java    From rice with Educational Community License v2.0 6 votes vote down vote up
/**
 * Overridden to obtain the Credentials from the CredentialsSource and pass
 * them via HTTP BASIC Authorization.
 */

protected void setRequestBody(final HttpInvokerClientConfiguration config,
    final HttpPost httpPost, final ByteArrayOutputStream baos) throws IOException {
	final UsernamePasswordCredentials credentials = (UsernamePasswordCredentials) this.credentialsSource.getCredentials(this.serviceConfiguration.getEndpointUrl().toExternalForm());

    final String base64 = credentials.getUsername() + ":"
    + credentials.getPassword();
    httpPost.addHeader("Authorization", "Basic " + new String(Base64.encodeBase64(base64.getBytes())));

    if (logger.isDebugEnabled()) {
        logger
            .debug("HttpInvocation now presenting via BASIC authentication CredentialsSource-derived: "
                + credentials.getUsername());
    }
    
    super.setRequestBody(config, httpPost, baos);
}
 
Example #2
Source File: GoHttpClientHttpInvokerRequestExecutor.java    From gocd with Apache License 2.0 6 votes vote down vote up
@Override
protected RemoteInvocationResult doExecuteRequest(HttpInvokerClientConfiguration config, ByteArrayOutputStream baos) throws Exception {
    HttpPost postMethod = new HttpPost(config.getServiceUrl());

    ByteArrayEntity entity = new ByteArrayEntity(baos.toByteArray());
    entity.setContentType(getContentType());
    postMethod.setEntity(entity);

    BasicHttpContext context = null;

    postMethod.setHeader("X-Agent-GUID", defaultAgentRegistry.uuid());
    postMethod.setHeader("Authorization", defaultAgentRegistry.token());

    try (CloseableHttpResponse response = goAgentServerHttpClient.execute(postMethod, context)) {
        validateResponse(response);
        try (InputStream responseBody = getResponseBody(response)) {
            return readRemoteInvocationResult(responseBody, config.getCodebaseUrl());
        }
    }
}
 
Example #3
Source File: KSBHttpInvokerRequestExecutor.java    From rice with Educational Community License v2.0 5 votes vote down vote up
/**
 * Signs the outgoing request by generating a digital signature from the bytes in the ByteArrayOutputStream and attaching the
 * signature and our alias to the headers of the PostMethod.
 */
@Override
protected void setRequestBody(HttpInvokerClientConfiguration config, HttpPost httpPost, ByteArrayOutputStream baos) throws IOException {
    if (isSecure()) {
        try {
            signRequest(httpPost, baos);
        } catch (Exception e) {
            throw new RuntimeException("Failed to sign the outgoing message.", e);
        }
    }
    super.setRequestBody(config, httpPost, baos);
}
 
Example #4
Source File: KSBHttpInvokerRequestExecutor.java    From rice with Educational Community License v2.0 5 votes vote down vote up
@Override
protected void validateResponse(HttpInvokerClientConfiguration config, HttpResponse response) throws HttpException {
    int statusCode = response.getStatusLine().getStatusCode();

    // HTTP status codes in the 200-299 range indicate success
    if (statusCode >= HttpStatus.SC_MULTIPLE_CHOICES /* 300 */) {
        throw new HttpException(statusCode, "Did not receive successful HTTP response: status code = " + statusCode +
                ", status message = [" + response.getStatusLine().getReasonPhrase() + "]");
    }
}
 
Example #5
Source File: ClusteredHttpInvokerRequestExecutor.java    From cuba with Apache License 2.0 4 votes vote down vote up
@Override
protected RemoteInvocationResult doExecuteRequest(HttpInvokerClientConfiguration config, ByteArrayOutputStream baos)
        throws IOException, ClassNotFoundException {

    RemoteInvocationResult result;

    Object context = serverSelector.initContext();
    String url = currentServiceUrl(serverSelector.getUrl(context), config);
    if (url == null)
        throw new IllegalStateException("Server URL list is empty");

    while (true) {
        HttpURLConnection con = openConnection(url);
        try {
            StopWatch sw = new StopWatch();
            prepareConnection(con, baos.size());
            writeRequestBody(config, con, baos);
            sw.start("waiting time");
            validateResponse(config, con);
            CountingInputStream responseInputStream = new CountingInputStream(readResponseBody(config, con));
            sw.stop();

            serverSelector.success(context);

            sw.start("reading time");
            try (ObjectInputStream ois = createObjectInputStream(decorateInputStream(responseInputStream), config.getCodebaseUrl())) {
                result = doReadRemoteInvocationResult(ois);
            }
            sw.stop();
            if (log.isDebugEnabled()) {
                log.debug(String.format("Receiving HTTP invoker response for service at [%s], with size %s, %s", config.getServiceUrl(),
                        responseInputStream.getCount(), printStopWatch(sw)));
            }
            break;
        } catch (IOException e) {
            log.info(String.format("Invocation of %s failed: %s", url, e));

            serverSelector.fail(context);
            url = currentServiceUrl(serverSelector.getUrl(context), config);
            if (url != null) {
                log.info("Trying to invoke the next available URL: " + url);
                continue;
            }
            log.info("No more URL available");
            throw e;
        }
    }
    return result;
}
 
Example #6
Source File: ClusteredHttpInvokerRequestExecutor.java    From cuba with Apache License 2.0 4 votes vote down vote up
@Nullable
protected String currentServiceUrl(String url, HttpInvokerClientConfiguration config) {
    return url == null ? null :  url + "/" + config.getServiceUrl();
}
 
Example #7
Source File: KSBHttpInvokerRequestExecutor.java    From rice with Educational Community License v2.0 4 votes vote down vote up
/**
 * Returns a wrapped InputStream which is responsible for verifying the digital signature on the response after all
 * data has been read.
 */
@Override
protected InputStream getResponseBody(HttpInvokerClientConfiguration config, HttpResponse postMethod) throws IOException {
    if (isSecure()) {
        // extract and validate the headers
        Header digitalSignatureHeader = postMethod.getFirstHeader(KSBConstants.DIGITAL_SIGNATURE_HEADER);
        Header keyStoreAliasHeader = postMethod.getFirstHeader(KSBConstants.KEYSTORE_ALIAS_HEADER);
        Header certificateHeader = postMethod.getFirstHeader(KSBConstants.KEYSTORE_CERTIFICATE_HEADER);

        if (digitalSignatureHeader == null || StringUtils.isEmpty(digitalSignatureHeader.getValue())) {
            throw new RuntimeException("A digital signature header was required on the response but none was found.");
        }

        boolean foundValidKeystoreAlias = (keyStoreAliasHeader != null && StringUtils.isNotBlank(keyStoreAliasHeader.getValue()));
        boolean foundValidCertificate = (certificateHeader != null && StringUtils.isNotBlank(certificateHeader.getValue()));

        if (!foundValidCertificate && !foundValidKeystoreAlias) {
            throw new RuntimeException("Either a key store alias header or a certificate header was required on the response but neither were found.");
        }

        // decode the digital signature from the header into binary
        byte[] digitalSignature = Base64.decodeBase64(digitalSignatureHeader.getValue().getBytes("UTF-8"));
        String errorQualifier = "General Security Error";

        try {
            Signature signature = null;

            if (foundValidCertificate) {
                errorQualifier = "Error with given certificate";
                // get the Signature for verification based on the alias that was sent to us
                byte[] encodedCertificate = Base64.decodeBase64(certificateHeader.getValue().getBytes("UTF-8"));
                CertificateFactory cf = CertificateFactory.getInstance("X.509");
                signature = getDigitalSignatureService().getSignatureForVerification(cf.generateCertificate(new ByteArrayInputStream(encodedCertificate)));
            } else if (foundValidKeystoreAlias) {
                // get the Signature for verification based on the alias that was sent to us
                String keystoreAlias = keyStoreAliasHeader.getValue();
                errorQualifier = "Error with given alias " + keystoreAlias;
                signature = getDigitalSignatureService().getSignatureForVerification(keystoreAlias);
            }

            // wrap the InputStream in an input stream that will verify the signature
            return new SignatureVerifyingInputStream(digitalSignature, signature, super.getResponseBody(config, postMethod));
        } catch (GeneralSecurityException e) {
            throw new RuntimeException("Problem verifying signature: " + errorQualifier,e);
        }
    }

    return super.getResponseBody(config, postMethod);
}