List of usage examples for org.apache.http.client.methods HttpUriRequest getMethod
String getMethod();
From source file:com.github.pascalgn.jiracli.web.HttpClient.java
private <T> T doExecute(HttpUriRequest request, boolean retry, Function<HttpEntity, T> function) { LOGGER.debug("Calling URL: {} [{}]", request.getURI(), request.getMethod()); // disable XSRF check: if (!request.containsHeader("X-Atlassian-Token")) { request.addHeader("X-Atlassian-Token", "nocheck"); }/*ww w. ja va2s .c om*/ HttpResponse response; try { response = httpClient.execute(request, httpClientContext); } catch (IOException e) { if (Thread.interrupted()) { LOGGER.trace("Could not call URL: {}", request.getURI(), e); throw new InterruptedError(); } else { throw new IllegalStateException("Could not call URL: " + request.getURI(), e); } } LOGGER.debug("Response received ({})", response.getStatusLine().toString().trim()); HttpEntity entity = response.getEntity(); try { if (Thread.interrupted()) { throw new InterruptedError(); } int statusCode = response.getStatusLine().getStatusCode(); if (isSuccess(statusCode)) { T result; try { result = function.apply(entity, Hint.none()); } catch (NotAuthenticatedException e) { if (retry) { resetAuthentication(); setCredentials(); return doExecute(request, false, function); } else { throw e.getCause(); } } catch (RuntimeException e) { if (Thread.interrupted()) { LOGGER.trace("Could not call URL: {}", request.getURI(), e); throw new InterruptedError(); } else { throw e; } } if (Thread.interrupted()) { throw new InterruptedError(); } return result; } else { if (statusCode == HttpURLConnection.HTTP_UNAUTHORIZED) { resetAuthentication(); if (retry) { setCredentials(); return doExecute(request, false, function); } else { String error = readErrorResponse(request.getURI(), entity); LOGGER.debug("Unauthorized [401]: {}", error); throw new AccessControlException("Unauthorized [401]: " + request.getURI()); } } else if (statusCode == HttpURLConnection.HTTP_FORBIDDEN) { resetAuthentication(); checkAccountLocked(response); if (retry) { setCredentials(); return doExecute(request, false, function); } else { throw new AccessControlException("Forbidden [403]: " + request.getURI()); } } else { String status = response.getStatusLine().toString().trim(); String message; if (entity == null) { message = status; } else { String error = readErrorResponse(request.getURI(), entity); message = status + (error.isEmpty() ? "" : ": " + error); } if (Thread.interrupted()) { throw new InterruptedError(); } if (statusCode == HttpURLConnection.HTTP_NOT_FOUND) { throw new NoSuchElementException(message); } else { throw new IllegalStateException(message); } } } } finally { EntityUtils.consumeQuietly(entity); } }
From source file:nl.esciencecenter.octopus.webservice.mac.MacScheme.java
private String getNormalizedRequestString(HttpUriRequest request, String nonce, Long timestamp) { URI uri = request.getURI();//from ww w .j av a 2 s . c om // request can become wrapped, causing the request.getURI() to miss host // and port if (request instanceof RequestWrapper) { uri = ((HttpUriRequest) ((RequestWrapper) request).getOriginal()).getURI(); } String normalized_request_string = timestamp + "\n"; normalized_request_string += nonce + "\n"; normalized_request_string += request.getMethod() + "\n"; normalized_request_string += uri.getPath() + "\n"; normalized_request_string += uri.getHost().toLowerCase() + "\n"; normalized_request_string += getPort(uri) + "\n"; normalized_request_string += "" + "\n"; return normalized_request_string; }
From source file:org.sonatype.nexus.proxy.storage.remote.httpclient.HttpClientRemoteStorage.java
/** * Executes the HTTP request.//from w w w. jav a 2 s . c o m * <p/> * In case of any exception thrown by HttpClient, it will release the connection. In other cases it * is the duty of caller to do it, or process the input stream. * * @param repository to execute the HTTP method fpr * @param request resource store request that triggered the HTTP request * @param httpRequest HTTP request to be executed * @return response of making the request * @throws RemoteStorageException If an error occurred during execution of HTTP request */ private HttpResponse executeRequest(final ProxyRepository repository, final ResourceStoreRequest request, final HttpUriRequest httpRequest) throws RemoteStorageException { final URI methodUri = httpRequest.getURI(); if (getLogger().isDebugEnabled()) { getLogger().debug( "Invoking HTTP " + httpRequest.getMethod() + " method against remote location " + methodUri); } final RemoteStorageContext ctx = getRemoteStorageContext(repository); final HttpClient httpClient = HttpClientUtil.getHttpClient(CTX_KEY, ctx); httpRequest.setHeader("user-agent", formatUserAgentString(ctx, repository)); httpRequest.setHeader("accept", "*/*"); httpRequest.setHeader("accept-language", "en-us"); httpRequest.setHeader("accept-encoding", "gzip,deflate,identity"); httpRequest.setHeader("cache-control", "no-cache"); // HTTP keep alive should not be used, except when NTLM is used final Boolean isNtlmUsed = HttpClientUtil.isNTLMAuthenticationUsed(CTX_KEY, ctx); if (isNtlmUsed == null || !isNtlmUsed) { httpRequest.setHeader("Connection", "close"); httpRequest.setHeader("Proxy-Connection", "close"); } HttpResponse httpResponse = null; try { httpResponse = httpClient.execute(httpRequest); final int statusCode = httpResponse.getStatusLine().getStatusCode(); final Header httpServerHeader = httpResponse.getFirstHeader("server"); checkForRemotePeerAmazonS3Storage(repository, httpServerHeader == null ? null : httpServerHeader.getValue()); Header proxyReturnedErrorHeader = httpResponse.getFirstHeader(NEXUS_MISSING_ARTIFACT_HEADER); boolean proxyReturnedError = proxyReturnedErrorHeader != null && Boolean.valueOf(proxyReturnedErrorHeader.getValue()); if (statusCode == HttpStatus.SC_FORBIDDEN) { throw new RemoteAccessDeniedException(repository, methodUri.toASCIIString(), httpResponse.getStatusLine().getReasonPhrase()); } else if (statusCode == HttpStatus.SC_UNAUTHORIZED) { throw new RemoteAuthenticationNeededException(repository, httpResponse.getStatusLine().getReasonPhrase()); } else if (statusCode == HttpStatus.SC_OK && proxyReturnedError) { throw new RemoteStorageException( "Invalid artifact found, most likely a proxy redirected to an HTML error page."); } return httpResponse; } catch (RemoteStorageException ex) { release(httpResponse); throw ex; } catch (ClientProtocolException ex) { release(httpResponse); throw new RemoteStorageException("Protocol error while executing " + httpRequest.getMethod() + " method. [repositoryId=\"" + repository.getId() + "\", requestPath=\"" + request.getRequestPath() + "\", remoteUrl=\"" + methodUri.toASCIIString() + "\"]", ex); } catch (IOException ex) { release(httpResponse); throw new RemoteStorageException("Transport error while executing " + httpRequest.getMethod() + " method [repositoryId=\"" + repository.getId() + "\", requestPath=\"" + request.getRequestPath() + "\", remoteUrl=\"" + methodUri.toASCIIString() + "\"]", ex); } }
From source file:org.dasein.cloud.azure.tests.network.AzureVlanSupportTest.java
@Test public void removeVlanShouldPostCorrectRequest() throws CloudException, InternalException { final AtomicInteger putCount = new AtomicInteger(0); new MockUp<CloseableHttpClient>() { @Mock/*from w ww. j ava 2 s . c o m*/ public CloseableHttpResponse execute(Invocation inv, HttpUriRequest request) throws IOException { if (request.getMethod().equals("GET") && VIRTUAL_NETWORK_SITES_URL.equals(request.getURI().toString())) { DaseinObjectToXmlEntity<VirtualNetworkSitesModel> daseinEntity = new DaseinObjectToXmlEntity<VirtualNetworkSitesModel>( createVirtualNetworkSitesModel(ID, NAME, REGION, CIDR, "Updating")); return getHttpResponseMock(getStatusLineMock(HttpServletResponse.SC_OK), daseinEntity, new Header[] { new BasicHeader("x-ms-request-id", UUID.randomUUID().toString()) }); } else if ("GET".equals(request.getMethod()) && NETWORK_CONFIG_URL.equals(request.getURI().toString())) { DaseinObjectToXmlEntity<NetworkConfigurationModel> daseinEntity = new DaseinObjectToXmlEntity<NetworkConfigurationModel>( createNetworkConfigurationModel(NAME, REGION, CIDR)); return getHttpResponseMock(getStatusLineMock(HttpServletResponse.SC_OK), daseinEntity, new Header[] { new BasicHeader("x-ms-request-id", UUID.randomUUID().toString()) }); } else if ("PUT".equals(request.getMethod())) { putCount.incrementAndGet(); NetworkConfigurationModel networkConfigurationModel = createNetworkConfigurationModel(null, null, null); assertPut(request, NETWORK_CONFIG_URL, new Header[] { new BasicHeader("x-ms-version", "2012-03-01") }, networkConfigurationModel); return getHttpResponseMock(getStatusLineMock(HttpServletResponse.SC_OK), null, new Header[] { new BasicHeader("x-ms-request-id", UUID.randomUUID().toString()) }); } else { throw new IOException("Request is not mocked"); } } }; vlanSupport.removeVlan(ID); assertEquals("removeVlan PUT network config should perform only 1 times", 1, putCount.get()); }
From source file:org.dasein.cloud.azure.tests.network.AzureVlanSupportTest.java
@Test public void removeSubnetShouldPostCorrectRequest() throws CloudException, InternalException { final AtomicInteger putCount = new AtomicInteger(0); new MockUp<CloseableHttpClient>() { @Mock//from w w w. java 2 s .co m public CloseableHttpResponse execute(Invocation inv, HttpUriRequest request) throws IOException { if (request.getMethod().equals("GET") && VIRTUAL_NETWORK_SITES_URL.equals(request.getURI().toString())) { DaseinObjectToXmlEntity<VirtualNetworkSitesModel> daseinEntity = new DaseinObjectToXmlEntity<VirtualNetworkSitesModel>( createVirtualNetworkSitesModelWithSubnet(ID, NAME, REGION, CIDR, "Created", SUBNET_NAME, SUBNET_CIDR)); return getHttpResponseMock(getStatusLineMock(HttpServletResponse.SC_OK), daseinEntity, new Header[] { new BasicHeader("x-ms-request-id", UUID.randomUUID().toString()) }); } else if ("GET".equals(request.getMethod()) && NETWORK_CONFIG_URL.equals(request.getURI().toString())) { DaseinObjectToXmlEntity<NetworkConfigurationModel> daseinEntity = new DaseinObjectToXmlEntity<NetworkConfigurationModel>( createNetworkConfigurationModelWithSubnet(NAME, REGION, CIDR, SUBNET_NAME, SUBNET_CIDR)); return getHttpResponseMock(getStatusLineMock(HttpServletResponse.SC_OK), daseinEntity, new Header[] { new BasicHeader("x-ms-request-id", UUID.randomUUID().toString()) }); } else if ("PUT".equals(request.getMethod())) { putCount.incrementAndGet(); NetworkConfigurationModel networkConfigurationModel = createNetworkConfigurationModelWithSubnet( NAME, REGION, CIDR, null, null); assertPut(request, NETWORK_CONFIG_URL, new Header[] { new BasicHeader("x-ms-version", "2012-03-01") }, networkConfigurationModel); return getHttpResponseMock(getStatusLineMock(HttpServletResponse.SC_OK), null, new Header[] { new BasicHeader("x-ms-request-id", UUID.randomUUID().toString()) }); } else { throw new IOException("Request is not mocked"); } } }; vlanSupport.removeSubnet(SUBNET_ID); assertEquals("removeVlan PUT network config should perform only 1 times", 1, putCount.get()); }
From source file:org.dasein.cloud.azurepack.tests.compute.AzurePackVirtualMachineSupportTest.java
@Test public void terminateShouldSendCorrectRequest() throws CloudException, InternalException { final AtomicInteger deleteCount = new AtomicInteger(0); new GetOrListVirtualMachinesRequestExecutorMockUp() { @Mock// w w w. j a v a 2 s . c om public void $init(CloudProvider provider, HttpClientBuilder clientBuilder, HttpUriRequest request, ResponseHandler handler) { String requestUri = request.getURI().toString(); if (request.getMethod().equals("DELETE") && requestUri .equals(String.format(VM_RESOURCES, ENDPOINT, ACCOUNT_NO, DATACENTER_ID, VM_1_ID))) { requestResourceType = 11; } else { super.$init(provider, clientBuilder, request, handler); } } @Mock public Object execute() { if (requestResourceType == 11) { deleteCount.incrementAndGet(); return ""; } else { return super.execute(); } } }; azurePackVirtualMachineSupport.terminate(VM_1_ID, "no reason"); assertEquals("terminate doesn't send DELETE request", 1, deleteCount.get()); }
From source file:jetbrains.buildServer.commitPublisher.github.api.impl.GitHubApiImpl.java
private void logFailedResponse(@NotNull HttpUriRequest request, @Nullable String requestEntity, @NotNull HttpResponse execute) throws IOException { String responseText = extractResponseEntity(execute); if (responseText == null) { responseText = "<none>"; }//from w w w . j ava 2 s . c o m if (requestEntity == null) { requestEntity = "<none>"; } LOG.warn("Failed to complete query to GitHub with:\n" + " requestURL: " + request.getURI().toString() + "\n" + " requestMethod: " + request.getMethod() + "\n" + " requestEntity: " + requestEntity + "\n" + " response: " + execute.getStatusLine() + "\n" + " responseEntity: " + responseText); }
From source file:org.dasein.cloud.azurepack.tests.compute.AzurePackVirtualMachineSupportTest.java
@Test(expected = InternalException.class) public void lauchShouldThrowExceptionIfLaunchFromVHDWithDefaultProduct() throws CloudException, InternalException { final AtomicInteger postCount = new AtomicInteger(0); new StartOrStopVirtualMachinesRequestExecutorMockUp("Start") { @Mock/*from w ww.j a v a2 s .c o m*/ public void $init(CloudProvider provider, HttpClientBuilder clientBuilder, HttpUriRequest request, ResponseHandler handler) { String requestUri = request.getURI().toString(); if (request.getMethod().equals("POST") && requestUri.equals(String.format(LIST_VM_RESOURCES, ENDPOINT, ACCOUNT_NO))) { requestResourceType = 21; WAPVirtualMachineModel wapVirtualMachineModel = new WAPVirtualMachineModel(); wapVirtualMachineModel.setName(VM_1_NAME); wapVirtualMachineModel.setCloudId(REGION); wapVirtualMachineModel.setStampId(DATACENTER_ID); wapVirtualMachineModel.setVirtualHardDiskId(VHD_1_ID); wapVirtualMachineModel.setHardwareProfileId(HWP_1_ID); List<WAPNewAdapterModel> adapters = new ArrayList<>(); WAPNewAdapterModel newAdapterModel = new WAPNewAdapterModel(); newAdapterModel.setVmNetworkName(VM_1_NETWORK_NAME); adapters.add(newAdapterModel); wapVirtualMachineModel.setNewVirtualNetworkAdapterInput(adapters); } else { super.$init(provider, clientBuilder, request, handler); } responseHandler = handler; } @Mock public Object execute() { if (requestResourceType == 21) { postCount.incrementAndGet(); return mapFromModel(this.responseHandler, createWAPVirtualMachineModel()); } else { return super.execute(); } } }; VMLaunchOptions vmLaunchOptions = VMLaunchOptions.getInstance("default", VHD_1_ID, VM_1_NAME, VM_1_DESCRIPTION); vmLaunchOptions.inVlan(null, DATACENTER_ID, VM_1_NETWORK_ID); azurePackVirtualMachineSupport.launch(vmLaunchOptions); }
From source file:org.dasein.cloud.azurepack.tests.compute.AzurePackVirtualMachineSupportTest.java
@Test public void lauchVhdVMShouldSendCorrectRequest() throws CloudException, InternalException { final AtomicInteger postCount = new AtomicInteger(0); new StartOrStopVirtualMachinesRequestExecutorMockUp("Start") { @Mock/* ww w .j a v a 2 s . c o m*/ public void $init(CloudProvider provider, HttpClientBuilder clientBuilder, HttpUriRequest request, ResponseHandler handler) { String requestUri = request.getURI().toString(); if (request.getMethod().equals("POST") && requestUri.equals(String.format(LIST_VM_RESOURCES, ENDPOINT, ACCOUNT_NO))) { requestResourceType = 21; WAPVirtualMachineModel wapVirtualMachineModel = new WAPVirtualMachineModel(); wapVirtualMachineModel.setName(VM_1_NAME); wapVirtualMachineModel.setCloudId(REGION); wapVirtualMachineModel.setStampId(DATACENTER_ID); wapVirtualMachineModel.setVirtualHardDiskId(VHD_1_ID); wapVirtualMachineModel.setHardwareProfileId(HWP_1_ID); List<WAPNewAdapterModel> adapters = new ArrayList<>(); WAPNewAdapterModel newAdapterModel = new WAPNewAdapterModel(); newAdapterModel.setVmNetworkName(VM_1_NETWORK_NAME); adapters.add(newAdapterModel); wapVirtualMachineModel.setNewVirtualNetworkAdapterInput(adapters); assertPost(request, String.format(LIST_VM_RESOURCES, ENDPOINT, ACCOUNT_NO), new Header[0], wapVirtualMachineModel); } else { super.$init(provider, clientBuilder, request, handler); } responseHandler = handler; } @Mock public Object execute() { if (requestResourceType == 21) { postCount.incrementAndGet(); return mapFromModel(this.responseHandler, createWAPVirtualMachineModel()); } else { return super.execute(); } } }; VMLaunchOptions vmLaunchOptions = VMLaunchOptions.getInstance(HWP_1_ID, VHD_1_ID, VM_1_NAME, VM_1_DESCRIPTION); vmLaunchOptions.inVlan(null, DATACENTER_ID, VM_1_NETWORK_ID); VirtualMachine virtualMachine = azurePackVirtualMachineSupport.launch(vmLaunchOptions); assertEquals("terminate doesn't send DELETE request", 1, postCount.get()); assertVirtualMachine(virtualMachine); }