Example usage for java.net URI getPort

List of usage examples for java.net URI getPort

Introduction

In this page you can find the example usage for java.net URI getPort.

Prototype

public int getPort() 

Source Link

Document

Returns the port number of this URI.

Usage

From source file:io.pravega.test.system.ControllerRestApiTest.java

@Test(timeout = 300000)
public void restApiTests() {

    Service conService = new PravegaControllerService("controller", null, 0, 0.0, 0.0);
    List<URI> ctlURIs = conService.getServiceDetails();
    URI controllerRESTUri = ctlURIs.get(1);
    Invocation.Builder builder;/*ww  w. j a v a 2s. c  om*/
    Response response;

    restServerURI = "http://" + controllerRESTUri.getHost() + ":" + controllerRESTUri.getPort();
    log.info("REST Server URI: {}", restServerURI);

    // TEST REST server status, ping test
    resourceURl = new StringBuilder(restServerURI).append("/ping").toString();
    webTarget = client.target(resourceURl);
    builder = webTarget.request();
    response = builder.get();
    assertEquals("Ping test", OK.getStatusCode(), response.getStatus());
    log.info("REST Server is running. Ping successful.");

    final String scope1 = RandomStringUtils.randomAlphanumeric(10);
    final String stream1 = RandomStringUtils.randomAlphanumeric(10);

    // TEST CreateScope POST http://controllerURI:Port/v1/scopes
    resourceURl = new StringBuilder(restServerURI).append("/v1/scopes").toString();
    webTarget = client.target(resourceURl);
    final CreateScopeRequest createScopeRequest = new CreateScopeRequest();
    createScopeRequest.setScopeName(scope1);
    builder = webTarget.request(MediaType.APPLICATION_JSON_TYPE);
    response = builder.post(Entity.json(createScopeRequest));

    assertEquals("Create scope status", CREATED.getStatusCode(), response.getStatus());
    Assert.assertEquals("Create scope response", scope1,
            response.readEntity(ScopeProperty.class).getScopeName());
    log.info("Create scope: {} successful ", scope1);

    // TEST CreateStream POST  http://controllerURI:Port/v1/scopes/{scopeName}/streams
    resourceURl = new StringBuilder(restServerURI).append("/v1/scopes/" + scope1 + "/streams").toString();
    webTarget = client.target(resourceURl);

    CreateStreamRequest createStreamRequest = new CreateStreamRequest();
    ScalingConfig scalingConfig = new ScalingConfig();
    scalingConfig.setType(ScalingConfig.TypeEnum.FIXED_NUM_SEGMENTS);
    scalingConfig.setTargetRate(2);
    scalingConfig.scaleFactor(2);
    scalingConfig.minSegments(2);

    RetentionConfig retentionConfig = new RetentionConfig();
    retentionConfig.setType(RetentionConfig.TypeEnum.LIMITED_DAYS);
    retentionConfig.setValue(123L);

    createStreamRequest.setStreamName(stream1);
    createStreamRequest.setScalingPolicy(scalingConfig);
    createStreamRequest.setRetentionPolicy(retentionConfig);

    builder = webTarget.request(MediaType.APPLICATION_JSON_TYPE);
    response = builder.post(Entity.json(createStreamRequest));

    assertEquals("Create stream status", CREATED.getStatusCode(), response.getStatus());
    final StreamProperty streamPropertyResponse = response.readEntity(StreamProperty.class);
    assertEquals("Scope name in response", scope1, streamPropertyResponse.getScopeName());
    assertEquals("Stream name in response", stream1, streamPropertyResponse.getStreamName());
    log.info("Create stream: {} successful", stream1);

    // Test listScopes  GET http://controllerURI:Port/v1/scopes/{scopeName}/streams
    resourceURl = new StringBuilder(restServerURI).append("/v1/scopes").toString();
    webTarget = client.target(resourceURl);
    builder = webTarget.request();
    response = builder.get();
    assertEquals("List scopes", OK.getStatusCode(), response.getStatus());
    log.info("List scopes successful");

    // Test listStream GET /v1/scopes/scope1/streams
    resourceURl = new StringBuilder(restServerURI).append("/v1/scopes/" + scope1 + "/streams").toString();
    webTarget = client.target(resourceURl);
    builder = webTarget.request();
    response = builder.get();
    assertEquals("List streams", OK.getStatusCode(), response.getStatus());
    Assert.assertEquals("List streams size", 1, response.readEntity(StreamsList.class).getStreams().size());
    log.info("List streams successful");

    // Test getScope
    resourceURl = new StringBuilder(restServerURI).append("/v1/scopes/" + scope1).toString();
    response = client.target(resourceURl).request().get();
    assertEquals("Get scope status", OK.getStatusCode(), response.getStatus());
    assertEquals("Get scope scope1 response", scope1, response.readEntity(ScopeProperty.class).getScopeName());
    log.info("Get scope successful");

    // Test updateStream
    resourceURl = new StringBuilder(restServerURI).append("/v1/scopes/" + scope1 + "/streams/" + stream1)
            .toString();

    UpdateStreamRequest updateStreamRequest = new UpdateStreamRequest();
    ScalingConfig scalingConfig1 = new ScalingConfig();
    scalingConfig1.setType(ScalingConfig.TypeEnum.FIXED_NUM_SEGMENTS);
    scalingConfig1.setTargetRate(2);
    scalingConfig1.scaleFactor(3); // update existing scaleFactor from 2 to 3
    scalingConfig1.minSegments(4); // update existing minSegments from 2 to 4
    updateStreamRequest.setScalingPolicy(scalingConfig1);
    updateStreamRequest.setRetentionPolicy(retentionConfig);

    response = client.target(resourceURl).request(MediaType.APPLICATION_JSON_TYPE)
            .put(Entity.json(updateStreamRequest));
    assertEquals("Update stream status", OK.getStatusCode(), response.getStatus());
    assertEquals("Verify updated property", 4,
            response.readEntity(StreamProperty.class).getScalingPolicy().getMinSegments().intValue());
    log.info("Update stream successful");

    // Test getStream
    resourceURl = new StringBuilder(restServerURI).append("/v1/scopes/" + scope1 + "/streams/" + stream1)
            .toString();
    response = client.target(resourceURl).request().get();
    assertEquals("Get stream status", OK.getStatusCode(), response.getStatus());
    assertEquals("Get stream stream1 response", stream1,
            response.readEntity(StreamProperty.class).getStreamName());
    log.info("Get stream successful");

    // Test updateStreamState
    resourceURl = new StringBuilder(restServerURI)
            .append("/v1/scopes/" + scope1 + "/streams/" + stream1 + "/state").toString();
    StreamState streamState = new StreamState();
    streamState.setStreamState(StreamState.StreamStateEnum.SEALED);
    response = client.target(resourceURl).request(MediaType.APPLICATION_JSON_TYPE)
            .put(Entity.json(streamState));
    assertEquals("UpdateStreamState status", OK.getStatusCode(), response.getStatus());
    assertEquals("UpdateStreamState status in response", streamState.getStreamState(),
            response.readEntity(StreamState.class).getStreamState());
    log.info("Update stream state successful");

    // Test deleteStream
    resourceURl = new StringBuilder(restServerURI).append("/v1/scopes/" + scope1 + "/streams/" + stream1)
            .toString();
    response = client.target(resourceURl).request().delete();
    assertEquals("DeleteStream status", NO_CONTENT.getStatusCode(), response.getStatus());
    log.info("Delete stream successful");

    // Test deleteScope
    resourceURl = new StringBuilder(restServerURI).append("/v1/scopes/" + scope1).toString();
    response = client.target(resourceURl).request().delete();
    assertEquals("Get scope status", NO_CONTENT.getStatusCode(), response.getStatus());
    log.info("Delete Scope successful");

    // Test reader groups APIs.
    // Prepare the streams and readers using the admin client.
    final String testScope = RandomStringUtils.randomAlphanumeric(10);
    final String testStream1 = RandomStringUtils.randomAlphanumeric(10);
    final String testStream2 = RandomStringUtils.randomAlphanumeric(10);
    URI controllerUri = ctlURIs.get(0);
    try (StreamManager streamManager = new StreamManagerImpl(controllerUri)) {
        log.info("Creating scope: {}", testScope);
        streamManager.createScope(testScope);

        log.info("Creating stream: {}", testStream1);
        StreamConfiguration streamConf1 = StreamConfiguration.builder().scope(testScope).streamName(testStream1)
                .scalingPolicy(ScalingPolicy.fixed(1)).build();
        streamManager.createStream(testScope, testStream1, streamConf1);

        log.info("Creating stream: {}", testStream2);
        StreamConfiguration streamConf2 = StreamConfiguration.builder().scope(testScope).streamName(testStream2)
                .scalingPolicy(ScalingPolicy.fixed(1)).build();
        streamManager.createStream(testScope, testStream2, streamConf2);
    }

    final String readerGroupName1 = RandomStringUtils.randomAlphanumeric(10);
    final String readerGroupName2 = RandomStringUtils.randomAlphanumeric(10);
    final String reader1 = RandomStringUtils.randomAlphanumeric(10);
    final String reader2 = RandomStringUtils.randomAlphanumeric(10);
    Controller controller = new ControllerImpl(controllerUri);
    try (ClientFactory clientFactory = new ClientFactoryImpl(testScope, controller);
            ReaderGroupManager readerGroupManager = ReaderGroupManager.withScope(testScope, controllerUri)) {
        readerGroupManager.createReaderGroup(readerGroupName1,
                ReaderGroupConfig.builder().startingTime(0).build(),
                new HashSet<>(Arrays.asList(testStream1, testStream2)));
        readerGroupManager.createReaderGroup(readerGroupName2,
                ReaderGroupConfig.builder().startingTime(0).build(),
                new HashSet<>(Arrays.asList(testStream1, testStream2)));
        clientFactory.createReader(reader1, readerGroupName1, new JavaSerializer<Long>(),
                ReaderConfig.builder().build());
        clientFactory.createReader(reader2, readerGroupName1, new JavaSerializer<Long>(),
                ReaderConfig.builder().build());
    }

    // Verify the reader group info using REST APIs.
    resourceURl = new StringBuilder(restServerURI).append("/v1/scopes/" + testScope + "/readergroups")
            .toString();
    response = client.target(resourceURl).request().get();
    assertEquals("Get readergroups status", OK.getStatusCode(), response.getStatus());
    ReaderGroupsList readerGroupsList = response.readEntity(ReaderGroupsList.class);
    assertEquals("Get readergroups size", 2, readerGroupsList.getReaderGroups().size());
    assertTrue(readerGroupsList.getReaderGroups()
            .contains(new ReaderGroupsListReaderGroups().readerGroupName(readerGroupName1)));
    assertTrue(readerGroupsList.getReaderGroups()
            .contains(new ReaderGroupsListReaderGroups().readerGroupName(readerGroupName2)));
    log.info("Get readergroups successful");

    // Test fetching readergroup info.
    resourceURl = new StringBuilder(restServerURI)
            .append("/v1/scopes/" + testScope + "/readergroups/" + readerGroupName1).toString();
    response = client.target(resourceURl).request().get();
    assertEquals("Get readergroup properties status", OK.getStatusCode(), response.getStatus());
    ReaderGroupProperty readerGroupProperty = response.readEntity(ReaderGroupProperty.class);
    assertEquals("Get readergroup name", readerGroupName1, readerGroupProperty.getReaderGroupName());
    assertEquals("Get readergroup scope name", testScope, readerGroupProperty.getScopeName());
    assertEquals("Get readergroup streams size", 2, readerGroupProperty.getStreamList().size());
    assertTrue(readerGroupProperty.getStreamList().contains(testStream1));
    assertTrue(readerGroupProperty.getStreamList().contains(testStream2));
    assertEquals("Get readergroup onlinereaders size", 2, readerGroupProperty.getOnlineReaderIds().size());
    assertTrue(readerGroupProperty.getOnlineReaderIds().contains(reader1));
    assertTrue(readerGroupProperty.getOnlineReaderIds().contains(reader2));

    // Test readergroup or scope not found.
    resourceURl = new StringBuilder(restServerURI)
            .append("/v1/scopes/" + testScope + "/readergroups/" + "unknownreadergroup").toString();
    response = client.target(resourceURl).request().get();
    assertEquals("Get readergroup properties status", NOT_FOUND.getStatusCode(), response.getStatus());
    resourceURl = new StringBuilder(restServerURI)
            .append("/v1/scopes/" + "unknownscope" + "/readergroups/" + readerGroupName1).toString();
    response = client.target(resourceURl).request().get();
    assertEquals("Get readergroup properties status", NOT_FOUND.getStatusCode(), response.getStatus());
    log.info("Get readergroup properties successful");

    log.info("Test restApiTests passed successfully!");
}

From source file:com.abiquo.api.services.RemoteServiceService.java

@Transactional(propagation = Propagation.REQUIRED)
public RemoteServiceDto modifyRemoteService(final Integer id, final RemoteServiceDto dto)
        throws URISyntaxException {
    RemoteService old = getRemoteService(id);

    // check new uri
    if (org.apache.commons.lang.StringUtils.isBlank(dto.getUri())) {
        addValidationErrors(APIError.REMOTE_SERVICE_MALFORMED_URL);
        flushErrors();/*from w w  w  . j ava2 s.  c om*/
    }

    // if it's the same uri, we must check the rs to update the state
    // (it can change [stop, redis,rabbit,...])
    if (old.getUri().equals(dto.getUri())) {
        final ErrorsDto checkError = checkRemoteServiceStatus(old.getDatacenter(), dto.getType(), dto.getUri());
        if (checkError.isEmpty()) {
            old.setStatus(STATUS_SUCCESS);
            dto.setStatus(STATUS_SUCCESS);
        } else {
            old.setStatus(STATUS_ERROR);
            dto.setStatus(STATUS_ERROR);
        }
        infrastructureRepo.updateRemoteService(old);
        tracer.log(SeverityType.INFO, ComponentType.DATACENTER, EventType.REMOTE_SERVICES_UPDATE,
                "remoteServices.updated", dto.getType().getName());
        return dto;
    }

    try {
        URI uriChecked = new URI(dto.getUri());

        if (uriChecked.getPort() < 0) {
            addConflictErrors(APIError.REMOTE_SERVICE_UNDEFINED_PORT);
            flushErrors();
        } else {

            if (dto.getType().checkUniqueness()) {
                if (infrastructureRepo.existAnyRemoteServiceWithUri(dto.getUri())) {
                    addConflictErrors(APIError.REMOTE_SERVICE_URL_ALREADY_EXISTS);
                    flushErrors();
                }
            }
        }
    } catch (URISyntaxException e) {
        addConflictErrors(APIError.REMOTE_SERVICE_MALFORMED_URL);
        flushErrors();
    }

    final ErrorsDto checkError = checkRemoteServiceStatus(old.getDatacenter(), dto.getType(), dto.getUri());
    if (!checkError.isEmpty()) {
        addConflictErrors(APIError.REMOTE_SERVICE_CANNOT_BE_CHECKED);
        flushErrors();
    }

    old.setUri(dto.getUri());
    old.setType(dto.getType());
    old.setStatus(STATUS_SUCCESS);
    dto.setStatus(STATUS_SUCCESS);

    if (dto.getType() == RemoteServiceType.APPLIANCE_MANAGER) {
        checkModifyApplianceManager(old, dto);
    }

    flushErrors();

    infrastructureRepo.updateRemoteService(old);

    RemoteServiceDto responseDto = createTransferObject(old);

    tracer.log(SeverityType.INFO, ComponentType.DATACENTER, EventType.REMOTE_SERVICES_UPDATE,
            "remoteServices.updated", dto.getType().getName());

    return responseDto;
}

From source file:org.elasticsearch.xpack.security.authc.saml.SamlAuthenticationIT.java

private String getCookie(String name, HttpExchange http) throws IOException {
    try {/*  www .j  av  a2 s  .c  o m*/
        final String cookies = http.getRequestHeaders().getFirst("Cookie");
        if (cookies == null) {
            return null;
        }
        Header header = new BasicHeader("Cookie", cookies);
        final URI serverUri = getWebServerUri();
        final URI requestURI = http.getRequestURI();
        final CookieOrigin origin = new CookieOrigin(serverUri.getHost(), serverUri.getPort(),
                requestURI.getPath(), false);
        final List<Cookie> parsed = new DefaultCookieSpec().parse(header, origin);
        return parsed.stream().filter(c -> name.equals(c.getName())).map(c -> c.getValue()).findFirst()
                .orElse(null);
    } catch (MalformedCookieException e) {
        throw new IOException("Cannot read cookies", e);
    }
}

From source file:com.geoxp.oss.client.OSSClient.java

public static List<String> getACL(String ossURL, String sshKeyFingerprint, String secretName)
        throws OSSException {

    SSHAgentClient agent = null;//from   w  ww .  j a v a 2  s .co  m

    HttpClient httpclient = null;

    try {
        agent = new SSHAgentClient();

        List<SSHKey> sshkeys = agent.requestIdentities();

        //
        // If no SSH Key fingerprint was provided, try all SSH keys available in the agent
        //

        List<String> fingerprints = new ArrayList<String>();

        if (null == sshKeyFingerprint) {
            for (SSHKey key : sshkeys) {
                fingerprints.add(key.fingerprint);
            }
        } else {
            fingerprints.add(sshKeyFingerprint.toLowerCase().replaceAll("[^0-9a-f]", ""));
        }

        int idx = 0;

        for (String fingerprint : fingerprints) {
            idx++;

            //
            // Check if the signing key is available in the agent
            //

            byte[] keyblob = null;

            for (SSHKey key : sshkeys) {
                if (key.fingerprint.equals(fingerprint)) {
                    keyblob = key.blob;
                    break;
                }
            }

            //
            // Throw an exception if this condition is encountered as it can only happen if
            // there was a provided fingerprint which is not in the agent.
            //

            if (null == keyblob) {
                throw new OSSException("SSH Key " + sshKeyFingerprint + " was not found by your SSH agent.");
            }

            //
            // Generate temporary RSA key pair
            //

            RSAKeyPairGenerator rsagen = new RSAKeyPairGenerator();
            RSAKeyGenerationParameters params = new RSAKeyGenerationParameters(new BigInteger("65537"),
                    CryptoHelper.getSecureRandom(), OSS.DEFAULT_RSA_STRENGTH, 64);
            rsagen.init(params);
            final AsymmetricCipherKeyPair keypair = rsagen.generateKeyPair();

            RSAPrivateKey rsapriv = new RSAPrivateKey() {
                public BigInteger getModulus() {
                    return ((RSAKeyParameters) keypair.getPrivate()).getModulus();
                }

                public String getFormat() {
                    return "PKCS#8";
                }

                public byte[] getEncoded() {
                    return null;
                }

                public String getAlgorithm() {
                    return "RSA";
                }

                public BigInteger getPrivateExponent() {
                    return ((RSAKeyParameters) keypair.getPrivate()).getExponent();
                }
            };

            RSAPublicKey rsapub = new RSAPublicKey() {
                public BigInteger getModulus() {
                    return ((RSAKeyParameters) keypair.getPublic()).getModulus();
                }

                public String getFormat() {
                    return "PKCS#8";
                }

                public byte[] getEncoded() {
                    return null;
                }

                public String getAlgorithm() {
                    return "RSA";
                }

                public BigInteger getPublicExponent() {
                    return ((RSAKeyParameters) keypair.getPublic()).getExponent();
                }
            };

            //
            // Build OSS Token
            //
            // <TS> <<SECRET_NAME> <RSA_ENC_KEY>> <SSH Signing Key Blob> <SSH Signature Blob>
            //

            ByteArrayOutputStream token = new ByteArrayOutputStream();

            byte[] tsdata = nowBytes();

            token.write(CryptoHelper.encodeNetworkString(tsdata));

            ByteArrayOutputStream subtoken = new ByteArrayOutputStream();

            subtoken.write(CryptoHelper.encodeNetworkString(secretName.getBytes("UTF-8")));
            subtoken.write(CryptoHelper.encodeNetworkString(CryptoHelper.sshKeyBlobFromPublicKey(rsapub)));

            token.write(CryptoHelper.encodeNetworkString(subtoken.toByteArray()));

            token.write(CryptoHelper.encodeNetworkString(keyblob));

            //
            // Generate signature
            //

            byte[] sigblob = agent.sign(keyblob, token.toByteArray());

            token.write(CryptoHelper.encodeNetworkString(sigblob));

            String b64token = new String(Base64.encode(token.toByteArray()), "UTF-8");

            //
            // Send request
            //

            httpclient = newHttpClient();

            URIBuilder builder = new URIBuilder(ossURL + GuiceServletModule.SERVLET_PATH_GET_ACL);

            builder.addParameter("token", b64token);

            URI uri = builder.build();

            String qs = uri.getRawQuery();

            HttpPost post = new HttpPost(
                    uri.getScheme() + "://" + uri.getHost() + ":" + uri.getPort() + uri.getPath());

            post.setHeader("Content-Type", "application/x-www-form-urlencoded");

            post.setEntity(new StringEntity(qs));

            HttpResponse response = httpclient.execute(post);
            HttpEntity resEntity = response.getEntity();
            String content = EntityUtils.toString(resEntity, "UTF-8");
            post.reset();

            if (HttpServletResponse.SC_OK != response.getStatusLine().getStatusCode()) {
                // Only throw an exception if this is the last SSH key we could try
                if (idx == fingerprints.size()) {
                    throw new OSSException("None of the provided keys (" + idx
                            + ") could be used to retrieve ACLs. Latest error message was: "
                            + response.getStatusLine().getReasonPhrase());
                } else {
                    continue;
                }
            }

            //
            // Extract encrypted list of fingerprints and sealed key
            //

            byte[] fprandsealedkey = Base64.decode(content);

            byte[] encryptedfpr = CryptoHelper.decodeNetworkString(fprandsealedkey, 0);
            byte[] sealedkey = CryptoHelper.decodeNetworkString(fprandsealedkey, 4 + encryptedfpr.length);

            //
            // Unseal key
            //

            byte[] wrappingkey = CryptoHelper.decryptRSA(rsapriv, sealedkey);

            //
            // Unwrap fingerprints
            //

            byte[] fpr = CryptoHelper.unwrapAES(wrappingkey, encryptedfpr);

            int offset = 0;

            List<String> res = new ArrayList<String>();

            while (offset < fpr.length) {
                byte[] f = CryptoHelper.decodeNetworkString(fpr, offset);

                if (null == f) {
                    break;
                }

                offset += 4 + f.length;

                if (0 < f.length) {
                    res.add(new String(Hex.encode(f), "UTF-8").replaceAll("([0-9a-f]{2})", "$1:"));
                }
            }

            return res;
        }
    } catch (OSSException osse) {
        throw osse;
    } catch (Exception e) {
        throw new OSSException(e);
    } finally {
        if (null != httpclient) {
            httpclient.getConnectionManager().shutdown();
        }
        if (null != agent) {
            agent.close();
        }
    }

    return null;
}

From source file:org.apache.openmeetings.service.calendar.caldav.AppointmentManager.java

/**
 * Adds the Credentials provided to the given client on the Calendar's URL.
 *
 * @param context     Context of the Client which makes the connection.
 * @param calendar    Calendar whose Host the Credentials are for.
 * @param credentials Credentials to add
 *///from w w w . j  av a  2s  .c  o m
public void provideCredentials(HttpClientContext context, OmCalendar calendar, Credentials credentials) {
    // Done through creating a new Local context
    if (!Strings.isEmpty(calendar.getHref()) && credentials != null) {
        URI temp = URI.create(calendar.getHref());
        context.getCredentialsProvider().setCredentials(new AuthScope(temp.getHost(), temp.getPort()),
                credentials);
    }
}

From source file:org.apache.sling.etcd.client.impl.EtcdClientImpl.java

@Nonnull
private URI buildUri(@Nonnull URI endpoint, @Nonnull String path, @Nonnull Map<String, String> parameters) {
    try {/*from w  w w .  j a va 2  s .  co m*/
        URIBuilder builder = new URIBuilder();
        for (Map.Entry<String, String> p : parameters.entrySet()) {
            builder.setParameter(p.getKey(), p.getValue());
        }
        return builder.setScheme(endpoint.getScheme()).setHost(endpoint.getHost()).setPort(endpoint.getPort())
                .setPath(path).build();
    } catch (URISyntaxException e) {
        throw new EtcdException(e.getMessage(), e);
    }
}

From source file:com.altiscale.TcpProxy.HostPort.java

public HostPort parseServerString(String server) throws URISyntaxException {
    URI uri = new URI("my://" + server);
    String host = uri.getHost();// w  w w  .j  ava2  s.co  m
    int port = uri.getPort();
    if (uri.getHost() == null) {
        throw new URISyntaxException(uri.toString(), "URI must have at least a hostname.");
    }
    // Library sets port to -1 if it was missing in String server.
    return new HostPort(host, port);
}

From source file:com.cisco.oss.foundation.http.apache.ApacheHttpClient.java

@Override
public HttpResponse executeDirect(HttpRequest request) {

    org.apache.http.HttpRequest httpRequest = null;

    Joiner joiner = Joiner.on(",").skipNulls();
    URI requestUri = buildUri(request, joiner);

    httpRequest = buildHttpUriRequest(request, joiner, requestUri);

    try {/*w  ww .j  a  v a 2  s  .  c  o  m*/
        //            LOGGER.info("sending request: {}", request.getUri());

        HttpHost httpHost = new HttpHost(requestUri.getHost(), requestUri.getPort(), requestUri.getScheme());
        HttpContext httpContext = HTTP_CONTEXT_THREAD_LOCAL.get();
        CloseableHttpResponse response = httpContext == null ? httpClient.execute(httpHost, httpRequest)
                : httpClient.execute(httpHost, httpRequest, httpContext);
        ApacheHttpResponse apacheHttpResponse = new ApacheHttpResponse(response, requestUri, autoCloseable);
        //            LOGGER.info("got response status: {} for request: {}",apacheHttpResponse.getStatus(), apacheHttpResponse.getRequestedURI());
        return apacheHttpResponse;
    } catch (IOException e) {
        throw new ClientException(e.toString(), e);
    }
}

From source file:org.apache.jena.atlas.web.auth.PreemptiveBasicAuthenticator.java

@Override
public void apply(AbstractHttpClient client, HttpContext httpContext, URI target) {
    this.authenticator.apply(client, httpContext, target);

    // Enable preemptive basic authentication
    // For nice layering we need to respect existing auth cache if present
    AuthCache authCache = (AuthCache) httpContext.getAttribute(ClientContext.AUTH_CACHE);
    if (authCache == null)
        authCache = new BasicAuthCache();
    BasicScheme basicAuth = new BasicScheme(this.isProxy ? ChallengeState.PROXY : ChallengeState.TARGET);
    // TODO It is possible that this overwrites existing cached credentials
    // so potentially not ideal.
    authCache.put(new HttpHost(target.getHost(), target.getPort()), basicAuth);
    httpContext.setAttribute(ClientContext.AUTH_CACHE, authCache);
}