List of usage examples for org.apache.http.client.protocol HttpClientContext create
public static HttpClientContext create()
From source file:org.sonatype.nexus.plugins.crowd.client.rest.RestClient.java
/** * Authenticates a user with crowd. If authentication failed, raises a <code>RemoteException</code> * //www. ja v a 2 s .c o m * @param username * @param password * @return session token * @throws RemoteException */ public void authenticate(String username, String password) throws RemoteException { HttpClientContext hc = HttpClientContext.create(); HttpPost post = new HttpPost(crowdServer.resolve("authentication?username=" + urlEncode(username))); if (LOG.isDebugEnabled()) { LOG.debug("authentication attempt for '{}'", username); LOG.debug(post.getURI().toString()); } AuthenticatePost creds = new AuthenticatePost(); creds.value = password; try { acceptXmlResponse(post); StringWriter writer = new StringWriter(); JAXB.marshal(creds, writer); post.setEntity(EntityBuilder.create().setText(writer.toString()) .setContentType(ContentType.APPLICATION_XML).setContentEncoding("UTF-8").build()); enablePreemptiveAuth(post, hc); HttpResponse response = client.execute(post); if (response.getStatusLine().getStatusCode() != 200) { handleHTTPError(response); } } catch (IOException | AuthenticationException ioe) { handleError(ioe); } finally { post.releaseConnection(); } }
From source file:edu.lternet.pasta.client.LoginClient.java
/** * Perform a PASTA login operation using the user's credentials. Because there * is not a formal PASTA login method, we will use a simple query for the Data * Package Manager service, which will perform the necessary user * authentication (this step should be replaced with a formal PASTA * "login service method").//from w ww .j a v a 2 s . c o m * * @param uid * The user identifier. * @param password * The user password. * * @return The authentication token as a String object if the login is * successful. */ private String login(String uid, String password) { String token = null; String username = PastaClient.composeDistinguishedName(uid); /* * The following set of code sets up Preemptive Authentication for the HTTP * CLIENT and is done so at the warning stated within the Apache * Http-Components Client tutorial here: * http://hc.apache.org/httpcomponents- * client-ga/tutorial/html/authentication.html#d5e1031 */ // Define host parameters HttpHost httpHost = new HttpHost(this.pastaHost, this.pastaPort, this.pastaProtocol); CloseableHttpClient httpClient = HttpClientBuilder.create().build(); // Define user authentication credentials that will be used with the host AuthScope authScope = new AuthScope(httpHost.getHostName(), httpHost.getPort()); UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password); CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(authScope, credentials); // Create AuthCache instance AuthCache authCache = new BasicAuthCache(); // Generate BASIC scheme object and add it to the local auth cache BasicScheme basicAuth = new BasicScheme(); authCache.put(httpHost, basicAuth); // Add AuthCache to the execution context HttpClientContext context = HttpClientContext.create(); context.setCredentialsProvider(credentialsProvider); context.setAuthCache(authCache); HttpGet httpGet = new HttpGet(this.LOGIN_URL); HttpResponse response = null; Header[] headers = null; Integer statusCode = null; try { response = httpClient.execute(httpHost, httpGet, context); headers = response.getAllHeaders(); statusCode = (Integer) response.getStatusLine().getStatusCode(); logger.info("STATUS: " + statusCode.toString()); } catch (UnsupportedEncodingException e) { logger.error(e); e.printStackTrace(); } catch (ClientProtocolException e) { logger.error(e); e.printStackTrace(); } catch (IOException e) { logger.error(e); e.printStackTrace(); } finally { closeHttpClient(httpClient); } if (statusCode == HttpStatus.SC_OK) { String headerName = null; String headerValue = null; // Loop through all headers looking for the "Set-Cookie" header. for (int i = 0; i < headers.length; i++) { headerName = headers[i].getName(); if (headerName.equals("Set-Cookie")) { headerValue = headers[i].getValue(); token = this.getAuthToken(headerValue); } } } return token; }
From source file:org.apache.syncope.installer.utilities.HttpUtils.java
private HttpClientContext setAuth(final HttpHost targetHost, final AuthScheme authScheme) { final CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()), new UsernamePasswordCredentials(username, password)); final HttpClientContext context = HttpClientContext.create(); final AuthCache authCache = new BasicAuthCache(); authCache.put(targetHost, authScheme); context.setAuthCache(authCache);// w w w. j a v a 2 s .c o m context.setCredentialsProvider(credsProvider); return context; }
From source file:org.elasticsearch.xpack.watcher.common.http.HttpClient.java
public HttpResponse execute(HttpRequest request) throws IOException { URI uri = createURI(request); HttpRequestBase internalRequest;// www . ja v a 2 s . co m if (request.method == HttpMethod.HEAD) { internalRequest = new HttpHead(uri); } else { HttpMethodWithEntity methodWithEntity = new HttpMethodWithEntity(uri, request.method.name()); if (request.hasBody()) { ByteArrayEntity entity = new ByteArrayEntity(request.body.getBytes(StandardCharsets.UTF_8)); String contentType = request.headers().get(HttpHeaders.CONTENT_TYPE); if (Strings.hasLength(contentType)) { entity.setContentType(contentType); } else { entity.setContentType(ContentType.TEXT_PLAIN.toString()); } methodWithEntity.setEntity(entity); } internalRequest = methodWithEntity; } internalRequest.setHeader(HttpHeaders.ACCEPT_CHARSET, StandardCharsets.UTF_8.name()); // headers if (request.headers().isEmpty() == false) { for (Map.Entry<String, String> entry : request.headers.entrySet()) { internalRequest.setHeader(entry.getKey(), entry.getValue()); } } // BWC - hack for input requests made to elasticsearch that do not provide the right content-type header! if (request.hasBody() && internalRequest.containsHeader("Content-Type") == false) { XContentType xContentType = XContentFactory.xContentType(request.body()); if (xContentType != null) { internalRequest.setHeader("Content-Type", xContentType.mediaType()); } } RequestConfig.Builder config = RequestConfig.custom(); setProxy(config, request, settingsProxy); HttpClientContext localContext = HttpClientContext.create(); // auth if (request.auth() != null) { ApplicableHttpAuth applicableAuth = httpAuthRegistry.createApplicable(request.auth); CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); applicableAuth.apply(credentialsProvider, new AuthScope(request.host, request.port)); localContext.setCredentialsProvider(credentialsProvider); // preemptive auth, no need to wait for a 401 first AuthCache authCache = new BasicAuthCache(); BasicScheme basicAuth = new BasicScheme(); authCache.put(new HttpHost(request.host, request.port, request.scheme.scheme()), basicAuth); localContext.setAuthCache(authCache); } // timeouts if (request.connectionTimeout() != null) { config.setConnectTimeout(Math.toIntExact(request.connectionTimeout.millis())); } else { config.setConnectTimeout(Math.toIntExact(defaultConnectionTimeout.millis())); } if (request.readTimeout() != null) { config.setSocketTimeout(Math.toIntExact(request.readTimeout.millis())); config.setConnectionRequestTimeout(Math.toIntExact(request.readTimeout.millis())); } else { config.setSocketTimeout(Math.toIntExact(defaultReadTimeout.millis())); config.setConnectionRequestTimeout(Math.toIntExact(defaultReadTimeout.millis())); } internalRequest.setConfig(config.build()); try (CloseableHttpResponse response = SocketAccess .doPrivileged(() -> client.execute(internalRequest, localContext))) { // headers Header[] headers = response.getAllHeaders(); Map<String, String[]> responseHeaders = new HashMap<>(headers.length); for (Header header : headers) { if (responseHeaders.containsKey(header.getName())) { String[] old = responseHeaders.get(header.getName()); String[] values = new String[old.length + 1]; System.arraycopy(old, 0, values, 0, old.length); values[values.length - 1] = header.getValue(); responseHeaders.put(header.getName(), values); } else { responseHeaders.put(header.getName(), new String[] { header.getValue() }); } } final byte[] body; // not every response has a content, i.e. 204 if (response.getEntity() == null) { body = new byte[0]; } else { try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) { try (InputStream is = new SizeLimitInputStream(maxResponseSize, response.getEntity().getContent())) { Streams.copy(is, outputStream); } body = outputStream.toByteArray(); } } return new HttpResponse(response.getStatusLine().getStatusCode(), body, responseHeaders); } }
From source file:org.keycloak.testsuite.saml.LogoutTest.java
@Test public void testLogoutDifferentBrowser() throws ParsingException, ConfigurationException, ProcessingException { // This is in fact the same as admin logging out a session from admin console. // This always succeeds as it is essentially the same as backend logout which // does not report errors to client but only to the server log adminClient.realm(REALM_NAME).clients().get(sales2Rep.getId()) .update(ClientBuilder.edit(sales2Rep).frontchannelLogout(false) .attribute(SamlProtocol.SAML_SINGLE_LOGOUT_SERVICE_URL_POST_ATTRIBUTE, "") .removeAttribute(SamlProtocol.SAML_SINGLE_LOGOUT_SERVICE_URL_REDIRECT_ATTRIBUTE).build()); Document logoutDoc = prepareLogoutFromSalesAfterLoggingIntoTwoApps(); samlClient.execute((client, context, strategy) -> { HttpUriRequest post = POST.createSamlUnsignedRequest(getAuthServerSamlEndpoint(REALM_NAME), null, logoutDoc);/* w w w . j a va 2s . c o m*/ CloseableHttpResponse response = client.execute(post, HttpClientContext.create()); assertThat(response, statusCodeIsHC(Response.Status.OK)); return response; }); }
From source file:com.ibm.ws.lars.rest.RepositoryContext.java
@Override protected void before() throws InvalidJsonAssetException, IOException, KeyManagementException, NoSuchAlgorithmException, KeyStoreException { targetHost = new HttpHost(hostname, portNumber, protocol); /* Create the HTTPClient that we use to make all HTTP calls */ HttpClientBuilder b = HttpClientBuilder.create(); // Trust all certificates SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() { @Override//w w w .j a v a 2 s . c om public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { return true; } }).build(); b.setSslcontext(sslContext); // By default, it will verify the hostname in the certificate, which should be localhost // and therefore should match. If we start running these tests against a LARS server on // a different host then we may need disable hostname verification. context = HttpClientContext.create(); httpClient = b.build(); /* * Create the HTTPClientContext with the appropriate credentials. We'll use this whenever we * make an HTTP call. */ if (user != null && password != null) { credentials = new UsernamePasswordCredentials(user, password); CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()), credentials); AuthCache authCache = new BasicAuthCache(); BasicScheme basicAuth = new BasicScheme(); authCache.put(targetHost, basicAuth); context.setCredentialsProvider(credsProvider); context.setAuthCache(authCache); } /* Clean the repository but only if the client asked us to. */ if (cleanRepository) { cleanRepo(); } }
From source file:org.apache.sling.discovery.base.connectors.ping.TopologyConnectorClient.java
/** ping the server and pass the announcements between the two **/ void ping(final boolean force) { if (autoStopped) { // then we suppress any further pings! logger.debug("ping: autoStopped=true, hence suppressing any further pings."); return;//from w w w . ja v a 2s . c o m } if (force) { backoffPeriodEnd = -1; } else if (backoffPeriodEnd > 0) { if (System.currentTimeMillis() < backoffPeriodEnd) { logger.debug("ping: not issueing a heartbeat due to backoff instruction from peer."); return; } else { logger.debug("ping: backoff period ended, issuing another ping now."); } } final String uri = connectorUrl.toString() + "." + clusterViewService.getSlingId() + ".json"; if (logger.isDebugEnabled()) { logger.debug("ping: connectorUrl=" + connectorUrl + ", complete uri=" + uri); } final HttpClientContext clientContext = HttpClientContext.create(); final CloseableHttpClient httpClient = createHttpClient(); final HttpPut putRequest = new HttpPut(uri); // setting the connection timeout (idle connection, configured in seconds) putRequest.setConfig( RequestConfig.custom().setConnectTimeout(1000 * config.getSocketConnectTimeout()).build()); Announcement resultingAnnouncement = null; try { String userInfo = connectorUrl.getUserInfo(); if (userInfo != null) { Credentials c = new UsernamePasswordCredentials(userInfo); clientContext.getCredentialsProvider().setCredentials( new AuthScope(putRequest.getURI().getHost(), putRequest.getURI().getPort()), c); } Announcement topologyAnnouncement = new Announcement(clusterViewService.getSlingId()); topologyAnnouncement.setServerInfo(serverInfo); final ClusterView clusterView; try { clusterView = clusterViewService.getLocalClusterView(); } catch (UndefinedClusterViewException e) { // SLING-5030 : then we cannot ping logger.warn("ping: no clusterView available at the moment, cannot ping others now: " + e); return; } topologyAnnouncement.setLocalCluster(clusterView); if (force) { logger.debug("ping: sending a resetBackoff"); topologyAnnouncement.setResetBackoff(true); } announcementRegistry.addAllExcept(topologyAnnouncement, clusterView, new AnnouncementFilter() { public boolean accept(final String receivingSlingId, final Announcement announcement) { // filter out announcements that are of old cluster instances // which I dont really have in my cluster view at the moment final Iterator<InstanceDescription> it = clusterView.getInstances().iterator(); while (it.hasNext()) { final InstanceDescription instance = it.next(); if (instance.getSlingId().equals(receivingSlingId)) { // then I have the receiving instance in my cluster view // all fine then return true; } } // looks like I dont have the receiving instance in my cluster view // then I should also not propagate that announcement anywhere return false; } }); final String p = requestValidator.encodeMessage(topologyAnnouncement.asJSON()); if (logger.isDebugEnabled()) { logger.debug("ping: topologyAnnouncement json is: " + p); } requestValidator.trustMessage(putRequest, p); if (config.isGzipConnectorRequestsEnabled()) { // tell the server that the content is gzipped: putRequest.addHeader("Content-Encoding", "gzip"); // and gzip the body: final ByteArrayOutputStream baos = new ByteArrayOutputStream(); final GZIPOutputStream gzipOut = new GZIPOutputStream(baos); gzipOut.write(p.getBytes("UTF-8")); gzipOut.close(); final byte[] gzippedEncodedJson = baos.toByteArray(); putRequest.setEntity(new ByteArrayEntity(gzippedEncodedJson, ContentType.APPLICATION_JSON)); lastRequestEncoding = "gzip"; } else { // otherwise plaintext: final StringEntity plaintext = new StringEntity(p, "UTF-8"); plaintext.setContentType(ContentType.APPLICATION_JSON.getMimeType()); putRequest.setEntity(plaintext); lastRequestEncoding = "plaintext"; } // independent of request-gzipping, we do accept the response to be gzipped, // so indicate this to the server: putRequest.addHeader("Accept-Encoding", "gzip"); final CloseableHttpResponse response = httpClient.execute(putRequest, clientContext); if (logger.isDebugEnabled()) { logger.debug("ping: done. code=" + response.getStatusLine().getStatusCode() + " - " + response.getStatusLine().getReasonPhrase()); } lastStatusCode = response.getStatusLine().getStatusCode(); lastResponseEncoding = null; if (response.getStatusLine().getStatusCode() == HttpServletResponse.SC_OK) { final Header contentEncoding = response.getFirstHeader("Content-Encoding"); if (contentEncoding != null && contentEncoding.getValue() != null && contentEncoding.getValue().contains("gzip")) { lastResponseEncoding = "gzip"; } else { lastResponseEncoding = "plaintext"; } final String responseBody = requestValidator.decodeMessage(putRequest.getURI().getPath(), response); // limiting to 16MB, should be way enough if (logger.isDebugEnabled()) { logger.debug("ping: response body=" + responseBody); } if (responseBody != null && responseBody.length() > 0) { Announcement inheritedAnnouncement = Announcement.fromJSON(responseBody); final long backoffInterval = inheritedAnnouncement.getBackoffInterval(); if (backoffInterval > 0) { // then reset the backoffPeriodEnd: /* minus 1 sec to avoid slipping the interval by a few millis */ this.backoffPeriodEnd = System.currentTimeMillis() + (1000 * backoffInterval) - 1000; logger.debug("ping: servlet instructed to backoff: backoffInterval=" + backoffInterval + ", resulting in period end of " + new Date(backoffPeriodEnd)); } else { logger.debug("ping: servlet did not instruct any backoff-ing at this stage"); this.backoffPeriodEnd = -1; } if (inheritedAnnouncement.isLoop()) { if (logger.isDebugEnabled()) { logger.debug( "ping: connector response indicated a loop detected. not registering this announcement from " + inheritedAnnouncement.getOwnerId()); } if (inheritedAnnouncement.getOwnerId().equals(clusterViewService.getSlingId())) { // SLING-3316 : local-loop detected. Check config to see if we should stop this connector if (config.isAutoStopLocalLoopEnabled()) { inheritedAnnouncement = null; // results in connected -> false and representsloop -> true autoStopped = true; // results in isAutoStopped -> true } } } else { inheritedAnnouncement.setInherited(true); if (announcementRegistry.registerAnnouncement(inheritedAnnouncement) == -1) { if (logger.isDebugEnabled()) { logger.debug( "ping: connector response is from an instance which I already see in my topology" + inheritedAnnouncement); } statusDetails = "receiving side is seeing me via another path (connector or cluster) already (loop)"; return; } } resultingAnnouncement = inheritedAnnouncement; statusDetails = null; } else { statusDetails = "no response body received"; } } else { statusDetails = "got HTTP Status-Code: " + lastStatusCode; } // SLING-2882 : reset suppressPingWarnings_ flag in success case suppressPingWarnings_ = false; } catch (IOException e) { // SLING-2882 : set/check the suppressPingWarnings_ flag if (suppressPingWarnings_) { if (logger.isDebugEnabled()) { logger.debug("ping: got IOException: " + e + ", uri=" + uri); } } else { suppressPingWarnings_ = true; logger.warn("ping: got IOException [suppressing further warns]: " + e + ", uri=" + uri); } statusDetails = e.toString(); } catch (JSONException e) { logger.warn("ping: got JSONException: " + e); statusDetails = e.toString(); } catch (RuntimeException re) { logger.warn("ping: got RuntimeException: " + re, re); statusDetails = re.toString(); } finally { putRequest.releaseConnection(); lastInheritedAnnouncement = resultingAnnouncement; lastPingedAt = System.currentTimeMillis(); try { httpClient.close(); } catch (IOException e) { logger.error("disconnect: could not close httpClient: " + e, e); } } }
From source file:org.brutusin.rpc.client.http.HttpEndpoint.java
public static void main(String[] args) throws Exception { HttpClientContextFactory ctxFact = new HttpClientContextFactory() { public HttpClientContext create() { CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope("localhost", 8080, AuthScope.ANY_REALM, "basic"), new UsernamePasswordCredentials("user", "password")); HttpClientContext context = HttpClientContext.create(); context.setCredentialsProvider(credsProvider); return context; }//w w w . j a v a 2 s. c o m }; HttpEndpoint endpoint = new HttpEndpoint(new URI("http://localhost:8080/rpc/http"), ctxFact); HttpResponse resp = endpoint.exec("rpc.http.version", null, null); if (resp.isIsBinary()) { System.out.println("binary"); System.out.println(resp.getInputStream().getName()); } else { System.out.println(resp.getRpcResponse().getResult()); } }
From source file:com.supermap.desktop.icloud.online.AuthenticatorImpl.java
/** * ?onlinejsessionid(id)/*from www.j a va2 s . c o m*/ * * @param client * @param location * @return ?jsessionid * @throws IOException * @throws AuthenticationException */ private String getJSessionId(CloseableHttpClient client, String location) throws IOException, AuthenticationException { HttpClientContext context = HttpClientContext.create(); HttpGet httpGetToCheckTicket = new HttpGet(location); CloseableHttpResponse response = client.execute(httpGetToCheckTicket, context); try { int code = response.getStatusLine().getStatusCode(); String result = getJSessionIdFromResponse(response); String entity; if ((code >= 400) || (StringUtils.isEmpty(result))) { entity = getEntityText(response); throw new AuthenticationException( "invalid response. url:" + location + ".code:" + code + "." + entity); } return result; } finally { response.close(); } }
From source file:com.liferay.sync.engine.lan.session.LanSession.java
public HttpGet downloadFile(LanDownloadFileEvent lanDownloadFileEvent) throws Exception { final SyncFile syncFile = (SyncFile) lanDownloadFileEvent.getParameterValue("syncFile"); SyncLanClientQueryResult syncLanClientQueryResult = findSyncLanClient(syncFile); final LanDownloadFileHandler lanDownloadFileHandler = (LanDownloadFileHandler) lanDownloadFileEvent .getHandler();// ww w.j a v a 2 s.c om if (syncLanClientQueryResult == null) { lanDownloadFileHandler.handleException(new NoSuchSyncLanClientException()); return null; } if (syncLanClientQueryResult.getConnectionsCount() >= syncLanClientQueryResult.getMaxConnections()) { lanDownloadFileHandler.queueDownload(); return null; } final String url = _getUrl(syncLanClientQueryResult.getSyncLanClient(), syncFile); final HttpGet httpGet = new HttpGet(url); httpGet.addHeader("lanToken", LanTokenUtil.decryptLanToken(syncFile.getLanTokenKey(), syncLanClientQueryResult.getEncryptedToken())); Runnable runnable = new Runnable() { @Override public void run() { try { if (_logger.isTraceEnabled()) { _logger.trace("Downloading {} from {}", syncFile.getFilePathName(), url); } _downloadHttpClient.execute(httpGet, lanDownloadFileHandler, HttpClientContext.create()); } catch (Exception e) { lanDownloadFileHandler.handleException(e); } } }; _downloadExecutorService.execute(runnable); return httpGet; }