List of usage examples for org.apache.http.impl.client HttpClientBuilder setDefaultCredentialsProvider
public final HttpClientBuilder setDefaultCredentialsProvider(final CredentialsProvider credentialsProvider)
From source file:com.gargoylesoftware.htmlunit.HttpWebConnection.java
/** * Creates an <tt>HttpMethod</tt> instance according to the specified parameters. * @param webRequest the request// ww w . j a va 2 s. c o m * @param httpClientBuilder the httpClientBuilder that will be configured * @return the <tt>HttpMethod</tt> instance constructed according to the specified parameters * @throws IOException * @throws URISyntaxException */ @SuppressWarnings("deprecation") private HttpUriRequest makeHttpMethod(final WebRequest webRequest, final HttpClientBuilder httpClientBuilder) throws IOException, URISyntaxException { final String charset = webRequest.getCharset(); // Make sure that the URL is fully encoded. IE actually sends some Unicode chars in request // URLs; because of this we allow some Unicode chars in URLs. However, at this point we're // handing things over the HttpClient, and HttpClient will blow up if we leave these Unicode // chars in the URL. final URL url = UrlUtils.encodeUrl(webRequest.getUrl(), false, charset); // URIUtils.createURI is deprecated but as of httpclient-4.2.1, URIBuilder doesn't work here as it encodes path // what shouldn't happen here URI uri = URIUtils.createURI(url.getProtocol(), url.getHost(), url.getPort(), url.getPath(), escapeQuery(url.getQuery()), null); if (getVirtualHost() != null) { uri = URI.create(getVirtualHost()); } final HttpRequestBase httpMethod = buildHttpMethod(webRequest.getHttpMethod(), uri); setProxy(httpMethod, webRequest); if (!(httpMethod instanceof HttpEntityEnclosingRequest)) { // this is the case for GET as well as TRACE, DELETE, OPTIONS and HEAD if (!webRequest.getRequestParameters().isEmpty()) { final List<NameValuePair> pairs = webRequest.getRequestParameters(); final org.apache.http.NameValuePair[] httpClientPairs = NameValuePair.toHttpClient(pairs); final String query = URLEncodedUtils.format(Arrays.asList(httpClientPairs), charset); uri = URIUtils.createURI(url.getProtocol(), url.getHost(), url.getPort(), url.getPath(), query, null); httpMethod.setURI(uri); } } else { // POST as well as PUT and PATCH final HttpEntityEnclosingRequest method = (HttpEntityEnclosingRequest) httpMethod; if (webRequest.getEncodingType() == FormEncodingType.URL_ENCODED && method instanceof HttpPost) { final HttpPost postMethod = (HttpPost) method; if (webRequest.getRequestBody() == null) { final List<NameValuePair> pairs = webRequest.getRequestParameters(); final org.apache.http.NameValuePair[] httpClientPairs = NameValuePair.toHttpClient(pairs); final String query = URLEncodedUtils.format(Arrays.asList(httpClientPairs), charset); final StringEntity urlEncodedEntity = new StringEntity(query, charset); urlEncodedEntity.setContentType(URLEncodedUtils.CONTENT_TYPE); postMethod.setEntity(urlEncodedEntity); } else { final String body = StringUtils.defaultString(webRequest.getRequestBody()); final StringEntity urlEncodedEntity = new StringEntity(body, charset); urlEncodedEntity.setContentType(URLEncodedUtils.CONTENT_TYPE); postMethod.setEntity(urlEncodedEntity); } } else if (FormEncodingType.MULTIPART == webRequest.getEncodingType()) { final Charset c = getCharset(charset, webRequest.getRequestParameters()); final MultipartEntityBuilder builder = MultipartEntityBuilder.create().setLaxMode(); builder.setCharset(c); for (final NameValuePair pair : webRequest.getRequestParameters()) { if (pair instanceof KeyDataPair) { buildFilePart((KeyDataPair) pair, builder); } else { builder.addTextBody(pair.getName(), pair.getValue(), ContentType.create("text/plain", charset)); } } method.setEntity(builder.build()); } else { // for instance a PUT or PATCH request final String body = webRequest.getRequestBody(); if (body != null) { method.setEntity(new StringEntity(body, charset)); } } } configureHttpProcessorBuilder(httpClientBuilder, webRequest); // Tell the client where to get its credentials from // (it may have changed on the webClient since last call to getHttpClientFor(...)) final CredentialsProvider credentialsProvider = webClient_.getCredentialsProvider(); // if the used url contains credentials, we have to add this final Credentials requestUrlCredentials = webRequest.getUrlCredentials(); if (null != requestUrlCredentials && webClient_.getBrowserVersion().hasFeature(URL_AUTH_CREDENTIALS)) { final URL requestUrl = webRequest.getUrl(); final AuthScope authScope = new AuthScope(requestUrl.getHost(), requestUrl.getPort()); // updating our client to keep the credentials for the next request credentialsProvider.setCredentials(authScope, requestUrlCredentials); httpContext_.removeAttribute(HttpClientContext.TARGET_AUTH_STATE); } // if someone has set credentials to this request, we have to add this final Credentials requestCredentials = webRequest.getCredentials(); if (null != requestCredentials) { final URL requestUrl = webRequest.getUrl(); final AuthScope authScope = new AuthScope(requestUrl.getHost(), requestUrl.getPort()); // updating our client to keep the credentials for the next request credentialsProvider.setCredentials(authScope, requestCredentials); httpContext_.removeAttribute(HttpClientContext.TARGET_AUTH_STATE); } httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider); httpContext_.removeAttribute(HttpClientContext.CREDS_PROVIDER); return httpMethod; }
From source file:org.apache.nifi.processors.standard.GetHTTP.java
@Override public void onTrigger(final ProcessContext context, final ProcessSessionFactory sessionFactory) throws ProcessException { final ComponentLog logger = getLogger(); final ProcessSession session = sessionFactory.createSession(); final FlowFile incomingFlowFile = session.get(); if (incomingFlowFile != null) { session.transfer(incomingFlowFile, REL_SUCCESS); logger.warn("found FlowFile {} in input queue; transferring to success", new Object[] { incomingFlowFile }); }/* w w w .ja va2s. c o m*/ // get the URL final String url = context.getProperty(URL).evaluateAttributeExpressions().getValue(); final URI uri; String source = url; try { uri = new URI(url); source = uri.getHost(); } catch (final URISyntaxException swallow) { // this won't happen as the url has already been validated } // get the ssl context service final SSLContextService sslContextService = context.getProperty(SSL_CONTEXT_SERVICE) .asControllerService(SSLContextService.class); // create the connection manager final HttpClientConnectionManager conMan; if (sslContextService == null) { conMan = new BasicHttpClientConnectionManager(); } else { final SSLContext sslContext; try { sslContext = createSSLContext(sslContextService); } catch (final Exception e) { throw new ProcessException(e); } final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext); // Also include a plain socket factory for regular http connections (especially proxies) final Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder .<ConnectionSocketFactory>create().register("https", sslsf) .register("http", PlainConnectionSocketFactory.getSocketFactory()).build(); conMan = new BasicHttpClientConnectionManager(socketFactoryRegistry); } try { // build the request configuration final RequestConfig.Builder requestConfigBuilder = RequestConfig.custom(); requestConfigBuilder.setConnectionRequestTimeout( context.getProperty(DATA_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS).intValue()); requestConfigBuilder.setConnectTimeout( context.getProperty(CONNECTION_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS).intValue()); requestConfigBuilder.setSocketTimeout( context.getProperty(DATA_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS).intValue()); requestConfigBuilder.setRedirectsEnabled(context.getProperty(FOLLOW_REDIRECTS).asBoolean()); switch (context.getProperty(REDIRECT_COOKIE_POLICY).getValue()) { case STANDARD_COOKIE_POLICY_STR: requestConfigBuilder.setCookieSpec(CookieSpecs.STANDARD); break; case STRICT_COOKIE_POLICY_STR: requestConfigBuilder.setCookieSpec(CookieSpecs.STANDARD_STRICT); break; case NETSCAPE_COOKIE_POLICY_STR: requestConfigBuilder.setCookieSpec(CookieSpecs.NETSCAPE); break; case IGNORE_COOKIE_POLICY_STR: requestConfigBuilder.setCookieSpec(CookieSpecs.IGNORE_COOKIES); break; case DEFAULT_COOKIE_POLICY_STR: default: requestConfigBuilder.setCookieSpec(CookieSpecs.DEFAULT); } // build the http client final HttpClientBuilder clientBuilder = HttpClientBuilder.create(); clientBuilder.setConnectionManager(conMan); // include the user agent final String userAgent = context.getProperty(USER_AGENT).getValue(); if (userAgent != null) { clientBuilder.setUserAgent(userAgent); } // set the ssl context if necessary if (sslContextService != null) { clientBuilder.setSslcontext(sslContextService.createSSLContext(ClientAuth.REQUIRED)); } final String username = context.getProperty(USERNAME).getValue(); final String password = context.getProperty(PASSWORD).getValue(); // set the credentials if appropriate if (username != null) { final CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); if (password == null) { credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username)); } else { credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password)); } clientBuilder.setDefaultCredentialsProvider(credentialsProvider); } // Set the proxy if specified if (context.getProperty(PROXY_HOST).isSet() && context.getProperty(PROXY_PORT).isSet()) { final String host = context.getProperty(PROXY_HOST).getValue(); final int port = context.getProperty(PROXY_PORT).asInteger(); clientBuilder.setProxy(new HttpHost(host, port)); } // create request final HttpGet get = new HttpGet(url); get.setConfig(requestConfigBuilder.build()); final StateMap beforeStateMap; try { beforeStateMap = context.getStateManager().getState(Scope.LOCAL); final String lastModified = beforeStateMap.get(LAST_MODIFIED + ":" + url); if (lastModified != null) { get.addHeader(HEADER_IF_MODIFIED_SINCE, parseStateValue(lastModified).getValue()); } final String etag = beforeStateMap.get(ETAG + ":" + url); if (etag != null) { get.addHeader(HEADER_IF_NONE_MATCH, parseStateValue(etag).getValue()); } } catch (final IOException ioe) { throw new ProcessException(ioe); } final String accept = context.getProperty(ACCEPT_CONTENT_TYPE).getValue(); if (accept != null) { get.addHeader(HEADER_ACCEPT, accept); } // Add dynamic headers PropertyValue customHeaderValue; for (PropertyDescriptor customProperty : customHeaders) { customHeaderValue = context.getProperty(customProperty).evaluateAttributeExpressions(); if (StringUtils.isNotBlank(customHeaderValue.getValue())) { get.addHeader(customProperty.getName(), customHeaderValue.getValue()); } } // create the http client try (final CloseableHttpClient client = clientBuilder.build()) { // NOTE: including this inner try in order to swallow exceptions on close try { final StopWatch stopWatch = new StopWatch(true); final HttpResponse response = client.execute(get); final int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == NOT_MODIFIED) { logger.info( "content not retrieved because server returned HTTP Status Code {}: Not Modified", new Object[] { NOT_MODIFIED }); context.yield(); // doing a commit in case there were flow files in the input queue session.commit(); return; } final String statusExplanation = response.getStatusLine().getReasonPhrase(); if ((statusCode >= 300) || (statusCode == 204)) { logger.error("received status code {}:{} from {}", new Object[] { statusCode, statusExplanation, url }); // doing a commit in case there were flow files in the input queue session.commit(); return; } FlowFile flowFile = session.create(); flowFile = session.putAttribute(flowFile, CoreAttributes.FILENAME.key(), context.getProperty(FILENAME).evaluateAttributeExpressions().getValue()); flowFile = session.putAttribute(flowFile, this.getClass().getSimpleName().toLowerCase() + ".remote.source", source); flowFile = session.importFrom(response.getEntity().getContent(), flowFile); final Header contentTypeHeader = response.getFirstHeader("Content-Type"); if (contentTypeHeader != null) { final String contentType = contentTypeHeader.getValue(); if (!contentType.trim().isEmpty()) { flowFile = session.putAttribute(flowFile, CoreAttributes.MIME_TYPE.key(), contentType.trim()); } } final long flowFileSize = flowFile.getSize(); stopWatch.stop(); final String dataRate = stopWatch.calculateDataRate(flowFileSize); session.getProvenanceReporter().receive(flowFile, url, stopWatch.getDuration(TimeUnit.MILLISECONDS)); session.transfer(flowFile, REL_SUCCESS); logger.info("Successfully received {} from {} at a rate of {}; transferred to success", new Object[] { flowFile, url, dataRate }); session.commit(); updateStateMap(context, response, beforeStateMap, url); } catch (final IOException e) { context.yield(); session.rollback(); logger.error("Failed to retrieve file from {} due to {}; rolling back session", new Object[] { url, e.getMessage() }, e); throw new ProcessException(e); } catch (final Throwable t) { context.yield(); session.rollback(); logger.error("Failed to process due to {}; rolling back session", new Object[] { t.getMessage() }, t); throw t; } } catch (final IOException e) { logger.debug("Error closing client due to {}, continuing.", new Object[] { e.getMessage() }); } } finally { conMan.shutdown(); } }
From source file:org.apache.nifi.processors.standard.PostHTTP.java
@Override public void onTrigger(final ProcessContext context, final ProcessSession session) { final boolean sendAsFlowFile = context.getProperty(SEND_AS_FLOWFILE).asBoolean(); final int compressionLevel = context.getProperty(COMPRESSION_LEVEL).asInteger(); final String userAgent = context.getProperty(USER_AGENT).getValue(); final RequestConfig.Builder requestConfigBuilder = RequestConfig.custom(); requestConfigBuilder.setConnectionRequestTimeout( context.getProperty(DATA_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS).intValue()); requestConfigBuilder.setConnectTimeout( context.getProperty(CONNECTION_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS).intValue()); requestConfigBuilder.setRedirectsEnabled(false); requestConfigBuilder/*from w w w . j a v a2s .co m*/ .setSocketTimeout(context.getProperty(DATA_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS).intValue()); final RequestConfig requestConfig = requestConfigBuilder.build(); final StreamThrottler throttler = throttlerRef.get(); final ComponentLog logger = getLogger(); final Double maxBatchBytes = context.getProperty(MAX_BATCH_SIZE).asDataSize(DataUnit.B); String lastUrl = null; long bytesToSend = 0L; final List<FlowFile> toSend = new ArrayList<>(); DestinationAccepts destinationAccepts = null; CloseableHttpClient client = null; final String transactionId = UUID.randomUUID().toString(); final AtomicReference<String> dnHolder = new AtomicReference<>("none"); while (true) { FlowFile flowFile = session.get(); if (flowFile == null) { break; } final String url = context.getProperty(URL).evaluateAttributeExpressions(flowFile).getValue(); try { new java.net.URL(url); } catch (final MalformedURLException e) { logger.error( "After substituting attribute values for {}, URL is {}; this is not a valid URL, so routing to failure", new Object[] { flowFile, url }); flowFile = session.penalize(flowFile); session.transfer(flowFile, REL_FAILURE); continue; } // If this FlowFile doesn't have the same url, throw it back on the queue and stop grabbing FlowFiles if (lastUrl != null && !lastUrl.equals(url)) { session.transfer(flowFile); break; } lastUrl = url; toSend.add(flowFile); if (client == null || destinationAccepts == null) { final Config config = getConfig(url, context); final HttpClientConnectionManager conMan = config.getConnectionManager(); final HttpClientBuilder clientBuilder = HttpClientBuilder.create(); clientBuilder.setConnectionManager(conMan); clientBuilder.setUserAgent(userAgent); clientBuilder.addInterceptorFirst(new HttpResponseInterceptor() { @Override public void process(final HttpResponse response, final HttpContext httpContext) throws HttpException, IOException { final HttpCoreContext coreContext = HttpCoreContext.adapt(httpContext); final ManagedHttpClientConnection conn = coreContext .getConnection(ManagedHttpClientConnection.class); if (!conn.isOpen()) { return; } final SSLSession sslSession = conn.getSSLSession(); if (sslSession != null) { final Certificate[] certChain = sslSession.getPeerCertificates(); if (certChain == null || certChain.length == 0) { throw new SSLPeerUnverifiedException("No certificates found"); } try { final X509Certificate cert = CertificateUtils .convertAbstractX509Certificate(certChain[0]); dnHolder.set(cert.getSubjectDN().getName().trim()); } catch (CertificateException e) { final String msg = "Could not extract subject DN from SSL session peer certificate"; logger.warn(msg); throw new SSLPeerUnverifiedException(msg); } } } }); clientBuilder.disableAutomaticRetries(); clientBuilder.disableContentCompression(); final String username = context.getProperty(USERNAME).getValue(); final String password = context.getProperty(PASSWORD).getValue(); // set the credentials if appropriate if (username != null) { final CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); if (password == null) { credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username)); } else { credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password)); } clientBuilder.setDefaultCredentialsProvider(credentialsProvider); } // Set the proxy if specified if (context.getProperty(PROXY_HOST).isSet() && context.getProperty(PROXY_PORT).isSet()) { final String host = context.getProperty(PROXY_HOST).getValue(); final int port = context.getProperty(PROXY_PORT).asInteger(); clientBuilder.setProxy(new HttpHost(host, port)); } client = clientBuilder.build(); // determine whether or not destination accepts flowfile/gzip destinationAccepts = config.getDestinationAccepts(); if (destinationAccepts == null) { try { destinationAccepts = getDestinationAcceptance(sendAsFlowFile, client, url, getLogger(), transactionId); config.setDestinationAccepts(destinationAccepts); } catch (final IOException e) { flowFile = session.penalize(flowFile); session.transfer(flowFile, REL_FAILURE); logger.error( "Unable to communicate with destination {} to determine whether or not it can accept " + "flowfiles/gzip; routing {} to failure due to {}", new Object[] { url, flowFile, e }); context.yield(); return; } } } bytesToSend += flowFile.getSize(); if (bytesToSend > maxBatchBytes.longValue()) { break; } // if we are not sending as flowfile, or if the destination doesn't accept V3 or V2 (streaming) format, // then only use a single FlowFile if (!sendAsFlowFile || !destinationAccepts.isFlowFileV3Accepted() && !destinationAccepts.isFlowFileV2Accepted()) { break; } } if (toSend.isEmpty()) { return; } final String url = lastUrl; final HttpPost post = new HttpPost(url); final List<FlowFile> flowFileList = toSend; final DestinationAccepts accepts = destinationAccepts; final boolean isDestinationLegacyNiFi = accepts.getProtocolVersion() == null; final EntityTemplate entity = new EntityTemplate(new ContentProducer() { @Override public void writeTo(final OutputStream rawOut) throws IOException { final OutputStream throttled = throttler == null ? rawOut : throttler.newThrottledOutputStream(rawOut); OutputStream wrappedOut = new BufferedOutputStream(throttled); if (compressionLevel > 0 && accepts.isGzipAccepted()) { wrappedOut = new GZIPOutputStream(wrappedOut, compressionLevel); } try (final OutputStream out = wrappedOut) { for (final FlowFile flowFile : flowFileList) { session.read(flowFile, new InputStreamCallback() { @Override public void process(final InputStream rawIn) throws IOException { try (final InputStream in = new BufferedInputStream(rawIn)) { FlowFilePackager packager = null; if (!sendAsFlowFile) { packager = null; } else if (accepts.isFlowFileV3Accepted()) { packager = new FlowFilePackagerV3(); } else if (accepts.isFlowFileV2Accepted()) { packager = new FlowFilePackagerV2(); } else if (accepts.isFlowFileV1Accepted()) { packager = new FlowFilePackagerV1(); } // if none of the above conditions is met, we should never get here, because // we will have already verified that at least 1 of the FlowFile packaging // formats is acceptable if sending as FlowFile. if (packager == null) { StreamUtils.copy(in, out); } else { final Map<String, String> flowFileAttributes; if (isDestinationLegacyNiFi) { // Old versions of NiFi expect nf.file.name and nf.file.path to indicate filename & path; // in order to maintain backward compatibility, we copy the filename & path to those attribute keys. flowFileAttributes = new HashMap<>(flowFile.getAttributes()); flowFileAttributes.put("nf.file.name", flowFile.getAttribute(CoreAttributes.FILENAME.key())); flowFileAttributes.put("nf.file.path", flowFile.getAttribute(CoreAttributes.PATH.key())); } else { flowFileAttributes = flowFile.getAttributes(); } packager.packageFlowFile(in, out, flowFileAttributes, flowFile.getSize()); } } } }); } out.flush(); } } }) { @Override public long getContentLength() { if (compressionLevel == 0 && !sendAsFlowFile && !context.getProperty(CHUNKED_ENCODING).asBoolean()) { return toSend.get(0).getSize(); } else { return -1; } } }; if (context.getProperty(CHUNKED_ENCODING).isSet()) { entity.setChunked(context.getProperty(CHUNKED_ENCODING).asBoolean()); } post.setEntity(entity); post.setConfig(requestConfig); final String contentType; if (sendAsFlowFile) { if (accepts.isFlowFileV3Accepted()) { contentType = APPLICATION_FLOW_FILE_V3; } else if (accepts.isFlowFileV2Accepted()) { contentType = APPLICATION_FLOW_FILE_V2; } else if (accepts.isFlowFileV1Accepted()) { contentType = APPLICATION_FLOW_FILE_V1; } else { logger.error( "Cannot send data to {} because the destination does not accept FlowFiles and this processor is " + "configured to deliver FlowFiles; rolling back session", new Object[] { url }); session.rollback(); context.yield(); IOUtils.closeQuietly(client); return; } } else { final String contentTypeValue = context.getProperty(CONTENT_TYPE) .evaluateAttributeExpressions(toSend.get(0)).getValue(); contentType = StringUtils.isBlank(contentTypeValue) ? DEFAULT_CONTENT_TYPE : contentTypeValue; } final String attributeHeaderRegex = context.getProperty(ATTRIBUTES_AS_HEADERS_REGEX).getValue(); if (attributeHeaderRegex != null && !sendAsFlowFile && flowFileList.size() == 1) { final Pattern pattern = Pattern.compile(attributeHeaderRegex); final Map<String, String> attributes = flowFileList.get(0).getAttributes(); for (final Map.Entry<String, String> entry : attributes.entrySet()) { final String key = entry.getKey(); if (pattern.matcher(key).matches()) { post.setHeader(entry.getKey(), entry.getValue()); } } } post.setHeader(CONTENT_TYPE_HEADER, contentType); post.setHeader(FLOWFILE_CONFIRMATION_HEADER, "true"); post.setHeader(PROTOCOL_VERSION_HEADER, PROTOCOL_VERSION); post.setHeader(TRANSACTION_ID_HEADER, transactionId); if (compressionLevel > 0 && accepts.isGzipAccepted()) { if (sendAsFlowFile) { post.setHeader(GZIPPED_HEADER, "true"); } else { post.setHeader(CONTENT_ENCODING_HEADER, CONTENT_ENCODING_GZIP_VALUE); } } // Do the actual POST final String flowFileDescription = toSend.size() <= 10 ? toSend.toString() : toSend.size() + " FlowFiles"; final String uploadDataRate; final long uploadMillis; CloseableHttpResponse response = null; try { final StopWatch stopWatch = new StopWatch(true); response = client.execute(post); // consume input stream entirely, ignoring its contents. If we // don't do this, the Connection will not be returned to the pool EntityUtils.consume(response.getEntity()); stopWatch.stop(); uploadDataRate = stopWatch.calculateDataRate(bytesToSend); uploadMillis = stopWatch.getDuration(TimeUnit.MILLISECONDS); } catch (final IOException e) { logger.error("Failed to Post {} due to {}; transferring to failure", new Object[] { flowFileDescription, e }); context.yield(); for (FlowFile flowFile : toSend) { flowFile = session.penalize(flowFile); session.transfer(flowFile, REL_FAILURE); } return; } finally { if (response != null) { try { response.close(); } catch (final IOException e) { getLogger().warn("Failed to close HTTP Response due to {}", new Object[] { e }); } } } // If we get a 'SEE OTHER' status code and an HTTP header that indicates that the intent // of the Location URI is a flowfile hold, we will store this holdUri. This prevents us // from posting to some other webservice and then attempting to delete some resource to which // we are redirected final int responseCode = response.getStatusLine().getStatusCode(); final String responseReason = response.getStatusLine().getReasonPhrase(); String holdUri = null; if (responseCode == HttpServletResponse.SC_SEE_OTHER) { final Header locationUriHeader = response.getFirstHeader(LOCATION_URI_INTENT_NAME); if (locationUriHeader != null) { if (LOCATION_URI_INTENT_VALUE.equals(locationUriHeader.getValue())) { final Header holdUriHeader = response.getFirstHeader(LOCATION_HEADER_NAME); if (holdUriHeader != null) { holdUri = holdUriHeader.getValue(); } } } if (holdUri == null) { for (FlowFile flowFile : toSend) { flowFile = session.penalize(flowFile); logger.error( "Failed to Post {} to {}: sent content and received status code {}:{} but no Hold URI", new Object[] { flowFile, url, responseCode, responseReason }); session.transfer(flowFile, REL_FAILURE); } return; } } if (holdUri == null) { if (responseCode == HttpServletResponse.SC_SERVICE_UNAVAILABLE) { for (FlowFile flowFile : toSend) { flowFile = session.penalize(flowFile); logger.error( "Failed to Post {} to {}: response code was {}:{}; will yield processing, " + "since the destination is temporarily unavailable", new Object[] { flowFile, url, responseCode, responseReason }); session.transfer(flowFile, REL_FAILURE); } context.yield(); return; } if (responseCode >= 300) { for (FlowFile flowFile : toSend) { flowFile = session.penalize(flowFile); logger.error("Failed to Post {} to {}: response code was {}:{}", new Object[] { flowFile, url, responseCode, responseReason }); session.transfer(flowFile, REL_FAILURE); } return; } logger.info("Successfully Posted {} to {} in {} at a rate of {}", new Object[] { flowFileDescription, url, FormatUtils.formatMinutesSeconds(uploadMillis, TimeUnit.MILLISECONDS), uploadDataRate }); for (final FlowFile flowFile : toSend) { session.getProvenanceReporter().send(flowFile, url, "Remote DN=" + dnHolder.get(), uploadMillis, true); session.transfer(flowFile, REL_SUCCESS); } return; } // // the response indicated a Hold URI; delete the Hold. // // determine the full URI of the Flow File's Hold; Unfortunately, the responses that are returned have // changed over the past, so we have to take into account a few different possibilities. String fullHoldUri = holdUri; if (holdUri.startsWith("/contentListener")) { // If the Hold URI that we get starts with /contentListener, it may not really be /contentListener, // as this really indicates that it should be whatever we posted to -- if posting directly to the // ListenHTTP component, it will be /contentListener, but if posting to a proxy/load balancer, we may // be posting to some other URL. fullHoldUri = url + holdUri.substring(16); } else if (holdUri.startsWith("/")) { // URL indicates the full path but not hostname or port; use the same hostname & port that we posted // to but use the full path indicated by the response. int firstSlash = url.indexOf("/", 8); if (firstSlash < 0) { firstSlash = url.length(); } final String beforeSlash = url.substring(0, firstSlash); fullHoldUri = beforeSlash + holdUri; } else if (!holdUri.startsWith("http")) { // Absolute URL fullHoldUri = url + (url.endsWith("/") ? "" : "/") + holdUri; } final HttpDelete delete = new HttpDelete(fullHoldUri); delete.setHeader(TRANSACTION_ID_HEADER, transactionId); while (true) { try { final HttpResponse holdResponse = client.execute(delete); EntityUtils.consume(holdResponse.getEntity()); final int holdStatusCode = holdResponse.getStatusLine().getStatusCode(); final String holdReason = holdResponse.getStatusLine().getReasonPhrase(); if (holdStatusCode >= 300) { logger.error( "Failed to delete Hold that destination placed on {}: got response code {}:{}; routing to failure", new Object[] { flowFileDescription, holdStatusCode, holdReason }); for (FlowFile flowFile : toSend) { flowFile = session.penalize(flowFile); session.transfer(flowFile, REL_FAILURE); } return; } logger.info("Successfully Posted {} to {} in {} milliseconds at a rate of {}", new Object[] { flowFileDescription, url, uploadMillis, uploadDataRate }); for (final FlowFile flowFile : toSend) { session.getProvenanceReporter().send(flowFile, url); session.transfer(flowFile, REL_SUCCESS); } return; } catch (final IOException e) { logger.warn("Failed to delete Hold that destination placed on {} due to {}", new Object[] { flowFileDescription, e }); } if (!isScheduled()) { context.yield(); logger.warn( "Failed to delete Hold that destination placed on {}; Processor has been stopped so routing FlowFile(s) to failure", new Object[] { flowFileDescription }); for (FlowFile flowFile : toSend) { flowFile = session.penalize(flowFile); session.transfer(flowFile, REL_FAILURE); } return; } } }
From source file:org.apache.nifi.remote.util.SiteToSiteRestApiClient.java
private void setupClient() { final HttpClientBuilder clientBuilder = HttpClients.custom(); if (sslContext != null) { clientBuilder.setSslcontext(sslContext); clientBuilder.addInterceptorFirst(new HttpsResponseInterceptor()); }//from w w w.java 2 s. c om httpClient = clientBuilder.setDefaultCredentialsProvider(getCredentialsProvider()).build(); }
From source file:org.apache.zeppelin.submarine.hadoop.YarnClient.java
private static HttpClient buildSpengoHttpClient() { HttpClientBuilder builder = HttpClientBuilder.create(); Lookup<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create() .register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory(true)).build(); builder.setDefaultAuthSchemeRegistry(authSchemeRegistry); BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(new AuthScope(null, -1, null), new Credentials() { @Override/*from ww w . ja va 2 s . c o m*/ public Principal getUserPrincipal() { return null; } @Override public String getPassword() { return null; } }); builder.setDefaultCredentialsProvider(credentialsProvider); // Avoid output WARN: Cookie rejected RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.IGNORE_COOKIES).build(); builder.setDefaultRequestConfig(globalConfig); CloseableHttpClient httpClient = builder.build(); return httpClient; }
From source file:org.flowable.ui.admin.service.engine.FlowableClientService.java
public CloseableHttpClient getHttpClient(String userName, String password) { CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(userName, password)); SSLConnectionSocketFactory sslsf = null; try {/*w ww . j av a 2 s . co m*/ SSLContextBuilder builder = new SSLContextBuilder(); builder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); sslsf = new SSLConnectionSocketFactory(builder.build(), new HostnameVerifier() { @Override public boolean verify(String s, SSLSession sslSession) { return true; } }); } catch (Exception e) { LOGGER.warn("Could not configure HTTP client to use SSL", e); } HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider); if (preemptiveBasicAuthentication) { String auth = userName + ":" + password; httpClientBuilder.setDefaultHeaders(Collections.singletonList(new BasicHeader(AUTH.WWW_AUTH_RESP, "Basic " + Base64.getEncoder().encodeToString(auth.getBytes(StandardCharsets.UTF_8))))); } if (sslsf != null) { httpClientBuilder.setSSLSocketFactory(sslsf); } return httpClientBuilder.build(); }
From source file:org.mitre.dsmiley.httpproxy.ProxyServlet.java
/** * Called from {@link #init(javax.servlet.ServletConfig)}. HttpClient offers * many opportunities for customization. By default, <a href= * "http://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/impl/client/SystemDefaultHttpClient.html"> * SystemDefaultHttpClient</a> is used if available, otherwise it falls back * to://from www .j ava2s . c om * * <pre> * new DefaultHttpClient(new ThreadSafeClientConnManager(), hcParams) * </pre> * * SystemDefaultHttpClient uses PoolingClientConnectionManager. In any case, * it should be thread-safe. */ protected HttpClient createHttpClient(HttpParams hcParams) { try { String negotiateURL = getConfigParam("negotiate.url"); String negotiateSPN = getConfigParam("negotiate.spn"); if (negotiateURL != null && negotiateSPN != null) { System.out.println("negotiate url:" + negotiateURL); System.out.println("negotiate spn:" + negotiateSPN); // initialize the Windows security Context to get the negotiate // client token IWindowsSecurityContext clientContext = null; IWindowsCredentialsHandle clientCredentials = null; clientContext = WindowsSecurityContextImpl.getCurrent(SECURITY_PACKAGE, negotiateSPN); clientCredentials = WindowsCredentialsHandleImpl.getCurrent(SECURITY_PACKAGE); clientCredentials.initialize(); String username = WindowsAccountImpl.getCurrentUsername(); System.out.println("credentials for user " + username + " get prepared"); byte[] token = clientContext.getToken(); // encode the token with Base64 to be able to add it to the http // header String clientToken = Base64.encodeBase64String(token); System.out.println("clientToken" + clientToken); // if there is only a negotiate url the rest of the // authorization is based on cookies // so we need to support them. CookieStore cookieStore = new BasicCookieStore(); RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.DEFAULT).build(); HttpClientContext context = HttpClientContext.create(); proxyContext = context; context.setCookieStore(cookieStore); HttpClient httpClient = HttpClients.custom().disableRedirectHandling() .setDefaultRequestConfig(globalConfig).setDefaultCookieStore(cookieStore).build(); // first we need to act as a normal browser to get a http 401 // with negotiate header doActAsBrowser = true; HttpGet browserHttpGet = new HttpGet(negotiateURL); addBrowserHeader(browserHttpGet); HttpResponse rep = httpClient.execute(browserHttpGet, context); if (rep.getStatusLine().getStatusCode() == 401) { System.out.println("negotiate requested - sending negotiate client token"); HttpGet negotiateHttpGet = new HttpGet(negotiateURL); addBrowserHeader(negotiateHttpGet); negotiateHttpGet.addHeader("Authorization", "Negotiate " + clientToken); HttpResponse response = httpClient.execute(negotiateHttpGet, context); System.out.println( "http result code of negotiate request:" + response.getStatusLine().getStatusCode()); // now the url needs to be called periodically to keep the // cookie and connection alive String refreshTimeString = getConfigParam("negotiate.refreshtime"); long refreshTime = 1000000; if (refreshTimeString != null) { refreshTime = Long.parseLong(refreshTimeString); } HttpClientRefreshThread thread = new HttpClientRefreshThread(refreshTime, negotiateURL); thread.start(); List<org.apache.http.cookie.Cookie> cookies = context.getCookieStore().getCookies(); cookieString = ""; int size = cookies.size() - 1; for (int i = 0; i < cookies.size(); i++) { cookieString += cookies.get(i).getName(); cookieString += "="; cookieString += cookies.get(i).getValue(); if (i != size) cookieString += "; "; } } else { System.out.println("No negotiate requested"); } } else { if (!WinHttpClients.isWinAuthAvailable()) { System.out.println("Integrated Win auth is not supported!!!"); } else { HttpClientBuilder builder = WinHttpClients.custom(); Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create() .register(AuthSchemes.BASIC, new BasicSchemeFactory()) .register(AuthSchemes.DIGEST, new DigestSchemeFactory()) .register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory()) .register(AuthSchemes.NTLM, new NTLMSchemeFactory()) .register(AuthSchemes.KERBEROS, new KerberosSchemeFactory()).build(); builder.setDefaultAuthSchemeRegistry(authSchemeRegistry); String username = getConfigParam("user"); String password = getConfigParam("password"); String domain = getConfigParam("domain"); String host = getConfigParam("host"); if (username != null) { NTCredentials cred = new NTCredentials(username, password, host, domain); CredentialsProvider credsProvider = new WindowsCredentialsProvider( new SystemDefaultCredentialsProvider()); credsProvider.setCredentials(AuthScope.ANY, cred); builder.setDefaultCredentialsProvider(credsProvider); } builder.disableCookieManagement(); builder.disableRedirectHandling(); return builder.build(); } // as of HttpComponents v4.2, this class is better since it uses // System // Properties: Class<?> clientClazz = Class.forName("org.apache.http.impl.client.SystemDefaultHttpClient"); Constructor<?> constructor = clientClazz.getConstructor(HttpParams.class); return (HttpClient) constructor.newInstance(hcParams); } } catch (ClassNotFoundException e) { // no problem; use v4.1 below } catch (Exception e) { throw new RuntimeException(e); } // Fallback on using older client: return new DefaultHttpClient(new ThreadSafeClientConnManager(), hcParams); }
From source file:org.opennms.core.web.HttpClientWrapper.java
protected void setCredentials(final HttpClientBuilder httpClientBuilder, final String username, final String password) { final UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password); final BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, credentials); httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider); }
From source file:org.tanaguru.util.http.HttpRequestHandler.java
private CloseableHttpClient getHttpClient(String url) { RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(socketTimeout) .setConnectTimeout(connectionTimeout).build(); HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); httpClientBuilder.setDefaultRequestConfig(requestConfig); httpClientBuilder.setConnectionManager(new PoolingHttpClientConnectionManager()); httpClientBuilder.setUserAgent(TANAGURU_USER_AGENT); if (isProxySet(url)) { LOGGER.debug(("Set proxy with " + proxyHost + " and " + proxyPort)); httpClientBuilder.setProxy(new HttpHost(proxyHost, Integer.valueOf(proxyPort))); if (isProxyCredentialSet()) { CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(proxyHost, Integer.valueOf(proxyPort)), new UsernamePasswordCredentials(proxyUser, proxyPassword)); httpClientBuilder.setDefaultCredentialsProvider(credsProvider); LOGGER.debug(("Set proxy credentials " + proxyHost + " and " + proxyPort + " and " + proxyUser + " and " + proxyPassword)); }/*from w w w. jav a 2 s . c om*/ } return httpClientBuilder.build(); }