List of usage examples for org.apache.http.client.methods HttpHead HttpHead
public HttpHead(final String uri)
From source file:org.apache.nifi.processors.standard.PostHTTP.java
private DestinationAccepts getDestinationAcceptance(final boolean sendAsFlowFile, final HttpClient client, final String uri, final ComponentLog logger, final String transactionId) throws IOException { final HttpHead head = new HttpHead(uri); if (sendAsFlowFile) { head.addHeader(TRANSACTION_ID_HEADER, transactionId); }//from w w w . j a va 2s. c o m final HttpResponse response = client.execute(head); // we assume that the destination can support FlowFile v1 always when the processor is also configured to send as a FlowFile // otherwise, we do not bother to make any determinations concerning this compatibility final boolean acceptsFlowFileV1 = sendAsFlowFile; boolean acceptsFlowFileV2 = false; boolean acceptsFlowFileV3 = false; boolean acceptsGzip = false; Integer protocolVersion = null; final int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == Status.METHOD_NOT_ALLOWED.getStatusCode()) { return new DestinationAccepts(acceptsFlowFileV3, acceptsFlowFileV2, acceptsFlowFileV1, false, null); } else if (statusCode == Status.OK.getStatusCode()) { Header[] headers = response.getHeaders(ACCEPT); // If configured to send as a flowfile, determine the capabilities of the endpoint if (sendAsFlowFile) { if (headers != null) { for (final Header header : headers) { for (final String accepted : header.getValue().split(",")) { final String trimmed = accepted.trim(); if (trimmed.equals(APPLICATION_FLOW_FILE_V3)) { acceptsFlowFileV3 = true; } else if (trimmed.equals(APPLICATION_FLOW_FILE_V2)) { acceptsFlowFileV2 = true; } } } } final Header destinationVersion = response.getFirstHeader(PROTOCOL_VERSION_HEADER); if (destinationVersion != null) { try { protocolVersion = Integer.valueOf(destinationVersion.getValue()); } catch (final NumberFormatException e) { // nothing to do here really.... it's an invalid value, so treat the same as if not specified } } if (acceptsFlowFileV3) { logger.debug("Connection to URI " + uri + " will be using Content Type " + APPLICATION_FLOW_FILE_V3 + " if sending data as FlowFile"); } else if (acceptsFlowFileV2) { logger.debug("Connection to URI " + uri + " will be using Content Type " + APPLICATION_FLOW_FILE_V2 + " if sending data as FlowFile"); } else if (acceptsFlowFileV1) { logger.debug("Connection to URI " + uri + " will be using Content Type " + APPLICATION_FLOW_FILE_V1 + " if sending data as FlowFile"); } } headers = response.getHeaders(ACCEPT_ENCODING); if (headers != null) { for (final Header header : headers) { for (final String accepted : header.getValue().split(",")) { if (accepted.equalsIgnoreCase("gzip")) { acceptsGzip = true; } } } } if (acceptsGzip) { logger.debug("Connection to URI " + uri + " indicates that inline GZIP compression is supported"); } else { logger.debug( "Connection to URI " + uri + " indicates that it does NOT support inline GZIP compression"); } return new DestinationAccepts(acceptsFlowFileV3, acceptsFlowFileV2, acceptsFlowFileV1, acceptsGzip, protocolVersion); } else { logger.warn( "Unable to communicate with destination; when attempting to perform an HTTP HEAD, got unexpected response code of " + statusCode + ": " + response.getStatusLine().getReasonPhrase()); return new DestinationAccepts(false, false, false, false, null); } }
From source file:org.apache.nutch.protocol.httpclient.HttpClientRedirectStrategy.java
public HttpUriRequest getRedirect(final HttpRequest request, final HttpResponse response, final HttpContext context) throws ProtocolException { URI uri = getLocationURI(request, response, context); String method = request.getRequestLine().getMethod(); if (method.equalsIgnoreCase(HttpHead.METHOD_NAME)) { return new HttpHead(uri); } else if (method.equalsIgnoreCase(HttpGet.METHOD_NAME)) { return new HttpGet(uri); } else {/* ww w. j a v a 2 s . c o m*/ int status = response.getStatusLine().getStatusCode(); if (status == HttpStatus.SC_TEMPORARY_REDIRECT) { if (method.equalsIgnoreCase(HttpPost.METHOD_NAME)) { return copyEntity(new HttpPost(uri), request); } else if (method.equalsIgnoreCase(HttpPut.METHOD_NAME)) { return copyEntity(new HttpPut(uri), request); } else if (method.equalsIgnoreCase(HttpDelete.METHOD_NAME)) { return new HttpDelete(uri); } else if (method.equalsIgnoreCase(HttpTrace.METHOD_NAME)) { return new HttpTrace(uri); } else if (method.equalsIgnoreCase(HttpOptions.METHOD_NAME)) { return new HttpOptions(uri); } else if (method.equalsIgnoreCase(HttpPatch.METHOD_NAME)) { return copyEntity(new HttpPatch(uri), request); } } return new HttpGet(uri); } }
From source file:org.apache.sentry.tests.e2e.solr.AbstractSolrSentryTestBase.java
/** * Make a raw http request to specific cluster node. Node is of the format * host:port/context, i.e. "localhost:8983/solr" *//*from ww w. ja v a 2s.c o m*/ protected String makeHttpRequest(CloudSolrServer server, String node, String httpMethod, String path, byte[] content, String contentType) throws Exception { HttpClient httpClient = server.getLbServer().getHttpClient(); URI uri = new URI("http://" + node + path); HttpRequestBase method = null; if ("GET".equals(httpMethod)) { method = new HttpGet(uri); } else if ("HEAD".equals(httpMethod)) { method = new HttpHead(uri); } else if ("POST".equals(httpMethod)) { method = new HttpPost(uri); } else if ("PUT".equals(httpMethod)) { method = new HttpPut(uri); } else { throw new IOException("Unsupported method: " + method); } if (method instanceof HttpEntityEnclosingRequestBase) { HttpEntityEnclosingRequestBase entityEnclosing = (HttpEntityEnclosingRequestBase) method; ByteArrayEntity entityRequest = new ByteArrayEntity(content); entityRequest.setContentType(contentType); entityEnclosing.setEntity(entityRequest); } HttpEntity httpEntity = null; boolean success = false; String retValue = ""; try { final HttpResponse response = httpClient.execute(method); int httpStatus = response.getStatusLine().getStatusCode(); httpEntity = response.getEntity(); if (httpEntity != null) { InputStream is = httpEntity.getContent(); ByteArrayOutputStream os = new ByteArrayOutputStream(); try { IOUtils.copyLarge(is, os); os.flush(); } finally { IOUtils.closeQuietly(os); IOUtils.closeQuietly(is); } retValue = os.toString(); } success = true; } finally { if (!success) { EntityUtils.consumeQuietly(httpEntity); method.abort(); } } return retValue; }
From source file:org.apache.sentry.tests.e2e.solr.AbstractSolrSentryTestCase.java
/** * Make a raw http request to specific cluster node. Node is of the format * host:port/context, i.e. "localhost:8983/solr" *///from w w w. j av a 2 s . c om protected String makeHttpRequest(CloudSolrClient client, String node, String httpMethod, String path, byte[] content, String contentType, int expectedStatusCode) throws Exception { HttpClient httpClient = client.getLbClient().getHttpClient(); URI uri = new URI("http://" + node + path); HttpRequestBase method = null; if ("GET".equals(httpMethod)) { method = new HttpGet(uri); } else if ("HEAD".equals(httpMethod)) { method = new HttpHead(uri); } else if ("POST".equals(httpMethod)) { method = new HttpPost(uri); } else if ("PUT".equals(httpMethod)) { method = new HttpPut(uri); } else { throw new IOException("Unsupported method: " + method); } if (method instanceof HttpEntityEnclosingRequestBase) { HttpEntityEnclosingRequestBase entityEnclosing = (HttpEntityEnclosingRequestBase) method; ByteArrayEntity entityRequest = new ByteArrayEntity(content); entityRequest.setContentType(contentType); entityEnclosing.setEntity(entityRequest); } HttpEntity httpEntity = null; boolean success = false; String retValue = ""; try { final HttpResponse response = httpClient.execute(method); httpEntity = response.getEntity(); assertEquals(expectedStatusCode, response.getStatusLine().getStatusCode()); if (httpEntity != null) { InputStream is = httpEntity.getContent(); ByteArrayOutputStream os = new ByteArrayOutputStream(); try { IOUtils.copyLarge(is, os); os.flush(); } finally { IOUtils.closeQuietly(os); IOUtils.closeQuietly(is); } retValue = os.toString(); } success = true; } finally { if (!success) { EntityUtils.consumeQuietly(httpEntity); method.abort(); } } return retValue; }
From source file:org.artifactory.repo.HttpRepo.java
@Override protected RepoResource retrieveInfo(String path, boolean folder, @Nullable RequestContext context) { assert !isOffline() : "Should never be called in offline mode"; RepoPath repoPath = InternalRepoPathFactory.create(this.getKey(), path, folder); String fullUrl = assembleRetrieveInfoUrl(path, context); Map<String, String> headers = Maps.newHashMap(); HttpRequestBase method;/*from www . j a v a2 s . c o m*/ boolean replaceHeadWithGet = false; String methodType = "HEAD"; if (context != null && StringUtils.isNotBlank(context.getRequest() .getParameter(ArtifactoryRequest.PARAM_REPLACE_HEAD_IN_RETRIEVE_INFO_WITH_GET))) { replaceHeadWithGet = Boolean.valueOf(context.getRequest() .getParameter(ArtifactoryRequest.PARAM_REPLACE_HEAD_IN_RETRIEVE_INFO_WITH_GET)); } if (replaceHeadWithGet) { log.debug("Param " + ArtifactoryRequest.PARAM_REPLACE_HEAD_IN_RETRIEVE_INFO_WITH_GET + " found in request" + " context, switching HEAD with GET request"); methodType = "GET"; method = new HttpGet(HttpUtils.encodeQuery(fullUrl)); } else { method = new HttpHead(HttpUtils.encodeQuery(fullUrl)); } RepoRequests.logToContext("Executing %s request to %s", methodType, fullUrl); CloseableHttpResponse response = null; try { HttpClientContext httpClientContext = new HttpClientContext(); notifyInterceptorsOnBeforeRemoteHttpMethodExecution(method, headers); response = executeMethod(method, httpClientContext, headers); return handleGetInfoResponse(repoPath, method, response, httpClientContext, context); } catch (IOException e) { String exceptionMessage = HttpClientUtils.getErrorMessage(e); RepoRequests.logToContext("Failed to execute %s request: %s", methodType, exceptionMessage); throw new RuntimeException("Failed retrieving resource from " + fullUrl + ": " + exceptionMessage, e); } finally { IOUtils.closeQuietly(response); } }
From source file:org.cloudifysource.dsl.internal.tools.download.ResourceDownloader.java
private InputStream openConnectionInputStream(final URL url) throws ResourceDownloadException { final DefaultHttpClient httpClient = new DefaultHttpClient(); final HttpHead httpMethod = new HttpHead(url.toString()); HttpResponse response;/*from w w w. j a v a2s . c o m*/ try { logger.fine("validating url"); response = httpClient.execute(httpMethod); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { logger.warning("Failed to validate Resource URL: " + url.toString()); throw new ResourceDownloadException("Invalid resource URL: " + url.toString()); } final URLConnection connection = url.openConnection(); if (this.userName != null || this.password != null) { logger.fine("Setting connection credentials"); String up = this.userName + ":" + this.password; String encoding = new String(Base64.encodeBase64(up.getBytes())); connection.setRequestProperty("Authorization", "Basic " + encoding); } return connection.getInputStream(); } catch (ClientProtocolException e) { throw new ResourceDownloadException("Invalid connection protocol " + url.toString(), e); } catch (IOException e) { throw new ResourceDownloadException("Invalid resource URL: " + url.toString(), e); } }
From source file:org.codice.solr.factory.impl.HttpSolrClientFactory.java
public static void createSolrCore(String url, String coreName, String configFileName, CloseableHttpClient httpClient) throws IOException, SolrServerException { try (CloseableHttpClient closeableHttpClient = httpClient; HttpSolrClient client = (httpClient != null ? new HttpSolrClient.Builder(url).withHttpClient(closeableHttpClient).build() : new HttpSolrClient.Builder(url).build())) { HttpResponse ping = client.getHttpClient().execute(new HttpHead(url)); if (ping != null && ping.getStatusLine().getStatusCode() == 200) { ConfigurationFileProxy configProxy = new ConfigurationFileProxy(ConfigurationStore.getInstance()); configProxy.writeSolrConfiguration(coreName); if (!solrCoreExists(client, coreName)) { LOGGER.debug("Solr({}): Creating Solr core", coreName); String configFile = StringUtils.defaultIfBlank(configFileName, DEFAULT_SOLRCONFIG_XML); String solrDir;/*w w w. java 2s .c o m*/ if (AccessController.doPrivileged( (PrivilegedAction<Boolean>) () -> System.getProperty(SOLR_DATA_DIR) != null)) { solrDir = AccessController .doPrivileged((PrivilegedAction<String>) () -> System.getProperty(SOLR_DATA_DIR)); } else { solrDir = Paths.get( AccessController.doPrivileged( (PrivilegedAction<String>) () -> System.getProperty("karaf.home")), "data", "solr").toString(); } String instanceDir = Paths.get(solrDir, coreName).toString(); String dataDir = Paths.get(instanceDir, "data").toString(); CoreAdminRequest.createCore(coreName, instanceDir, client, configFile, DEFAULT_SCHEMA_XML, dataDir, dataDir); } else { LOGGER.debug("Solr({}): Solr core already exists; reloading it", coreName); CoreAdminRequest.reloadCore(coreName, client); } } else { LOGGER.debug("Solr({}): Unable to ping Solr core at {}", coreName, url); throw new SolrServerException("Unable to ping Solr core"); } } }
From source file:org.codice.solr.factory.SolrClientFactory.java
private static void createSolrCore(String url, String coreName, String configFileName, HttpClient httpClient) throws IOException, SolrServerException { HttpSolrClient client;//from w ww . j a v a 2s . c om if (httpClient != null) { client = new HttpSolrClient(url, httpClient); } else { client = new HttpSolrClient(url); } HttpResponse ping = client.getHttpClient().execute(new HttpHead(url)); if (ping != null && ping.getStatusLine().getStatusCode() == 200) { if (!solrCoreExists(client, coreName)) { LOGGER.debug("Creating Solr core {}", coreName); String configFile = StringUtils.defaultIfBlank(configFileName, DEFAULT_SOLRCONFIG_XML); String instanceDir = Paths.get(System.getProperty("karaf.home"), "data", "solr", coreName) .toString(); CoreAdminRequest.createCore(coreName, instanceDir, client, configFile, DEFAULT_SCHEMA_XML); } else { LOGGER.debug("Solr core ({}) already exists - reloading it", coreName); CoreAdminRequest.reloadCore(coreName, client); } } else { LOGGER.debug("Unable to ping Solr core {}", coreName); throw new SolrServerException("Unable to ping Solr core"); } }
From source file:org.dasein.cloud.digitalocean.models.rest.DigitalOceanModelFactory.java
/** * Sent http request to the server//from w w w. j a v a2 s .c o m * @return Http response * @throws CloudException */ private static HttpResponse sendRequest(org.dasein.cloud.digitalocean.DigitalOcean provider, RESTMethod method, String token, String strUrl, DigitalOceanAction action) throws CloudException, InternalException { HttpRequestBase req = null; if (method == RESTMethod.GET) { req = new HttpGet(strUrl); } else if (method == RESTMethod.POST) { req = new HttpPost(strUrl); } else if (method == RESTMethod.PUT) { req = new HttpPut(strUrl); } else if (method == RESTMethod.DELETE) { req = new HttpDelete(strUrl); } else if (method == RESTMethod.HEAD) { req = new HttpHead(strUrl); } try { req.setHeader("Authorization", "Bearer " + token); req.setHeader("Accept", "application/json"); req.setHeader("Content-Type", "application/json;charset=UTF-8"); StringEntity requestEntity = null; if (req instanceof HttpEntityEnclosingRequestBase && action != null) { JSONObject jsonToPost = action.getParameters(); if (jsonToPost != null) { requestEntity = new StringEntity(jsonToPost.toString(), ContentType.APPLICATION_JSON); ((HttpEntityEnclosingRequestBase) req).setEntity(requestEntity); } } HttpClient httpClient = provider.getClient(); if (wire.isDebugEnabled()) { wire.debug(""); wire.debug( "--------------------------------------------------------------------------------------"); } if (wire.isDebugEnabled()) { wire.debug(req.getRequestLine().toString()); for (Header header : req.getAllHeaders()) { wire.debug(header.getName() + ": " + header.getValue()); } wire.debug(""); if (requestEntity != null) { try { wire.debug(EntityUtils.toString(requestEntity)); wire.debug(""); } catch (IOException ignore) { } } } HttpResponse response = null; int retryCount = 0; while (retryCount < 6) { response = httpClient.execute(req); if (wire.isDebugEnabled()) { wire.debug(response.getStatusLine().toString()); } if (method == RESTMethod.DELETE) { if ((response.getStatusLine().getStatusCode() == 204)) { break; } else { retryCount++; Thread.sleep(5000); } } else { break; } } if (method == RESTMethod.DELETE && (response.getStatusLine().getStatusCode() != 204)) { //Error occurred throw new CloudException("Delete method returned unexpected code, despite retrying."); } return response; } catch (JSONException e) { throw new CloudException("Problem sending request.", e); } catch (InterruptedException e) { throw new CloudException("Problem sending request.", e); } catch (ClientProtocolException e) { throw new CloudException("Problem sending request.", e); } catch (IOException e) { throw new CloudException("Problem sending request.", e); } finally { try { // req.releaseConnection(); } catch (Exception e) { } } }
From source file:org.fcrepo.integration.http.api.AbstractResourceIT.java
protected static void assertNotDeleted(final String id) { final String location = serverAddress + id; assertThat("Expected object not to be deleted", getStatus(new HttpHead(location)), is(OK.getStatusCode())); assertThat("Expected object not to be deleted", getStatus(new HttpGet(location)), is(OK.getStatusCode())); }