@Override
  @Test
  public void multipleMaxConnectionOpenTest() throws Throwable {
    AsyncHttpClientConfig cg =
        new AsyncHttpClientConfig.Builder()
            .setAllowPoolingConnection(true)
            .setConnectionTimeoutInMs(5000)
            .setMaximumConnectionsTotal(1)
            .build();
    AsyncHttpClient c = getAsyncHttpClient(cg);

    String body = "hello there";

    // once
    Response response =
        c.preparePost(getTargetUrl()).setBody(body).execute().get(TIMEOUT, TimeUnit.SECONDS);

    assertEquals(response.getResponseBody(), body);

    // twice
    Exception exception = null;
    try {
      c.preparePost(String.format("http://127.0.0.1:%d/foo/test", port2))
          .setBody(body)
          .execute()
          .get(TIMEOUT, TimeUnit.SECONDS);
      fail("Should throw exception. Too many connections issued.");
    } catch (Exception ex) {
      ex.printStackTrace();
      exception = ex;
    }
    assertNotNull(exception);
    c.close();
  }
Ejemplo n.º 2
0
  @Test()
  public void uploadImage() {

    Response result = null;

    File file = new File("psyduck.jpg");

    MimetypesFileTypeMap fileTypeMap = new MimetypesFileTypeMap();

    AsyncHttpClient client = new AsyncHttpClient(new AsyncHttpClientConfig.Builder().build());
    AsyncHttpClient.BoundRequestBuilder builder = client.preparePost("http://localhost:8080/");

    builder.setHeader("Content-Type", "multipart/form-data");

    builder.addBodyPart(new FilePart("image", file, fileTypeMap.getContentType(file), "UTF-8"));

    try {

      result = builder.execute().get();

      System.out.println(result.getResponseBody());

    } catch (Exception e) {

      e.printStackTrace();
    }
  }
 public static boolean register(String username, String basicAuthenticationHeader) {
   try {
     BoundRequestBuilder reqBregister =
         asynSenderclient
             .preparePost(
                 HttpResources.getBaseHost() + HttpResources.getRegisterResource(username))
             .addHeader("Authorization", basicAuthenticationHeader);
     String registerNotification;
     // -- Sync response management, no other thing can be done before this step is completed
     Response response = reqBregister.execute().get();
     if (!HttpErrorCodeEvaluator.isCorrectRegistrationOperation(response.getStatusCode())) {
       log.error("FAIL - Could not register " + response.getStatusCode());
       return false;
     } else {
       registerNotification = requestRegisterNotification(username, basicAuthenticationHeader);
       if (registerNotification != null) {
         if (SimpleNotificationParser.extractRegistrationResult(registerNotification)) {
           log.info("OK - Registration requested successfully: " + response.getStatusCode());
           return true;
         }
       }
     }
   } catch (Exception e) {
     log.error("FAIL - REGISTER ERROR: username="******", cause: " + e.getCause());
   }
   return false;
 }
Ejemplo n.º 4
0
  @Test
  public void testHttpServer() throws IOException, ExecutionException, InterruptedException {
    final CountDownLatch lock = new CountDownLatch(CONCURRENT_REQUESTS);

    for (int i = 0; i < CONCURRENT_REQUESTS; i++) {
      TrackingDataTO trackingDataTO = bootstrapTrackingData();
      String requestAsJson = gson.toJson(trackingDataTO);

      AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
      asyncHttpClient
          .preparePost("http://localhost:8080/" + trackingDataTO.getType().getLabel())
          .setBody(requestAsJson)
          .execute(
              new AsyncCompletionHandler<Response>() {

                @Override
                public Response onCompleted(Response response) throws Exception {
                  ResultTO resultTo = gson.fromJson(response.getResponseBody(), ResultTO.class);
                  if (resultTo.getCode().equals(ResultCode.SUCCESS)) {
                    lock.countDown();
                  }
                  return response;
                }

                @Override
                public void onThrowable(Throwable t) {
                  log.error(t.toString());
                }
              });
    }

    lock.await(TIMEOUT, TimeUnit.MILLISECONDS);
    assertEquals(0, lock.getCount());
  }
  private static String requestRegisterNotification(
      String username, String basicAuthenticationHeader) {

    BoundRequestBuilder reqBregister =
        asynSenderclient
            .preparePost(
                HttpResources.getNotifierBaseHost()
                    + HttpResources.getNotificationResource(username))
            .addHeader("Authorization", basicAuthenticationHeader);
    // -- Sync response management, no other thing can be done before this step is completed
    try {

      Response response = reqBregister.execute().get();
      if (response.getStatusCode() != 200) {
        log.error(
            "FAIL - Bad response to the notification request: "
                + response.getStatusCode()
                + " checking if it already came...");
      } else {
        return response.getResponseBody();
      }

    } catch (Exception e) {
      log.error("FAIL - Could not request the registration notification...");
      e.printStackTrace();
    }
    return null;
  }
  private BoundRequestBuilder getBuilderWithHeaderAndQuery(
      final String verb,
      final String url,
      @Nullable final String username,
      @Nullable final String password,
      final Multimap<String, String> options) {
    BoundRequestBuilder builder;

    if (verb.equals("GET")) {
      builder = httpClient.prepareGet(url);
    } else if (verb.equals("POST")) {
      builder = httpClient.preparePost(url);
    } else if (verb.equals("PUT")) {
      builder = httpClient.preparePut(url);
    } else if (verb.equals("DELETE")) {
      builder = httpClient.prepareDelete(url);
    } else if (verb.equals("HEAD")) {
      builder = httpClient.prepareHead(url);
    } else if (verb.equals("OPTIONS")) {
      builder = httpClient.prepareOptions(url);
    } else {
      throw new IllegalArgumentException("Unrecognized verb: " + verb);
    }

    if (username != null && password != null) {
      final Realm realm = new RealmBuilder().setPrincipal(username).setPassword(password).build();
      builder.setRealm(realm);
    }

    final Collection<String> acceptHeaders = options.removeAll(HTTP_HEADER_ACCEPT);
    final String acceptHeader;
    if (!acceptHeaders.isEmpty()) {
      acceptHeader = CSV_JOINER.join(acceptHeaders);
    } else {
      acceptHeader = ACCEPT_JSON;
    }
    builder.addHeader(HTTP_HEADER_ACCEPT, acceptHeader);

    String contentTypeHeader = getUniqueValue(options, HTTP_HEADER_CONTENT_TYPE);
    if (contentTypeHeader == null) {
      contentTypeHeader = CONTENT_TYPE_JSON;
    } else {
      options.removeAll(HTTP_HEADER_CONTENT_TYPE);
    }
    builder.addHeader(HTTP_HEADER_CONTENT_TYPE, contentTypeHeader);

    builder.setBodyEncoding("UTF-8");

    for (final String key : options.keySet()) {
      if (options.get(key) != null) {
        for (final String value : options.get(key)) {
          builder.addQueryParam(key, value);
        }
      }
    }

    return builder;
  }
    public Request apply(HttpRequest request) {

      for (HttpRequestFilter filter : request.getFilters()) {
        filter.filter(request);
      }

      AsyncHttpClient client = new AsyncHttpClient();
      AsyncHttpClient.BoundRequestBuilder nativeRequestBuilder;
      String endpoint = request.getEndpoint().toASCIIString();
      if (request.getMethod().equals(HttpMethod.HEAD)) {
        nativeRequestBuilder = client.prepareHead(endpoint);
      } else if (request.getMethod().equals(HttpMethod.GET)) {
        nativeRequestBuilder = client.prepareGet(endpoint);
      } else if (request.getMethod().equals(HttpMethod.DELETE)) {
        nativeRequestBuilder = client.prepareDelete(endpoint);
      } else if (request.getMethod().equals(HttpMethod.PUT)) {
        nativeRequestBuilder = client.preparePut(endpoint);
      } else if (request.getMethod().equals(HttpMethod.POST)) {
        nativeRequestBuilder = client.preparePost(endpoint);
      } else {
        throw new UnsupportedOperationException(request.getMethod());
      }
      Payload payload = request.getPayload();
      if (payload != null) {
        boolean chunked = "chunked".equals(request.getFirstHeaderOrNull("Transfer-Encoding"));

        if (request.getPayload().getContentMD5() != null)
          nativeRequestBuilder.addHeader(
              "Content-MD5", CryptoStreams.base64(request.getPayload().getContentMD5()));
        if (request.getPayload().getContentType() != null)
          nativeRequestBuilder.addHeader(
              HttpHeaders.CONTENT_TYPE, request.getPayload().getContentType());
        if (!chunked) {
          Long length =
              checkNotNull(request.getPayload().getContentLength(), "payload.getContentLength");
          nativeRequestBuilder.addHeader(HttpHeaders.CONTENT_LENGTH, length.toString());
        }
        setPayload(nativeRequestBuilder, payload);
      } else {
        nativeRequestBuilder.addHeader(HttpHeaders.CONTENT_LENGTH, "0");
      }

      nativeRequestBuilder.addHeader(HttpHeaders.USER_AGENT, USER_AGENT);
      for (String header : request.getHeaders().keySet()) {
        for (String value : request.getHeaders().get(header)) {
          nativeRequestBuilder.addHeader(header, value);
        }
      }

      return nativeRequestBuilder.build();
    }
  public static void sendIMAutomaticSession(
      String username, String basicAuthenticationHeader, String destUri, String message) {

    try {

      BoundRequestBuilder reqBsender =
          asynSenderclient
              .preparePost(
                  HttpResources.getBaseHost() + HttpResources.getChatResource(username, destUri))
              .addHeader("Authorization", basicAuthenticationHeader)
              .addHeader("Content-Type", "application/json; charset=utf-8");

      ChatMessage cm = new ChatMessage();
      cm.setText(message);
      log.info("OK - Send message request:\n" + cm.toString());
      reqBsender.setBody(cm.toString().getBytes("utf-8")).setBodyEncoding("utf-8");

      // -- Async response management, once the message is sent you can keep working, no need to
      // wait for the response from the API
      reqBsender.execute(
          new AsyncCompletionHandler<Response>() {
            @Override
            public Response onCompleted(Response response) throws Exception {
              if (!HttpErrorCodeEvaluator.isChatMessageSent(response.getStatusCode())) {
                log.error("FAIL -	Could not send message: " + response.getStatusCode());
              } else {
                log.info("OK -	Message sent: " + response.getStatusCode());
              }
              return null;
            }

            @Override
            public void onThrowable(Throwable t) {
              log.error("FAIL - ERROR: run - onThrowable: " + t.getCause());
            }
          });

    } catch (Exception e) {
      log.error(
          "FAIL - SENDIMMESSAGE ERROR: username="******", destination uri="
              + destUri
              + ", message="
              + message
              + ", cause: "
              + e.getCause());
    }
  }
  private <T> T doPOST(final String resource, final RecurlyObject payload, final Class<T> clazz) {
    final String xmlPayload;
    try {
      xmlPayload = xmlMapper.writeValueAsString(payload);
      if (debug()) {
        log.info("Msg to Recurly API [POST]:: URL : {}", baseUrl + resource);
        log.info("Payload for [POST]:: {}", xmlPayload);
      }
    } catch (IOException e) {
      log.warn("Unable to serialize {} object as XML: {}", clazz.getName(), payload.toString());
      return null;
    }

    return callRecurlySafe(client.preparePost(baseUrl + resource).setBody(xmlPayload), clazz);
  }
Ejemplo n.º 10
0
  public String readTokenFromLogin(
      final String vaultBaseUrl, final String appId, final String userId) {
    try {
      final Response response =
          asyncHttpClient
              .preparePost(vaultBaseUrl + "/v1/auth/app-id/login")
              .setBody(createAuthBody(appId, userId))
              .execute()
              .get();

      if ((response.getStatusCode() != 200)) {
        throw new RuntimeException(
            "login to vault failed, return code is " + response.getStatusCode());
      }
      LOG.info("login to vault successful");

      return extractToken(response.getResponseBody());
    } catch (ExecutionException | InterruptedException | IOException e) {
      LOG.error("could not retrieve token from vault", e);
      throw new RuntimeException(e);
    }
  }
  public Future<Response> save() throws IOException {
    if (id != null) {
      return asyncHttpClient
          .preparePut(getCapsuleUrl() + "/api" + writeContextPath() + "/" + id)
          .addHeader("Content-Type", "application/xml")
          .setRealm(getRealm())
          .setBodyEncoding("UTF-8")
          .setBody(xstream.toXML(this))
          .execute(new ThrowOnHttpFailure());
    } else {
      return asyncHttpClient
          .preparePost(getCapsuleUrl() + "/api" + writeContextPath())
          .addHeader("Content-Type", "application/xml")
          .addQueryParams(extraQueryParams())
          .setRealm(getRealm())
          .setBodyEncoding("UTF-8")
          .setBody(xstream.toXML(this))
          .execute(
              new ThrowOnHttpFailure() {
                @Override
                public Response onCompleted(Response response) throws Exception {
                  response = super.onCompleted(response);

                  String location = response.getHeader("Location");
                  if (location == null) {
                    throw new RuntimeException(
                        "null location, cannot assign id to "
                            + this
                            + ", status is "
                            + response.getStatusCode()
                            + " "
                            + response.getStatusText());
                  }
                  id = Long.parseLong(location.substring(location.lastIndexOf("/") + 1));
                  return response;
                }
              });
    }
  }
Ejemplo n.º 12
0
  private void restCall(Tuple tuple) throws ExecutionException, InterruptedException {
    Future<Response> fureRet = null;
    for (RestInfo restInfo : restInfos) {
      String url = restInfo.getUrl();
      String body = restInfo.getBody();
      for (BaseBindColumnDef bindColumn : restInfo.getColumns()) {
        url =
            url.replace(
                "[:" + bindColumn.getName() + "]", tuple.getStringByField(bindColumn.getName()));
        if (body != null) {
          body =
              body.replace(
                  "[:" + bindColumn.getName() + "]", tuple.getStringByField(bindColumn.getName()));
        }
      }

      AsyncHttpClient.BoundRequestBuilder boundRequestBuilder = null;
      if (RestCmd.PUT.equals(restInfo.getCmd())) {
        boundRequestBuilder = asyncHttpClient.preparePut(url);
      } else if (RestCmd.GET.equals(restInfo.getCmd())) {
        boundRequestBuilder = asyncHttpClient.prepareGet(url);
      } else if (RestCmd.DELETE.equals(restInfo.getCmd())) {
        boundRequestBuilder = asyncHttpClient.prepareDelete(url);
      } else if (RestCmd.POST.equals(restInfo.getCmd())) {
        boundRequestBuilder = asyncHttpClient.preparePost(url);
      } else {
        break;
      }

      if (body != null) {
        fureRet = boundRequestBuilder.setBody(body).execute();
      } else {
        fureRet = boundRequestBuilder.execute();
      }

      fureRet.get();
    }
  }
  public static boolean createChannelAndSubscriptions(
      String username, String basicAuthenticationHeader) {

    try {

      // Channel creation
      BoundRequestBuilder reqSubscribe =
          asynSenderclient
              .preparePost(
                  HttpResources.getBaseHost()
                      + HttpResources.getNotificationChannelResource(username))
              .addHeader("Authorization", basicAuthenticationHeader);

      NotificationChannelSubscription ncs =
          new NotificationChannelSubscription("12345", "myService", 50, "LongPolling", 3600);

      reqSubscribe.setBody(ncs.getText());

      // -- Sync response management, no other thing can be done before this step is completed
      Response response = reqSubscribe.execute().get();
      notificationChannelURL = getChannelURL(response.getResponseBody());
      if ((!HttpErrorCodeEvaluator.isChannelCorrectlyCreated(response.getStatusCode()))
          || (notificationChannelURL == null)) {
        log.error("FAIL - Channel not created " + response.getStatusCode());
        return false;
      } else {
        log.info("OK - Channel correctly created, HTTP " + response.getStatusCode());
      }

      NotificationSubscription ns =
          new NotificationSubscription(
              "sessionSubscription", "sessionSubscription", notificationChannelURL, 3600);

      // Subscription creation
      // -- Sync response management, no other thing can be done before this step is completed

      // Session subscription
      reqSubscribe =
          asynSenderclient
              .preparePost(
                  HttpResources.getBaseHost()
                      + HttpResources.getSubscriptionsResource(username, "register"))
              .addHeader("Authorization", basicAuthenticationHeader);
      reqSubscribe.setBody(ns.getText());
      response = reqSubscribe.execute().get();
      if (!HttpErrorCodeEvaluator.isSessionSubscribeCorrect(response.getStatusCode())) {
        log.error(
            "FAIL - Session notification subscription could not be created: "
                + response.getStatusCode());
        return false;
      } else {
        log.info("OK - Session notification subscription created: " + response.getStatusCode());
      }

      // Chat subscription
      ns =
          new NotificationSubscription(
              "chatNotificationSubscription", "chatSubscription1", notificationChannelURL, 3600);
      reqSubscribe =
          asynSenderclient
              .preparePost(
                  HttpResources.getBaseHost()
                      + HttpResources.getSubscriptionsResource(username, "chat"))
              .addHeader("Authorization", basicAuthenticationHeader);
      reqSubscribe.setBody(ns.getText());
      response = reqSubscribe.execute().get();
      if (!HttpErrorCodeEvaluator.isChatSubscribeCorrect(response.getStatusCode())) {
        log.error(
            "FAIL - Chat notification subscription could not be created: "
                + response.getStatusCode());
        return false;
      } else {
        log.info("OK - Chat notification subscription created: " + response.getStatusCode());
      }

    } catch (Exception e) {
      log.error(
          "FAIL - NOTIFICATION CHANNEL ERROR: username="******", cause: " + e.getCause());
      return false;
    }
    return true;
  }