Java Code Examples for org.apache.http.HttpResponse

The following examples show how to use org.apache.http.HttpResponse. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: cxf   Source File: CrossOriginSimpleTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void preflightPostClassAnnotationFail() throws ClientProtocolException, IOException {
    HttpClient httpclient = HttpClientBuilder.create().build();
    HttpOptions httpoptions = new HttpOptions("http://localhost:" + PORT + "/antest/unannotatedPost");
    httpoptions.addHeader("Origin", "http://in.org");
    // nonsimple header
    httpoptions.addHeader("Content-Type", "application/json");
    httpoptions.addHeader(CorsHeaderConstants.HEADER_AC_REQUEST_METHOD, "POST");
    httpoptions.addHeader(CorsHeaderConstants.HEADER_AC_REQUEST_HEADERS, "X-custom-1");
    HttpResponse response = httpclient.execute(httpoptions);
    assertEquals(200, response.getStatusLine().getStatusCode());
    assertEquals(0, response.getHeaders(CorsHeaderConstants.HEADER_AC_ALLOW_ORIGIN).length);
    assertEquals(0, response.getHeaders(CorsHeaderConstants.HEADER_AC_ALLOW_HEADERS).length);
    assertEquals(0, response.getHeaders(CorsHeaderConstants.HEADER_AC_ALLOW_METHODS).length);
    if (httpclient instanceof Closeable) {
        ((Closeable)httpclient).close();
    }

}
 
Example 2
Source Project: onos   Source File: OpenstackNetworkingUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Serializes HttpResponse header to byte array.
 *
 * @param response http response object
 * @return byte array
 */
public static byte[] unparseHttpResponseHeader(HttpResponse response) {
    try {
        SessionOutputBufferImpl sessionOutputBuffer =
                new SessionOutputBufferImpl(
                        new HttpTransportMetricsImpl(), HTTP_PAYLOAD_BUFFER);

        ByteArrayOutputStream headerBaos = new ByteArrayOutputStream();
        sessionOutputBuffer.bind(headerBaos);

        HttpMessageWriter<HttpResponse> responseWriter =
                new DefaultHttpResponseWriter(sessionOutputBuffer);
        responseWriter.write(response);
        sessionOutputBuffer.flush();

        log.debug(headerBaos.toString(Charsets.UTF_8.name()));

        return headerBaos.toByteArray();
    } catch (IOException | HttpException e) {
        log.warn("Failed to unparse HttpResponse headers, due to {}", e);
    }

    return null;
}
 
Example 3
Source Project: Sentinel   Source File: MetricFetcher.java    License: Apache License 2.0 6 votes vote down vote up
private void handleResponse(final HttpResponse response, MachineInfo machine,
                            Map<String, MetricEntity> metricMap) throws Exception {
    int code = response.getStatusLine().getStatusCode();
    if (code != HTTP_OK) {
        return;
    }
    Charset charset = null;
    try {
        String contentTypeStr = response.getFirstHeader("Content-type").getValue();
        if (StringUtil.isNotEmpty(contentTypeStr)) {
            ContentType contentType = ContentType.parse(contentTypeStr);
            charset = contentType.getCharset();
        }
    } catch (Exception ignore) {
    }
    String body = EntityUtils.toString(response.getEntity(), charset != null ? charset : DEFAULT_CHARSET);
    if (StringUtil.isEmpty(body) || body.startsWith(NO_METRICS)) {
        //logger.info(machine.getApp() + ":" + machine.getIp() + ":" + machine.getPort() + ", bodyStr is empty");
        return;
    }
    String[] lines = body.split("\n");
    //logger.info(machine.getApp() + ":" + machine.getIp() + ":" + machine.getPort() +
    //    ", bodyStr.length()=" + body.length() + ", lines=" + lines.length);
    handleBody(lines, machine, metricMap);
}
 
Example 4
Source Project: multiapps-controller   Source File: CsrfHttpClient.java    License: Apache License 2.0 6 votes vote down vote up
private String fetchNewCsrfToken() throws IOException {
    if (csrfGetTokenUrl == null) {
        return null;
    }

    HttpGet fetchTokenRequest = new HttpGet(csrfGetTokenUrl);
    fetchTokenRequest.addHeader(CSRF_TOKEN_HEADER_NAME, CSRF_TOKEN_HEADER_FETCH_VALUE);
    setHttpRequestHeaders(fetchTokenRequest);
    HttpResponse response = delegate.execute(fetchTokenRequest);
    EntityUtils.consume(response.getEntity());
    if (response.containsHeader(CSRF_TOKEN_HEADER_NAME)) {
        return response.getFirstHeader(CSRF_TOKEN_HEADER_NAME)
                       .getValue();
    }

    return null;
}
 
Example 5
Source Project: apigee-android-sdk   Source File: CacheEntryUpdater.java    License: Apache License 2.0 6 votes vote down vote up
protected Header[] mergeHeaders(HttpCacheEntry entry, HttpResponse response) {
	List<Header> cacheEntryHeaderList = new ArrayList<Header>(
			Arrays.asList(entry.getAllHeaders()));

	if (entryAndResponseHaveDateHeader(entry, response)
			&& entryDateHeaderNewerThenResponse(entry, response)) {
		// Don't merge Headers, keep the entries headers as they are newer.
		removeCacheEntry1xxWarnings(cacheEntryHeaderList, entry);

		return cacheEntryHeaderList.toArray(new Header[cacheEntryHeaderList
				.size()]);
	}

	removeCacheHeadersThatMatchResponse(cacheEntryHeaderList, response);
	removeCacheEntry1xxWarnings(cacheEntryHeaderList, entry);
	cacheEntryHeaderList.addAll(Arrays.asList(response.getAllHeaders()));

	return cacheEntryHeaderList.toArray(new Header[cacheEntryHeaderList
			.size()]);
}
 
Example 6
Source Project: Alite   Source File: DownloadThread.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * Check the HTTP response status and handle anything unusual (e.g. not
 * 200/206).
 */
private void handleExceptionalStatus(State state, InnerState innerState, HttpResponse response)
        throws StopRequest, RetryDownload {
    int statusCode = response.getStatusLine().getStatusCode();
    if (statusCode == 503 && mInfo.mNumFailed < Constants.MAX_RETRIES) {
        handleServiceUnavailable(state, response);
    }
    if (statusCode == 301 || statusCode == 302 || statusCode == 303 || statusCode == 307) {
        handleRedirect(state, response, statusCode);
    }

    int expectedStatus = innerState.mContinuingDownload ? 206
            : DownloaderService.STATUS_SUCCESS;
    if (statusCode != expectedStatus) {
        handleOtherStatus(state, innerState, statusCode);
    } else {
        // no longer redirected
        state.mRedirectCount = 0;
    }
}
 
Example 7
private static String getExifToolsZipUrl(HttpClient httpClient) throws IOException {
    HttpGet request = new HttpGet(exifToolRslUrl);
    HttpResponse response = httpClient.execute(request);
    try (BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()))) {
        StringBuilder result = new StringBuilder();
        String line;
        while ((line = rd.readLine()) != null) {
            result.append(line);
        }

        Matcher m = namePattern.matcher(result.toString());
        if (m.find()) {
            return m.group(0);
        } else {
            throw new IOException("Cannot find the exiftool url in the provided rss");
        }
    }
}
 
Example 8
Source Project: olingo-odata4   Source File: TripPinServiceTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testReadEntityWithFullMetadata() throws Exception {
  HttpResponse response = httpGET(
      baseURL+ "/People('russellwhyte')?$format=application/json;odata.metadata=full",
      200);
  JsonNode node = getJSONNode(response);
  assertEquals("#Collection(String)", node.get("[email protected]").asText());
  assertEquals("Microsoft.OData.SampleService.Models.TripPin.ShareTrip",
      node.get("#Microsoft.OData.SampleService.Models.TripPin.ShareTrip").get("title").asText());
  assertEquals("/People('russellwhyte')/Microsoft.OData.SampleService.Models.TripPin.ShareTrip",
      node.get("#Microsoft.OData.SampleService.Models.TripPin.ShareTrip").get("target").asText());    

  assertEquals("Microsoft.OData.SampleService.Models.TripPin.GetFavoriteAirline",
      node.get("#Microsoft.OData.SampleService.Models.TripPin.GetFavoriteAirline").get("title").asText());
  assertEquals("/People('russellwhyte')/Microsoft.OData.SampleService.Models.TripPin.GetFavoriteAirline",
      node.get("#Microsoft.OData.SampleService.Models.TripPin.GetFavoriteAirline").get("target").asText());    

  assertEquals("Microsoft.OData.SampleService.Models.TripPin.GetFriendsTrips",
      node.get("#Microsoft.OData.SampleService.Models.TripPin.GetFriendsTrips(userName)").get("title").asText());
  assertEquals("/People('russellwhyte')/Microsoft.OData."
      + "SampleService.Models.TripPin.GetFriendsTrips([email protected])",
      node.get("#Microsoft.OData.SampleService.Models.TripPin.GetFriendsTrips(userName)").get("target").asText());
}
 
Example 9
Source Project: JavaRushTasks   Source File: Solution.java    License: MIT License 6 votes vote down vote up
public void sendPost(String url, String urlParameters) throws Exception {
    HttpClient client = getHttpClient();
    HttpPost request = new HttpPost(url);
    request.addHeader("User-Agent", "Mozilla/5.0");

    List<NameValuePair> valuePairs = new ArrayList<NameValuePair>();
    String[] s = urlParameters.split("&");
    for (int i = 0; i < s.length; i++) {
        String g = s[i];
        valuePairs.add(new BasicNameValuePair(g.substring(0,g.indexOf("=")), g.substring(g.indexOf("=")+1)));
    }

    request.setEntity(new UrlEncodedFormEntity(valuePairs));
    HttpResponse response = client.execute(request);
    System.out.println("Response Code: " + response.getStatusLine().getStatusCode());

    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
    StringBuffer result = new StringBuffer();
    String responseLine;
    while ((responseLine = bufferedReader.readLine()) != null) {
        result.append(responseLine);
    }

    System.out.println("Response: " + result.toString());
}
 
Example 10
Source Project: google-http-java-client   Source File: MockHttpClient.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected RequestDirector createClientRequestDirector(
    HttpRequestExecutor requestExec,
    ClientConnectionManager conman,
    ConnectionReuseStrategy reustrat,
    ConnectionKeepAliveStrategy kastrat,
    HttpRoutePlanner rouplan,
    HttpProcessor httpProcessor,
    HttpRequestRetryHandler retryHandler,
    RedirectHandler redirectHandler,
    AuthenticationHandler targetAuthHandler,
    AuthenticationHandler proxyAuthHandler,
    UserTokenHandler stateHandler,
    HttpParams params) {
  return new RequestDirector() {
    @Beta
    public HttpResponse execute(HttpHost target, HttpRequest request, HttpContext context)
        throws HttpException, IOException {
      return new BasicHttpResponse(HttpVersion.HTTP_1_1, responseCode, null);
    }
  };
}
 
Example 11
public void execute(final URI serviceEndpoint) throws Exception {
  HttpRequestBase request = null;

  try {
    String endpoint = serviceEndpoint.toASCIIString();
    String requestUrl = endpoint.substring(0, endpoint.length() - 1) + path;
    if (queryOptions != null) {
      requestUrl += queryOptions;
    }
    request = this.request.createRequest(requestUrl);

    requestLine = request.getRequestLine().toString();
    HttpClient httpClient = new DefaultHttpClient();

    LOG.debug("Execute test for [" + requestLine + "]");
    final HttpResponse response = httpClient.execute(request);
    LOG.debug("Got response for request [" + requestLine + "]");

    int resultStatusCode = response.getStatusLine().getStatusCode();
    assertEquals("Unexpected status code for " + toString(), expectedStatusCode.getStatusCode(), resultStatusCode);

    final String contentType = response.getFirstHeader(HttpHeaders.CONTENT_TYPE).getValue();
    assertEquals("Unexpected content type for " + toString(), ContentType.create(expectedContentType), ContentType
        .create(contentType));

    if (isContentExpected) {
      assertNotNull("Unexpected content for " + toString(), StringHelper.inputStreamToString(response.getEntity()
          .getContent()));
    }
    LOG.trace("Test passed [" + toString() + "]");
  } finally {
    if (request != null) {
      request.releaseConnection();
      LOG.debug("Released connection [" + requestLine + "]");
    }
  }
}
 
Example 12
private String getErrorString(HttpResponse response)
		throws IllegalStateException, IOException {
	StringWriter writer = new StringWriter();
	IOUtils.copy(response.getEntity().getContent(), writer, "UTF-8");
	String body = writer.toString();
	return "Error: " + response.getStatusLine() + " - " + body;
}
 
Example 13
@Test
public void fetchMetaData() throws Exception {
  HttpResponse httpResponse = client.fetch(YAML_FILE_NAME, CONTENT_TYPE_YAML);

  assertThat(status(httpResponse), is(HttpStatus.OK));
  assertThat(bytes(httpResponse), is(Files.toByteArray(testData.resolveFile(YAML_FILE_NAME))));
}
 
Example 14
Source Project: blueflood   Source File: HttpAnnotationsEndToEndTest.java    License: Apache License 2.0 5 votes vote down vote up
private HttpResponse postEvent(String requestBody, String tenantId) throws Exception {
    URIBuilder builder = new URIBuilder().setScheme("http").setHost("127.0.0.1")
            .setPort(httpPort).setPath("/v2.0/" + tenantId + "/events");
    HttpPost post = new HttpPost(builder.build());
    HttpEntity entity = new StringEntity(requestBody,
            ContentType.APPLICATION_JSON);
    post.setEntity(entity);
    post.setHeader(Event.FieldLabels.tenantId.name(), tenantId);
    post.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.toString());
    HttpResponse response = client.execute(post);
    return response;
}
 
Example 15
Source Project: geoportal-server-harvester   Source File: DataGovBroker.java    License: Apache License 2.0 5 votes vote down vote up
private MimeType readContentType(HttpResponse httpResponse) {
  Header contentTypeHeader = httpResponse.getFirstHeader("Content-Type");
  String contentType = contentTypeHeader!=null? contentTypeHeader.getValue(): null;
  if (contentType!=null) {
    int semiCol = contentType.indexOf(";");
    if (semiCol>=0) {
      contentType = contentType.substring(0, semiCol);
    }
  }
  return MimeType.parse(contentType);
}
 
Example 16
Source Project: quarkus-http   Source File: RealPathTestCase.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testRealPath() throws Exception {
    HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL() + "/servletContext/path/real-path");
    HttpResponse result = new TestHttpClient().execute(get);
    Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
    String response = HttpClientUtils.readResponse(result);
    Assert.assertEquals(Paths.get(RealPathTestCase.class.getResource("file.txt").toURI()).toString(), response);
}
 
Example 17
private HttpResponse getStaticApiRefreshResponse(String endpoint, int returnCode) throws IOException {
    URI uri = HttpRequestUtils.getUriFromGateway(endpoint);
    HttpPost request = new HttpPost(uri);
    String cookie = HttpSecurityUtils.getCookieForGateway();
    HttpSecurityUtils.addCookie(request, cookie);

    // When
    HttpResponse response = HttpClientUtils.client().execute(request);

    // Then
    assertThat(response.getStatusLine().getStatusCode(), equalTo(returnCode));

    return response;
}
 
Example 18
Source Project: attic-polygene-java   Source File: WebRealmServiceTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void test()
    throws IOException
{
    DefaultHttpClient client = new DefaultHttpClient();

    // Our request method
    HttpGet get = new HttpGet( "http://127.0.0.1:" + port + "/" );

    HttpResponse response = client.execute( get );
    int status = response.getStatusLine().getStatusCode();

    assertThat( String.valueOf( status ).substring( 0, 1 ) + "xx", is( "4xx" ) );

    EntityUtils.consume( response.getEntity() );

    // Simple interceptor set as first interceptor in the protocol chain
    HttpRequestInterceptor preemptiveAuth = new BasicAuthRequestInterceptor();
    client.addRequestInterceptor( preemptiveAuth, 0 );

    // Set credentials
    UsernamePasswordCredentials creds = new UsernamePasswordCredentials( "foo", "bar" );
    client.getCredentialsProvider().setCredentials( AuthScope.ANY, creds );

    response = client.execute( get );
    status = response.getStatusLine().getStatusCode();

    assertThat( status, is( 200 ) );

    String result = new BasicResponseHandler().handleResponse( response ).trim();
    assertThat( result, is( "FOO" ) );
}
 
Example 19
@Test
public void testShouldThrowExceptionWhenGettingRemoteMetadataVersionWithServerError()
    throws Exception
{
    when( metadataSystemSettingService.getRemoteInstanceUserName() ).thenReturn( username );
    when( metadataSystemSettingService.getRemoteInstancePassword() ).thenReturn( password );

    String response = "{\"name\":\"testVersion\",\"created\":\"2016-05-26T11:43:59.787+0000\",\"type\":\"BEST_EFFORT\",\"id\":\"ktwh8PHNwtB\",\"hashCode\":\"12wa32d4f2et3tyt5yu6i\"}";
    MetadataVersion metadataVersion = new MetadataVersion( "testVersion", VersionType.BEST_EFFORT );
    metadataVersion.setHashCode( "12wa32d4f2et3tyt5yu6i" );

    AvailabilityStatus availabilityStatus = new AvailabilityStatus( true, "test_message", null );
    when( synchronizationManager.isRemoteServerAvailable() ).thenReturn( availabilityStatus );

    HttpResponse httpResponse = mock( HttpResponse.class );

    DhisHttpResponse dhisHttpResponse = new DhisHttpResponse( httpResponse, response,
        HttpStatus.GATEWAY_TIMEOUT.value() );

    when( metadataSystemSettingService.getVersionDetailsUrl( "testVersion" ) ).thenReturn( versionUrl );
    when( synchronizationManager.isRemoteServerAvailable() ).thenReturn( availabilityStatus );
    PowerMockito.when( HttpUtils.httpGET( versionUrl, true, username, password, null, VERSION_TIMEOUT, true ) )
        .thenReturn( dhisHttpResponse );

    expectedException.expect( MetadataVersionServiceException.class );
    expectedException.expectMessage( "Server Error. Http call failed with status code: "
        + HttpStatus.GATEWAY_TIMEOUT.value() + " Caused by: " + response );

    target.getRemoteMetadataVersion( "testVersion" );
}
 
Example 20
Source Project: olingo-odata4   Source File: AsyncRequestWrapperImpl.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private R instantiateResponse(final HttpResponse res) {
  R odataResponse;
  try {
    odataResponse = (R) ((AbstractODataRequest) odataRequest).getResponseTemplate().initFromEnclosedPart(res
        .getEntity().getContent());
  } catch (Exception e) {
    LOG.error("Error instantiating odata response", e);
    odataResponse = null;
  } finally {
    HttpClientUtils.closeQuietly(res);
  }
  return odataResponse;
}
 
Example 21
@Test
public void testFileUploadWithSmallFileSizeThreshold() throws Exception {
    DefaultServer.setRootHandler(new BlockingHandler(createInMemoryReadingHandler(10)));

    TestHttpClient client = new TestHttpClient();
    try {

        HttpPost post = new HttpPost(DefaultServer.getDefaultServerURL() + "/path");
        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

        entity.addPart("formValue", new StringBody("myValue", "text/plain", StandardCharsets.UTF_8));
        entity.addPart("file", new FileBody(new File(MultipartFormDataParserTestCase.class.getResource("uploadfile.txt").getFile())));

        post.setEntity(entity);
        HttpResponse result = client.execute(post);
        Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
        String resp = HttpClientUtils.readResponse(result);

        Map<String, String> parsedResponse = parse(resp);

        Assert.assertEquals("false", parsedResponse.get("in_memory"));
        Assert.assertEquals("uploadfile.txt", parsedResponse.get("file_name"));
        Assert.assertEquals(DigestUtils.md5Hex(new FileInputStream(new File(MultipartFormDataParserTestCase.class.getResource("uploadfile.txt").getFile()))), parsedResponse.get("hash"));

    } finally {
        client.getConnectionManager().shutdown();
    }
}
 
Example 22
Source Project: olingo-odata2   Source File: RequestContentTypeTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void textContentType() throws Exception {
  HttpPut put = new HttpPut(URI.create(getEndpoint().toString() + "Rooms('1')/Seats/$value"));
  put.setHeader(HttpHeaders.CONTENT_TYPE, "text");
  final HttpResponse response = getHttpClient().execute(put);
  assertEquals(HttpStatusCodes.UNSUPPORTED_MEDIA_TYPE.getStatusCode(), response.getStatusLine().getStatusCode());
}
 
Example 23
Source Project: olingo-odata2   Source File: EntryJsonCreateTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void createEntryRoomWithLink() throws Exception {
  final String id = UUID.randomUUID().toString();
  String content = "{\"d\":{\"__metadata\":{\"id\":\"" + getEndpoint() + "Rooms('1')\","
      + "\"uri\":\"" + getEndpoint() + "Rooms('1')\",\"type\":\"RefScenario.Room\","
      + "\"etag\":\"W/\\\"3\\\"\"},"
      + "\"Id\":\"" + id + "\",\"Name\":\"Room 104\","
      + "\"nr_Employees\":{\"__deferred\":{\"uri\":\"" + getEndpoint() + "Rooms('1')/nr_Employees\"}},"
      + "\"nr_Building\":{\"__deferred\":{\"uri\":\"" + getEndpoint() + "Rooms('1')/nr_Building\"}}}}";
  assertNotNull(content);
  HttpResponse response =
      postUri("Rooms", content, HttpContentType.APPLICATION_JSON, HttpHeaders.ACCEPT,
          HttpContentType.APPLICATION_JSON, HttpStatusCodes.CREATED);
  checkMediaType(response, HttpContentType.APPLICATION_JSON);

  String body = getBody(response);
  LinkedTreeMap<?,?> map = getStringMap(body);
  assertEquals(id, map.get("Id"));
  assertEquals("Room 104", map.get("Name"));
  @SuppressWarnings("unchecked")
  LinkedTreeMap<String, Object> employeesMap = (LinkedTreeMap<String, Object>) map.get("nr_Employees");
  assertNotNull(employeesMap);
  @SuppressWarnings("unchecked")
  LinkedTreeMap<String, String> deferredMap = (LinkedTreeMap<String, String>) employeesMap.get("__deferred");
  assertNotNull(deferredMap);
  assertEquals(getEndpoint() + "Rooms('" + id + "')/nr_Employees", deferredMap.get("uri"));
}
 
Example 24
/**
 * constructor.
 */
@Test(enabled = true, description = "Trigger contract by http")
public void test3TriggerConstantContract() {

  HttpResponse httpResponse = HttpMethed
      .triggerConstantContract(httpnode, assetOwnerAddress, contractAddress,
          "testView()",
          "");

  responseContent = HttpMethed.parseResponseContent(httpResponse);
  HttpMethed.printJsonContent(responseContent);
  Assert.assertEquals(responseContent.getString("result"), "{\"result\":true}");
  Assert.assertEquals(responseContent.getString("constant_result"),
      "[\"0000000000000000000000000000000000000000000000000000000000000001\"]");
}
 
Example 25
private void errorRetry() {
    String newAddress;
    boolean acquire;
    int retryTimes = this.batchPutRetryTimes;
    while (true) {
        newAddress = getNextAddress();
        acquire = this.hitsdbHttpClient.getSemaphoreManager().acquire(newAddress);
        retryTimes--;
        if (acquire || retryTimes <= 0) {
            break;
        }
    }

    if (retryTimes == 0) {
        this.hitsdbHttpClient.getSemaphoreManager().release(address);
        return;
    }

    // retry!
    LOGGER.warn("retry put data!");
    HttpResponseCallbackFactory httpResponseCallbackFactory = this.hitsdbHttpClient.getHttpResponseCallbackFactory();

    FutureCallback<HttpResponse> retryCallback;
    if (batchPutCallback != null) {
        retryCallback = httpResponseCallbackFactory.createBatchPutDataCallback(newAddress, this.batchPutCallback, this.pointList, this.config);
    } else {
        retryCallback = httpResponseCallbackFactory.createNoLogicBatchPutHttpFutureCallback(newAddress, this.pointList, this.config, retryTimes);
    }

    String jsonString = JSON.toJSONString(pointList);
    this.hitsdbHttpClient.post(HttpAPI.PUT, jsonString, retryCallback);
}
 
Example 26
Source Project: forge-api-java-client   Source File: OAuth2ThreeLegged.java    License: Apache License 2.0 5 votes vote down vote up
private String execute(HttpRequestBase request) throws ClientProtocolException, IOException, ApiException {
    HttpClient httpClient = HttpClientBuilder.create().build();
    HttpResponse response = httpClient.execute(request);

    HttpEntity entity = response.getEntity();
    String body = EntityUtils.toString(entity);

    int status = response.getStatusLine().getStatusCode();
    if (status != 200) {
        throw new ApiException(status, body);
    }

    return body;
}
 
Example 27
Source Project: knox   Source File: NiFiHaDispatch.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void executeRequest(HttpUriRequest outboundRequest, HttpServletRequest inboundRequest, HttpServletResponse outboundResponse) throws IOException {
  HttpResponse inboundResponse = null;
  try {
    outboundRequest = NiFiRequestUtil.modifyOutboundRequest(outboundRequest, inboundRequest);
    inboundResponse = executeOutboundRequest(outboundRequest);
    writeOutboundResponse(outboundRequest, inboundRequest, outboundResponse, inboundResponse);
  } catch (IOException e) {
    LOG.errorConnectingToServer(outboundRequest.getURI().toString(), e);
    failoverRequest(outboundRequest, inboundRequest, outboundResponse, inboundResponse, e);
  }
}
 
Example 28
Source Project: AndroidProjects   Source File: HttpClientStack.java    License: MIT License 5 votes vote down vote up
@Override
public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders)
        throws IOException, AuthFailureError {
    HttpUriRequest httpRequest = createHttpRequest(request, additionalHeaders);
    addHeaders(httpRequest, additionalHeaders);
    addHeaders(httpRequest, request.getHeaders());
    onPrepareRequest(httpRequest);
    HttpParams httpParams = httpRequest.getParams();
    int timeoutMs = request.getTimeoutMs();
    // TODO: Reevaluate this connection timeout based on more wide-scale
    // data collection and possibly different for wifi vs. 3G.
    HttpConnectionParams.setConnectionTimeout(httpParams, 5000);
    HttpConnectionParams.setSoTimeout(httpParams, timeoutMs);
    return mClient.execute(httpRequest);
}
 
Example 29
Source Project: product-ei   Source File: ActivitiRestClient.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Mehtod to delegate a task to certain user
 *
 * @param taskID used to identify the task to be delegated
 * @return String with the status of the delegation
 * @throws IOException
 */
public String delegateTaskByTaskId(String taskID) throws IOException {
    String url = serviceURL + "runtime/tasks/" + taskID;
    DefaultHttpClient httpClient = getHttpClient();
    HttpPost httpPost = new HttpPost(url);
    StringEntity params = new StringEntity("{\"action\" : \"delegate\"," +
                                           "\"assignee\" :\"" + USER_DELEGATE + "\"}",
                                           ContentType.APPLICATION_JSON);
    httpPost.setEntity(params);
    HttpResponse response;
    response = httpClient.execute(httpPost);
    return response.getStatusLine().toString();
}
 
Example 30
Source Project: product-es   Source File: EmailUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * This method is used to access the verification link provided by verification mail.
 * This method automates the browser redirection process in order to receive notifications
 *
 * @param   pointBrowserURL    redirection URL to management console.
 * @param   loginURL           login URL of the console.
 * @param   userName           user which is used to log in.
 * @param   password           password for the user.
 * @throws  Exception
 */
public static void browserRedirectionOnVerification(String pointBrowserURL, String loginURL, String userName,
        String password) throws Exception {

    initialize();
    pointBrowserURL = replaceIP(pointBrowserURL);
    HttpResponse verificationUrlResponse = sendGetRequest(String.format(pointBrowserURL));

    EntityUtils.consume(verificationUrlResponse.getEntity());

    urlParameters.clear();
    urlParameters.add(new BasicNameValuePair("username", userName));
    urlParameters.add(new BasicNameValuePair("password", password));

    HttpResponse loginResponse = sendPOSTMessage(loginURL + "admin/login.jsp", urlParameters);
    EntityUtils.consume(loginResponse.getEntity());

    HttpResponse reDirectionResponse = sendPOSTMessage(loginURL + "admin/login_action.jsp", urlParameters);
    String redirectionUrl = locationHeader(reDirectionResponse);
    EntityUtils.consume(reDirectionResponse.getEntity());

    HttpResponse newReDirectionResponse = sendGetRequest(String.format(redirectionUrl));
    EntityUtils.consume(newReDirectionResponse.getEntity());

    HttpResponse verificationConfirmationResponse = sendGetRequest(
            String.format(loginURL + "email-verification/validator_ajaxprocessor.jsp?confirmation=" +
                    pointBrowserURL.split("confirmation=")[1].split("&")[0]));
    EntityUtils.consume(verificationConfirmationResponse.getEntity());

    String newRedirectionUrl = locationHeader(reDirectionResponse);

    HttpResponse confirmationSuccessResponse = sendGetRequest(String.format(newRedirectionUrl));
    EntityUtils.consume(confirmationSuccessResponse.getEntity());

    log.info("Your email has been confirmed successfully");

}
 
Example 31
Source Project: gerrit-rest-java-client   Source File: GerritRestClient.java    License: Apache License 2.0 5 votes vote down vote up
private void checkStatusCodeError(HttpResponse response, int errorIfMin, int errorIfMax) throws HttpStatusException, IOException {
    StatusLine statusLine = response.getStatusLine();
    int code = statusLine.getStatusCode();
    if (code >= errorIfMin && code <= errorIfMax) {
        throwHttpStatusException(response);
    }
}
 
Example 32
@Test
@TestsNotMeantForZowe
public void shouldCallDiscoverableServiceApi() throws Exception {
    // When
    final HttpResponse response = HttpRequestUtils.getResponse("/api/v1/discoverableclient/greeting", SC_OK);
    final String jsonResponse = EntityUtils.toString(response.getEntity());
    DocumentContext jsonContext = JsonPath.parse(jsonResponse);
    String content = jsonContext.read("$.content");

    // Then
    assertThat(content, equalTo("Hello, world!"));
}
 
Example 33
Source Project: karyon   Source File: WebAdminTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testInvalidEndpoint() throws Exception {
    final String localhostUrlBase = String.format("http://localhost:%d/", adminServerPort);
    final HttpClient client = new DefaultHttpClient();
    HttpGet badGet = new HttpGet(localhostUrlBase + "/admin/not-there");
    final HttpResponse resp = client.execute(badGet);
    assertEquals(404, resp.getStatusLine().getStatusCode());
}
 
Example 34
@Test
public void retrieveDigest() throws Exception {
  HttpResponse response = proxyClient.getHttpResponse(PATH_DIGEST);
  assertThat(status(response), is(HttpStatus.OK));
  HttpEntity entity = response.getEntity();
  String digest = EntityUtils.toString(entity);
  JsonObject obj = new JsonParser().parse(digest).getAsJsonObject();
  assertThat(obj.get(FILE_MANIFEST).getAsString(), is(NXRM_CONAN_PROXY_REPO_PATH + PATH_MANIFEST));

  final Asset asset = findAsset(proxyRepo, PATH_DIGEST);
  assertThat(asset.format(), is(ConanFormat.NAME));
  assertThat(asset.name(), is(PATH_DIGEST));
  assertThat(asset.contentType(), is(ContentTypes.APPLICATION_JSON));
}
 
Example 35
public void handle(HttpRequest request, HttpResponse response, HttpContext context) throws HttpException,
		IOException
{
	try
	{
		String method = request.getRequestLine().getMethod().toUpperCase(Locale.ENGLISH);
		if (METHOD_GET.equals(method) || METHOD_HEAD.equals(method))
		{
			handleRequest(request, response, METHOD_HEAD.equals(method));
		}
		else if (METHOD_POST.equals(method))
		{
			handleRequest(request, response, METHOD_HEAD.equals(method));
		}
		else
		{
			throw new MethodNotSupportedException(MessageFormat.format(
					Messages.LocalWebServerHttpRequestHandler_UNSUPPORTED_METHOD, method));
		}
	}
	catch (Exception e)
	{
		IdeLog.logError(WebServerCorePlugin.getDefault(), e);
		response.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
		response.setEntity(createTextEntity(Messages.LocalWebServerHttpRequestHandler_INTERNAL_SERVER_ERROR));
	}
}
 
Example 36
Source Project: wisdom   Source File: FormTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testFormSubmissionAsFormURLEncoded() throws InterruptedException, IOException {
    Router router = prepareServer();

    // Prepare the router with a controller
    Controller controller = new DefaultController() {
        @SuppressWarnings("unused")
        public Result submit() {
            final Map<String, List<String>> form = context().form();
            // String
            if (!form.get("key").get(0).equals("value")) {
                return badRequest("key is not equals to value");
            }

            // Multiple values
            List<String> list = form.get("list");
            if (!(list.contains("1") && list.contains("2"))) {
                return badRequest("list does not contains 1 and 2");
            }

            return ok(context().header(HeaderNames.CONTENT_TYPE));
        }
    };
    Route route = new RouteBuilder().route(HttpMethod.POST)
            .on("/")
            .to(controller, "submit");
    when(router.getRouteFor(anyString(), anyString(), any(org.wisdom.api.http.Request.class))).thenReturn(route);

    server.start();
    waitForStart(server);

    int port = server.httpPort();

    final HttpResponse response = Request.Post("http://localhost:" + port + "/").bodyForm(
            Form.form().add("key", "value").add("list", "1").add("list", "2").build()
    ).execute().returnResponse();

    assertThat(response.getStatusLine().getStatusCode()).isEqualTo(200);
    assertThat(EntityUtils.toString(response.getEntity())).contains(MimeTypes.FORM);
}
 
Example 37
Source Project: tutorials   Source File: JerseyApiLiveTest.java    License: MIT License 5 votes vote down vote up
@Test
public void givenGetEmployee_whenEmployeeExists_thenResponseCodeSuccess() throws IOException {
    final HttpUriRequest request = new HttpGet(SERVICE_URL + "/1");

    final HttpResponse httpResponse = HttpClientBuilder.create().build().execute(request);

    assertEquals(httpResponse.getStatusLine().getStatusCode(), HttpStatus.SC_OK);
}
 
Example 38
Source Project: galaxy-fds-sdk-java   Source File: GalaxyFDSClient.java    License: Apache License 2.0 5 votes vote down vote up
@Override
@Deprecated
public QuotaPolicy getBucketQuota(String bucketName) throws GalaxyFDSClientException {
  Preconditions.checkNotNull(bucketName);

  URI uri = formatUri(fdsConfig.getBaseUri(), bucketName, SubResource.QUOTA);
  HttpUriRequest httpRequest = fdsHttpClient.prepareRequestMethod(uri, HttpMethod.GET, null, null,
    null, null, null);

  HttpResponse response = fdsHttpClient.executeHttpRequest(httpRequest, Action.GetBucketQuota);

  QuotaPolicy quotaPolicy = (QuotaPolicy) fdsHttpClient.processResponse(response,
    QuotaPolicy.class, "get bucket [" + bucketName + "] quota");
  return quotaPolicy;
}
 
Example 39
Source Project: kylin   Source File: LivyRestClient.java    License: Apache License 2.0 5 votes vote down vote up
public String livyGetJobStatusBatches(String jobId) throws IOException {
    String url = baseUrl + "/batches/" + jobId;
    HttpGet get = new HttpGet(url);

    HttpResponse response = client.execute(get);
    String content = getContent(response);
    if (response.getStatusLine().getStatusCode() != 200) {
        throw new IOException("Invalid response " + response.getStatusLine().getStatusCode() + " with url " + url + "\n");
    }
    return content;
}
 
Example 40
Source Project: riptide   Source File: ApacheClientHttpResponse.java    License: MIT License 5 votes vote down vote up
ApacheClientHttpResponse(final HttpResponse response) throws IOException {
    this.response = response;
    this.body = getBody(response);

    for (final Header header : response.getAllHeaders()) {
        this.headers.add(header.getName(), header.getValue());
    }
}