Esempio n. 1
1
  public static String doPost(
      String url, Map<String, String> headers, Map<String, String> params, boolean isHttps) {

    HttpClient client = isHttps ? createSSLClientDefault() : HttpClients.createDefault();
    HttpPost post = new HttpPost(url);
    if (headers == null) {
      post.setHeader("Content-Type", "text/html;charset=utf-8");
    } else {
      for (String key : headers.keySet()) {
        post.setHeader(key, headers.get(key));
      }
    }
    List<NameValuePair> nvps = new ArrayList<NameValuePair>();

    Set<String> keySet = params.keySet();
    for (String key : keySet) {
      nvps.add(new BasicNameValuePair(key, params.get(key)));
    }
    try {
      // UrlEncodedFormEntity entity = new UrlEncodedFormEntity(nvps, "UTF-8");
      HttpEntity entity = EntityBuilder.create().setParameters(nvps).build();
      System.out.println(nvps.get(1).getValue());
      System.out.println(StringUtils.streamToStringReader(entity.getContent()));
      post.setEntity(entity);
      HttpResponse response = client.execute(post);
      return httpClientResponse(response);
    } catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    return null;
  }
  @Test
  public void testEstablishRouteViaProxyTunnelRetryOnAuthChallengeNonPersistentConnection()
      throws Exception {
    final AuthState authState = new AuthState();
    final HttpRoute route = new HttpRoute(target, null, proxy, true);
    final HttpClientContext context = new HttpClientContext();
    final HttpRequestWrapper request = HttpRequestWrapper.wrap(new HttpGet("http://bar/test"));
    final HttpResponse response1 = new BasicHttpResponse(HttpVersion.HTTP_1_1, 401, "Huh?");
    final InputStream instream1 = Mockito.spy(new ByteArrayInputStream(new byte[] {1, 2, 3}));
    response1.setEntity(EntityBuilder.create().setStream(instream1).build());
    final HttpResponse response2 = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK");

    Mockito.when(managedConn.isOpen()).thenReturn(Boolean.TRUE);
    Mockito.when(
            proxyAuthStrategy.isAuthenticationRequested(
                Mockito.eq(proxy), Mockito.same(response1), Mockito.<HttpClientContext>any()))
        .thenReturn(Boolean.TRUE);
    Mockito.when(
            reuseStrategy.keepAlive(Mockito.<HttpResponse>any(), Mockito.<HttpClientContext>any()))
        .thenReturn(Boolean.FALSE);
    Mockito.when(
            requestExecutor.execute(
                Mockito.<HttpRequest>any(),
                Mockito.<HttpClientConnection>any(),
                Mockito.<HttpClientContext>any()))
        .thenReturn(response1, response2);

    mainClientExec.establishRoute(authState, managedConn, route, request, context);

    Mockito.verify(connManager).connect(managedConn, route, 0, context);
    Mockito.verify(connManager).routeComplete(managedConn, route, context);
    Mockito.verify(instream1, Mockito.never()).close();
    Mockito.verify(managedConn).close();
  }
  @Test
  public void testExecEntityEnclosingRequestRetryOnAuthChallenge() throws Exception {
    final HttpRoute route = new HttpRoute(target);
    final HttpRequestWrapper request = HttpRequestWrapper.wrap(new HttpGet("http://bar/test"));
    final HttpResponse response1 = new BasicHttpResponse(HttpVersion.HTTP_1_1, 401, "Huh?");
    final InputStream instream1 = Mockito.spy(new ByteArrayInputStream(new byte[] {1, 2, 3}));
    response1.setEntity(EntityBuilder.create().setStream(instream1).build());
    final HttpResponse response2 = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK");
    final InputStream instream2 = Mockito.spy(new ByteArrayInputStream(new byte[] {2, 3, 4}));
    response2.setEntity(EntityBuilder.create().setStream(instream2).build());

    final AuthState proxyAuthState = new AuthState();
    proxyAuthState.setState(AuthProtocolState.SUCCESS);
    proxyAuthState.update(new NTLMScheme(), new NTCredentials("user:pass"));

    final HttpClientContext context = new HttpClientContext();
    context.setAttribute(HttpClientContext.PROXY_AUTH_STATE, proxyAuthState);

    Mockito.when(managedConn.isOpen()).thenReturn(Boolean.TRUE);
    Mockito.when(managedConn.isStale()).thenReturn(Boolean.FALSE);
    Mockito.when(
            requestExecutor.execute(
                Mockito.same(request),
                Mockito.<HttpClientConnection>any(),
                Mockito.<HttpClientContext>any()))
        .thenReturn(response1, response2);
    Mockito.when(
            reuseStrategy.keepAlive(Mockito.<HttpResponse>any(), Mockito.<HttpClientContext>any()))
        .thenReturn(Boolean.FALSE);
    Mockito.when(
            targetAuthStrategy.isAuthenticationRequested(
                Mockito.eq(target), Mockito.same(response1), Mockito.<HttpClientContext>any()))
        .thenReturn(Boolean.TRUE);

    final CloseableHttpResponse finalResponse =
        mainClientExec.execute(route, request, context, execAware);
    Mockito.verify(requestExecutor, Mockito.times(2)).execute(request, managedConn, context);
    Mockito.verify(managedConn).close();
    Mockito.verify(instream2, Mockito.never()).close();

    Assert.assertNotNull(finalResponse);
    Assert.assertEquals(200, finalResponse.getStatusLine().getStatusCode());
    Assert.assertNull(proxyAuthState.getAuthScheme());
    Assert.assertNull(proxyAuthState.getCredentials());
  }
  @Test(expected = NonRepeatableRequestException.class)
  public void testExecEntityEnclosingRequest() throws Exception {
    final HttpRoute route = new HttpRoute(target);
    final HttpClientContext context = new HttpClientContext();
    final HttpPost post = new HttpPost("http://bar/test");
    final InputStream instream0 = new ByteArrayInputStream(new byte[] {1, 2, 3});
    post.setEntity(EntityBuilder.create().setStream(instream0).build());
    final HttpRequestWrapper request = HttpRequestWrapper.wrap(post);

    final HttpResponse response1 = new BasicHttpResponse(HttpVersion.HTTP_1_1, 401, "Huh?");
    final InputStream instream1 = new ByteArrayInputStream(new byte[] {1, 2, 3});
    response1.setEntity(EntityBuilder.create().setStream(instream1).build());

    Mockito.when(managedConn.isOpen()).thenReturn(Boolean.TRUE);
    Mockito.when(managedConn.isStale()).thenReturn(Boolean.FALSE);
    Mockito.when(
            requestExecutor.execute(
                Mockito.same(request),
                Mockito.<HttpClientConnection>any(),
                Mockito.<HttpClientContext>any()))
        .thenAnswer(
            new Answer<HttpResponse>() {

              @Override
              public HttpResponse answer(final InvocationOnMock invocationOnMock) throws Throwable {
                final Object[] args = invocationOnMock.getArguments();
                final HttpEntityEnclosingRequest requestEE = (HttpEntityEnclosingRequest) args[0];
                requestEE.getEntity().writeTo(new ByteArrayOutputStream());
                return response1;
              }
            });
    Mockito.when(
            reuseStrategy.keepAlive(Mockito.<HttpResponse>any(), Mockito.<HttpClientContext>any()))
        .thenReturn(Boolean.TRUE);
    Mockito.when(
            targetAuthStrategy.isAuthenticationRequested(
                Mockito.eq(target), Mockito.same(response1), Mockito.<HttpClientContext>any()))
        .thenReturn(Boolean.TRUE);

    mainClientExec.execute(route, request, context, execAware);
  }
  //	@Test
  public void testCreateSuspect() throws IOException {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    StringBuilder url = new StringBuilder(BASE_URL);
    url.append("suspect/");
    HttpPost httpPost = new HttpPost(url.toString());

    EntityBuilder entityBuilder = EntityBuilder.create();
    entityBuilder.setContentType(ContentType.APPLICATION_JSON);

    Suspect aaron = createMockSuspect("982c4a67-bb39-41f9-9872-88356822b7ad", "Aaron");
    JsonHelper jsonHelper = new JsonHelper();
    String jsonRequest = jsonHelper.convertToJson(aaron);

    entityBuilder.setText(jsonRequest);
    httpPost.setEntity(entityBuilder.build());
    CloseableHttpResponse response = httpclient.execute(httpPost);
    Assert.assertTrue(true);
  }
  @Test
  public void testExecRequestConnectionRelease() throws Exception {
    final HttpRoute route = new HttpRoute(target);
    final HttpClientContext context = new HttpClientContext();
    final HttpRequestWrapper request = HttpRequestWrapper.wrap(new HttpGet("http://bar/test"));
    final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK");
    // The entity is streaming
    response.setEntity(
        EntityBuilder.create().setStream(new ByteArrayInputStream(new byte[] {})).build());

    Mockito.when(managedConn.isOpen()).thenReturn(Boolean.TRUE);
    Mockito.when(managedConn.isStale()).thenReturn(Boolean.FALSE);
    Mockito.when(
            requestExecutor.execute(
                Mockito.same(request),
                Mockito.<HttpClientConnection>any(),
                Mockito.<HttpClientContext>any()))
        .thenReturn(response);
    Mockito.when(reuseStrategy.keepAlive(Mockito.same(response), Mockito.<HttpClientContext>any()))
        .thenReturn(Boolean.FALSE);

    final CloseableHttpResponse finalResponse =
        mainClientExec.execute(route, request, context, execAware);
    Mockito.verify(connManager).requestConnection(route, null);
    Mockito.verify(connRequest).get(0, TimeUnit.MILLISECONDS);
    Mockito.verify(requestExecutor, Mockito.times(1)).execute(request, managedConn, context);
    Mockito.verify(connManager, Mockito.never())
        .releaseConnection(
            Mockito.same(managedConn), Mockito.any(), Mockito.anyInt(), Mockito.<TimeUnit>any());
    Mockito.verify(managedConn, Mockito.never()).close();

    Assert.assertNotNull(finalResponse);
    Assert.assertTrue(finalResponse instanceof HttpResponseProxy);
    finalResponse.close();

    Mockito.verify(connManager, Mockito.times(1))
        .releaseConnection(managedConn, null, 0, TimeUnit.MILLISECONDS);
    Mockito.verify(managedConn, Mockito.times(1)).shutdown();
  }
  @SuppressWarnings("nls")
  private void processRESTRequest(
      GetFieldDataRequest request,
      List<Header> headers,
      GetFieldDataResult fullResult,
      FieldDataCriteria fieldDataCriteria,
      FieldSelection fieldSelection) {
    GetFieldDataResult singleResult = null;
    GetFieldDataRequest singleRequest =
        makeSingleRequest(request, fieldDataCriteria, fieldSelection);

    String url = fieldSelection.getFieldIdentifier().getSource();
    String method = fieldSelection.getFieldIdentifier().getName();
    if (url == null || !url.startsWith("http://") || !url.startsWith("https://"))
      throw new UnsupportedOperationException(
          "please set the source to the url of REST service e.g. https://myservice.com");
    if ("POST".equals(method.toUpperCase())) {
      EntityBuilder builder = EntityBuilder.create();
      builder.setText(this.mapper.toJson(singleRequest));
      HttpEntity reqEntity = builder.build();
      try (CloseableHttpResponse response =
          this.restClient.post(url, reqEntity, null, 100, 1000); ) {
        String res = this.restClient.getResponse(response);
        singleResult = this.mapper.fromJson(res, GetFieldDataResult.class);
      } catch (IOException e) {
        throw new RuntimeException("Error when performing POST to Custom Rest Service : ", e);
      }
    } else if ("GET".equals(method.toUpperCase())) {
      try (CloseableHttpResponse response = this.restClient.get(url, null, 100, 1000); ) {
        String res = this.restClient.getResponse(response);
        singleResult = this.mapper.fromJson(res, GetFieldDataResult.class);
      } catch (IOException e) {
        throw new RuntimeException("Error when performing GET to Custom Rest Service : ", e);
      }
    }
    fullResult.getFieldData().addAll(singleResult.getFieldData());
  }