org.asynchttpclient.AsyncCompletionHandler Java Examples

The following examples show how to use org.asynchttpclient.AsyncCompletionHandler. 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 check out the related API usage on the sidebar.
Example #1
Source File: RecurlyClient.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
protected <T extends BaseRecurlyModel> ListenableFuture<T> doPOST(String resourcePath, final Class<T> clazz, RecurlyObjectSerializer serializer, @Nullable String apiVersion) {
    final SettableFuture<T> future = SettableFuture.create();

    try {
        post(baseURL + resourcePath, apiVersion)
                .setBody(serializer.serialize())
                .execute(new AsyncCompletionHandler<Void>() {
                    @Override
                    public Void onCompleted(Response response) throws Exception {
                        setResponse(response, future, clazz);
                        return null;
                    }
                });
    } catch (Exception ex) {
        future.setException(ex);
    }

    return future;
}
 
Example #2
Source File: AsyncTrelloHttpClient2.java    From trello-java-wrapper with Apache License 2.0 6 votes vote down vote up
@Override
public <T> T delete(String url, final Class<T> responseType, String... params) {
    try {
        Future<T> f = asyncHttpClient.prepareDelete(expandUrl(url, params)).execute(
                new AsyncCompletionHandler<T>() {

                    @Override
                    public T onCompleted(Response response) throws Exception {
                        return reader.forType(responseType).readValue(response.getResponseBody());
                    }

                    @Override
                    public void onThrowable(Throwable t) {
                        throw new TrelloHttpException(t);
                    }
                });
        return f.get();
    } catch (InterruptedException | ExecutionException e) {
        throw new TrelloHttpException(e);
    }
}
 
Example #3
Source File: AsyncTrelloHttpClient2.java    From trello-java-wrapper with Apache License 2.0 6 votes vote down vote up
@Override
public <T> T putForObject(String url, Object object, final Class<T> responseType, String... params) {
    try {
        byte[] body = this.writer.writeValueAsBytes(object);
        Future<T> f = asyncHttpClient.preparePut(expandUrl(url, params)).setBody(body).execute(
                new AsyncCompletionHandler<T>() {

                    @Override
                    public T onCompleted(Response response) throws Exception {
                        return reader.forType(responseType).readValue(response.getResponseBody());
                    }

                    @Override
                    public void onThrowable(Throwable t) {
                        throw new TrelloHttpException(t);
                    }
                });
        return f.get();
    } catch (IOException | InterruptedException | ExecutionException e) {
        throw new TrelloHttpException(e);
    }
}
 
Example #4
Source File: AsyncTrelloHttpClient2.java    From trello-java-wrapper with Apache License 2.0 6 votes vote down vote up
@Override
public <T> T postForObject(String url, Object object, final Class<T> responseType, String... params) {
    try {
        byte[] body = this.writer.writeValueAsBytes(object);
        Future<T> f = asyncHttpClient.preparePost(expandUrl(url, params)).setBody(body)
                .setHeader("Content-Type", "application/json").execute(
                        new AsyncCompletionHandler<T>() {

                            @Override
                            public T onCompleted(Response response) throws Exception {
                                return reader.forType(responseType).readValue(response.getResponseBody());
                            }

                            @Override
                            public void onThrowable(Throwable t) {
                                throw new TrelloHttpException(t);
                            }
                        });
        return f.get();
    } catch (IOException | InterruptedException | ExecutionException e) {
        throw new TrelloHttpException(e);
    }
}
 
Example #5
Source File: AsyncTrelloHttpClient2.java    From trello-java-wrapper with Apache License 2.0 6 votes vote down vote up
@Override
public <T> T get(String url, final Class<T> responseType, String... params) {
    try {
        Future<T> f = asyncHttpClient.prepareGet(expandUrl(url, params)).execute(
                new AsyncCompletionHandler<T>() {

                    @Override
                    public T onCompleted(Response response) throws Exception {
                        return reader.forType(responseType).readValue(response.getResponseBody());
                    }

                    @Override
                    public void onThrowable(Throwable t) {
                        throw new TrelloHttpException(t);
                    }
                });
        return f.get();
    } catch (InterruptedException | ExecutionException e) {
        throw new TrelloHttpException(e);
    }
}
 
Example #6
Source File: TwitLogic.java    From blynk-server with GNU General Public License v3.0 6 votes vote down vote up
private void twit(Channel channel, String email, String token, String secret, String body, int msgId) {
    twitterWrapper.send(token, secret, body,
            new AsyncCompletionHandler<>() {
                @Override
                public Response onCompleted(Response response) {
                    if (response.getStatusCode() == HttpResponseStatus.OK.code()) {
                        channel.writeAndFlush(ok(msgId), channel.voidPromise());
                    }
                    return response;
                }

                @Override
                public void onThrowable(Throwable t) {
                    logError(t.getMessage(), email);
                    channel.writeAndFlush(notificationError(msgId), channel.voidPromise());
                }
            }
    );
}
 
Example #7
Source File: SMSWrapper.java    From blynk-server with GNU General Public License v3.0 6 votes vote down vote up
public void send(String to, String text) {
    ArrayList<Param> params = new ArrayList<>();
    params.add(new Param("api_key", key));
    params.add(new Param("api_secret", secret));
    params.add(new Param("from", "Blynk"));
    params.add(new Param("to", to));
    params.add(new Param("text", text));

    httpclient.preparePost("https://rest.nexmo.com/sms/json")
            .setQueryParams(params)
            .execute(new AsyncCompletionHandler<Response>() {
                @Override
                public Response onCompleted(org.asynchttpclient.Response response) throws Exception {
                    if (response.getStatusCode() == 200) {
                        SmsResponse smsResponse = smsResponseReader.readValue(response.getResponseBody());
                        if (!smsResponse.messages[0].status.equals("0")) {
                            log.error(smsResponse.messages[0].error);
                        }
                    }
                    return response;
                }
            });


}
 
Example #8
Source File: RecurlyClient.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
protected <T extends BaseRecurlyModel> ListenableFuture<T> doGET(String resourcePath, final Class<T> clazz, @Nullable String apiVersion) {
    final SettableFuture<T> future = SettableFuture.create();

    try {
        get(baseURL + resourcePath, apiVersion)
                .execute(new AsyncCompletionHandler<Void>() {
                    @Override
                    public Void onCompleted(Response response) throws Exception {
                        setResponse(response, future, clazz);
                        return null;
                    }
                });
    } catch (Exception ex) {
        future.setException(ex);
    }

    return future;
}
 
Example #9
Source File: AsyncHttpClientITest.java    From java-specialagent with Apache License 2.0 6 votes vote down vote up
public static void main(final String[] args) throws Exception {
  try (final AsyncHttpClient client = new DefaultAsyncHttpClient()) {
    final Request request = new RequestBuilder(HttpConstants.Methods.GET).setUrl("http://www.google.com").build();
    final int statusCode = client.executeRequest(request, new AsyncCompletionHandler<Response>() {
      @Override
      public Response onCompleted(final Response response) {
        TestUtil.checkActiveSpan();
        return response;
      }
    }).get(10, TimeUnit.SECONDS).getStatusCode();

    if (200 != statusCode)
      throw new AssertionError("ERROR: response: " + statusCode);

    TestUtil.checkSpan(true, new ComponentSpanCount("java-asynchttpclient", 1), new ComponentSpanCount("netty", 1));
  }
}
 
Example #10
Source File: TestAzureAsyncReader.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
private AzureAsyncReader prepareAsyncReader(final String responseBody, final int responseCode) {
  // Prepare response
  AsyncHttpClient client = mock(AsyncHttpClient.class);
  Response response = mock(Response.class);
  HttpResponseStatus status = mock(HttpResponseStatus.class);
  when(status.getStatusCode()).thenReturn(responseCode);
  when(response.getResponseBody()).thenReturn(responseBody);

  CompletableFuture<Response> future = new CompletableFuture<>(); //CompletableFuture.completedFuture(response);
  ListenableFuture<Response> resFuture = mock(ListenableFuture.class);
  when(resFuture.toCompletableFuture()).thenReturn(future);
  LocalDateTime versionDate = LocalDateTime.now(ZoneId.of("GMT")).minusDays(2);

  when(client.executeRequest(any(Request.class), any(AsyncCompletionHandler.class))).then(invocationOnMock -> {
    AsyncCompletionHandler<Response> responseHandler = invocationOnMock.getArgument(1, AsyncCompletionHandler.class);
    assertEquals(responseHandler.getClass(), BufferBasedCompletionHandler.class);
    responseHandler.onStatusReceived(status);
    try {
      responseHandler.onCompleted(response);
    } catch (Exception e) {
      future.completeExceptionally(e);
    }
    return resFuture;
  });

  AzureAsyncReader azureAsyncReader = spy(new AzureAsyncReader(
    "account", new Path("container/directory/file_00.parquet"),
    getMockAuthTokenProvider(), String.valueOf(versionDate.atZone(ZoneId.of("GMT")).toInstant().toEpochMilli()),
    true, client
  ));
  return azureAsyncReader;

}
 
Example #11
Source File: TwitterWrapper.java    From blynk-server with GNU General Public License v3.0 5 votes vote down vote up
public void send(String token, String secret, String message,
                 AsyncCompletionHandler<Response> handler) {
    asyncHttpClient
            .preparePost(TWITTER_UPDATE_STATUS_URL)
            .addQueryParam("status", message)
            .setSignatureCalculator(new OAuthSignatureCalculator(consumerKey, new RequestToken(token, secret)))
            .execute(handler);
}
 
Example #12
Source File: TwitterWrapperTest.java    From blynk-server with GNU General Public License v3.0 5 votes vote down vote up
@Test
@Ignore("requires real credentials")
public void testSend() throws Exception {
    TwitterProperties twitterProperties = new TwitterProperties(Collections.emptyMap());
    TwitterWrapper twitterWrapper = new TwitterWrapper(twitterProperties, client);

    String userToken = "";
    String userSecret = "";
    String message = "Hello!!!";

    twitterWrapper.send(userToken, userSecret, message,
            new AsyncCompletionHandler<>() {
                @Override
                public Response onCompleted(Response response) {
                    if (response.getStatusCode() != HttpResponseStatus.OK.code()) {
                        System.out.println("Error sending twit. Reason : " + response.getResponseBody());
                    }
                    assertEquals(200, response.getStatusCode());
                    return response;
                }

                @Override
                public void onThrowable(Throwable t) {
                    t.printStackTrace();
                    System.out.println("Error sending twit.");
                }
            });
    Thread.sleep(5000);
}
 
Example #13
Source File: AsyncTrelloHttpClient2.java    From trello-java-wrapper with Apache License 2.0 5 votes vote down vote up
@Override
public URI postForLocation(String url, Object object, String... params) {
    try {
        byte[] body = this.writer.writeValueAsBytes(object);
        Future<URI> f = asyncHttpClient.preparePost(expandUrl(url, params)).setBody(body).execute(
                new AsyncCompletionHandler<URI>() {

                    @Override
                    public URI onCompleted(Response response) {
                        String location = response.getHeader("Location");
                        if (location != null) {
                            return URI.create(location);
                        } else {
                            throw new TrelloHttpException("Location header not set");
                        }
                    }

                    @Override
                    public void onThrowable(Throwable t) {
                        throw new TrelloHttpException(t);
                    }
                });
        return f.get();
    } catch (IOException | InterruptedException | ExecutionException e) {
        throw new TrelloHttpException(e);
    }
}
 
Example #14
Source File: AsyncHttpClientTest.java    From java-specialagent with Apache License 2.0 5 votes vote down vote up
@Test
public void testWithHandler(final MockTracer tracer) throws IOException {
  final AtomicInteger counter = new AtomicInteger();
  try (final AsyncHttpClient client = new DefaultAsyncHttpClient()) {
    final Request request = new RequestBuilder(HttpConstants.Methods.GET).setUrl("http://localhost:12345").build();
    try {
      client.executeRequest(request, new AsyncCompletionHandler<Object>() {
        @Override
        public Object onCompleted(final Response response) {
          assertNotNull(tracer.activeSpan());
          counter.incrementAndGet();
          return response;
        }

        @Override
        public void onThrowable(final Throwable t) {
          assertNotNull(tracer.activeSpan());
          counter.incrementAndGet();
        }
      }).get(10, TimeUnit.SECONDS);
    }
    catch (final Exception ignore) {
    }
  }

  await().atMost(15, TimeUnit.SECONDS).until(TestUtil.reportedSpansSize(tracer), equalTo(1));
  assertEquals(1, tracer.finishedSpans().size());
  assertEquals(1, counter.get());
  assertNull(tracer.activeSpan());
}
 
Example #15
Source File: EventorProcessor.java    From blynk-server with GNU General Public License v3.0 5 votes vote down vote up
private void twit(DashBoard dash, String body) {
    if (Twitter.isWrongBody(body)) {
        log.debug("Wrong twit body.");
        return;
    }

    Twitter twitterWidget = dash.getTwitterWidget();

    if (twitterWidget == null
            || twitterWidget.token == null
            || twitterWidget.token.isEmpty()
            || twitterWidget.secret == null
            || twitterWidget.secret.isEmpty()) {
        log.debug("User has no access token provided for eventor twit.");
        return;
    }

    twitterWrapper.send(twitterWidget.token, twitterWidget.secret, body,
            new AsyncCompletionHandler<>() {
                @Override
                public Response onCompleted(Response response) {
                    if (response.getStatusCode() != HttpResponseStatus.OK.code()) {
                        log.debug("Error sending twit from eventor. Reason : {}.", response.getResponseBody());
                    }
                    return response;
                }

                @Override
                public void onThrowable(Throwable t) {
                    log.debug("Error sending twit from eventor.", t);
                }
            }
    );
}
 
Example #16
Source File: AsyncHttpClientPluginIT.java    From glowroot with Apache License 2.0 5 votes vote down vote up
@Override
public void transactionMarker() throws Exception {
    AsyncHttpClient asyncHttpClient = new DefaultAsyncHttpClient();
    final CountDownLatch latch = new CountDownLatch(1);
    final AtomicInteger statusCode = new AtomicInteger();
    asyncHttpClient.prepareGet("http://localhost:" + getPort() + "/hello3/")
            .execute(new AsyncCompletionHandler<Response>() {
                @Override
                public Response onCompleted(Response response) throws Exception {
                    latch.countDown();
                    return null;
                }
                @Override
                public State onStatusReceived(HttpResponseStatus status) {
                    statusCode.set(status.getStatusCode());
                    return null;
                }
                @Override
                public void onThrowable(Throwable t) {
                    t.printStackTrace();
                }
            });
    latch.await();
    asyncHttpClient.close();
    if (statusCode.get() != 200) {
        throw new IllegalStateException("Unexpected status code: " + statusCode);
    }
}
 
Example #17
Source File: IrisUpnpService.java    From arcusplatform with Apache License 2.0 4 votes vote down vote up
static void discover(final UpnpDeviceInformation device, @Nullable String location, long now) {
   device.discovery.set(now + UPNP_DISCOVERY_INTERVAL);
   if (location == null) {
      return;
   }

   AsyncHttpService.get(location).execute(new AsyncCompletionHandler<Response>() {
      @Override
      public Response onCompleted(@Nullable Response response) throws Exception {
         if (response == null || response.getStatusCode() != 200) {
            return response;
         }

         try {
            XmlPullParser parser = xmlFactory.newPullParser();
            parser.setInput(new StringReader(response.getResponseBody(StandardCharsets.UTF_8)));

            String manuf = device.manuf;
            String model = device.model;

            do {
               switch (parser.getEventType()) {
               case XmlPullParser.START_TAG:
                  switch (parser.getName().toLowerCase()) {
                  case "manufacturer":
                     String nmanuf = parser.nextText();
                     if (!nmanuf.trim().isEmpty() && manuf == null) {
                        manuf = nmanuf;
                     }
                     break;
                  case "modelnumber":
                     String nmodel = parser.nextText();
                     if (!nmodel.trim().isEmpty() && model == null) {
                        model = nmodel;
                     }
                     break;
                  default:
                     // ignore
                     break;
                  }
                  break;
               default:
                  // ignore
                  break;
               }

               //log.info("xml: {} -> {}", parser.getName(), parser.nextText());
            } while (parser.next() != XmlPullParser.END_DOCUMENT);

            device.manuf = manuf;
            device.model = model;
            if ((manuf != null) && (model != null)) {
               device.discovered = true;
               added(device);
            }
         } catch (Exception ex) {
            log.debug("failed to parse upnp descriptor:", ex);
         }

         return response;
      }
   });
}
 
Example #18
Source File: TestAzureAsyncReader.java    From dremio-oss with Apache License 2.0 4 votes vote down vote up
private void testSuccessHttpMode(boolean isSecure) {
  // Prepare response
  AsyncHttpClient client = mock(AsyncHttpClient.class);
  Response response = mock(Response.class);
  HttpResponseStatus status = mock(HttpResponseStatus.class);
  when(status.getStatusCode()).thenReturn(206);

  CompletableFuture<Response> future = CompletableFuture.completedFuture(response);
  ListenableFuture<Response> resFuture = mock(ListenableFuture.class);
  when(resFuture.toCompletableFuture()).thenReturn(future);
  LocalDateTime versionDate = LocalDateTime.now(ZoneId.of("GMT")).minusDays(2);

  byte[] responseBytes = getRandomBytes(20);
  HttpResponseBodyPart responsePart = mock(HttpResponseBodyPart.class);
  when(responsePart.getBodyByteBuffer()).thenReturn(ByteBuffer.wrap(responseBytes));

  when(client.executeRequest(any(Request.class), any(AsyncCompletionHandler.class))).then(invocationOnMock -> {
    // Validate URL
    Request req = invocationOnMock.getArgument(0, Request.class);
    String expectedPrefix = isSecure ? "https" : "http";
    assertEquals("Invalid request url",
      expectedPrefix + "://account.dfs.core.windows.net/container/directory%2Ffile_00.parquet", req.getUrl());

    // Validate Headers
    assertEquals("Invalid blob range header", "bytes=0-19", req.getHeaders().get("Range"));
    LocalDateTime dateHeaderVal = LocalDateTime.parse(req.getHeaders().get("Date"), DATE_RFC1123_FORMATTER);
    long dateHeaderDiffInSecs = Math.abs(dateHeaderVal.until(LocalDateTime.now(ZoneId.of("GMT")), ChronoUnit.SECONDS));
    assertTrue("Date header not set correctly", dateHeaderDiffInSecs < 2);

    LocalDateTime versionHeaderVal = LocalDateTime.parse(req.getHeaders().get("If-Unmodified-Since"), DATE_RFC1123_FORMATTER);
    assertEquals("Version header not set correctly", 0, versionHeaderVal.until(versionDate, ChronoUnit.SECONDS));

    assertEquals("Authz header not set correctly", req.getHeaders().get("Authorization"), "Bearer testtoken");
    assertNotNull(req.getHeaders().get("x-ms-client-request-id"));

    // Fill in response
    AsyncCompletionHandler<Response> responseHandler = invocationOnMock.getArgument(1, AsyncCompletionHandler.class);
    assertEquals(responseHandler.getClass(), BufferBasedCompletionHandler.class);

    responseHandler.onBodyPartReceived(responsePart);
    responseHandler.onStatusReceived(status);
    responseHandler.onCompleted(response);
    return resFuture;
  });

  AzureAsyncReader azureAsyncReader = spy(new AzureAsyncReader(
    "account", new Path("container/directory/file_00.parquet"),
    getMockAuthTokenProvider(), String.valueOf(versionDate.atZone(ZoneId.of("GMT")).toInstant().toEpochMilli()),
    isSecure, client
  ));

  try {
    ByteBuf buf = Unpooled.buffer(20);
    azureAsyncReader.readFully(0, buf, 0, 20).get();
    assertEquals(new String(buf.array()), new String(responseBytes));
    verify(azureAsyncReader).read(0, buf, 0, 20, 0);
  } catch (Exception e) {
    fail(e.getMessage());
  }
}
 
Example #19
Source File: Webhook.java    From attic-aurora with Apache License 2.0 4 votes vote down vote up
/**
 * Watches all TaskStateChanges and send them best effort to a configured endpoint.
 * <p>
 * This is used to expose an external event bus.
 *
 * @param stateChange State change notification.
 */
@Subscribe
public void taskChangedState(TaskStateChange stateChange) {
  LOG.debug("Got an event: {}", stateChange);
  // Ensure that this state change event is a transition, and not an event from when the scheduler
  // first initializes. In that case we do not want to resend the entire state. This check also
  // ensures that only whitelisted statuses will be sent to the configured endpoint.
  if (stateChange.isTransition() && isWhitelisted.apply(stateChange.getNewState())) {
    attemptsCounter.incrementAndGet();
    try {
      // We don't care about the response body, so only listen for the HTTP status code.
      createRequest(stateChange).execute(new AsyncCompletionHandler<Integer>() {
        @Override
        public void onThrowable(Throwable t) {
          errorsCounter.incrementAndGet();
          LOG.error("Error sending a Webhook event", t);
        }

        @Override
        public State onStatusReceived(HttpResponseStatus status) throws Exception {
          if (status.getStatusCode() == HttpConstants.ResponseStatusCodes.OK_200) {
            successCounter.incrementAndGet();
          } else {
            userErrorsCounter.incrementAndGet();
          }

          // Abort after we get the status because that is all we use for processing.
          return State.ABORT;
        }

        @Override
        public Integer onCompleted(Response response) throws Exception {
          // We do not care about the full response.
          return 0;
        }
      });
    } catch (Exception e) {
      LOG.error("Error making Webhook request", e);
      errorsCounter.incrementAndGet();
    }
  }
}
 
Example #20
Source File: TestAzureAsyncContainerProvider.java    From dremio-oss with Apache License 2.0 4 votes vote down vote up
@Test
public void testListContainers() throws IOException, ExecutionException, InterruptedException {
  AsyncHttpClient client = mock(AsyncHttpClient.class);
  Response response = mock(Response.class);
  when(response.getHeader(any(String.class))).thenReturn("");
  HttpResponseStatus status = mock(HttpResponseStatus.class);
  when(status.getStatusCode()).thenReturn(206);

  byte[] dfsCoreResponseBodyBytesPage1 = readStaticResponse("dfs-core-container-response-page1.json");
  RandomBytesResponseDispatcher dfsCoreResponseDispatcherPage1 = new RandomBytesResponseDispatcher(dfsCoreResponseBodyBytesPage1);

  byte[] dfsCoreResponseBodyBytesPage2 = readStaticResponse("dfs-core-container-response-page2.json");
  RandomBytesResponseDispatcher dfsCoreResponseDispatcherPage2 = new RandomBytesResponseDispatcher(dfsCoreResponseBodyBytesPage2);

  byte[] dfsCoreEmptyResponseBytes = readStaticResponse("dfs-core-container-empty.json");
  RandomBytesResponseDispatcher dfsCoreEmptyResponseDispatcher = new RandomBytesResponseDispatcher(dfsCoreEmptyResponseBytes);

  CompletableFuture<Response> future = CompletableFuture.completedFuture(response);
  ListenableFuture<Response> resFuture = mock(ListenableFuture.class);
  when(resFuture.toCompletableFuture()).thenReturn(future);
  when(resFuture.get()).thenReturn(response);

  when(client.executeRequest(any(Request.class), any(AsyncCompletionHandler.class))).then(invocationOnMock -> {
    Request req = invocationOnMock.getArgument(0, Request.class);
    AsyncCompletionHandler handler = invocationOnMock.getArgument(1, AsyncCompletionHandler.class);

    assertTrue(req.getUrl().startsWith("https://azurestoragev2hier.dfs.core.windows.net"));
    assertNotNull(req.getHeaders().get("Date"));
    assertNotNull(req.getHeaders().get("x-ms-client-request-id"));
    assertEquals("2019-07-07", req.getHeaders().get("x-ms-version")); // edit only if you're upgrading client
    assertEquals("Bearer testtoken", req.getHeaders().get("Authorization"));
    List<NameValuePair> queryParams = URLEncodedUtils.parse(new URI(req.getUrl()), StandardCharsets.UTF_8);
    String continuationKey = queryParams.stream()
      .filter(param -> param.getName().equalsIgnoreCase("continuation")).findAny()
      .map(NameValuePair::getValue).orElse("");

    // Return empty response if continuation key is not present. Return data in continuation call.
    // This is to ensure that the plugin makes another call when there's no data but continuation key present.
    if ("page1container1".equals(continuationKey)) {
      when(response.getHeader("x-ms-continuation")).thenReturn("page2container1");
      while (dfsCoreResponseDispatcherPage1.isNotFinished()) {
        handler.onBodyPartReceived(dfsCoreResponseDispatcherPage1.getNextBodyPart());
      }
    } else if ("page2container1".equals(continuationKey)) {
      when(response.getHeader("x-ms-continuation")).thenReturn("");
      while (dfsCoreResponseDispatcherPage2.isNotFinished()) {
        handler.onBodyPartReceived(dfsCoreResponseDispatcherPage2.getNextBodyPart());
      }
    } else {
      when(response.getHeader("x-ms-continuation")).thenReturn("page1container1");
      while (dfsCoreEmptyResponseDispatcher.isNotFinished()) {
        handler.onBodyPartReceived(dfsCoreEmptyResponseDispatcher.getNextBodyPart());
      }
    }

    handler.onStatusReceived(status);
    handler.onCompleted(response);
    return resFuture;
  });

  AzureStorageFileSystem parentClass = mock(AzureStorageFileSystem.class);
  AzureAuthTokenProvider authTokenProvider = getMockAuthTokenProvider();
  AzureAsyncContainerProvider containerProvider = new AzureAsyncContainerProvider(
    client, "azurestoragev2hier", authTokenProvider, parentClass, true);

  List<String> receivedContainers = containerProvider.getContainerCreators()
    .map(AzureStorageFileSystem.ContainerCreatorImpl.class::cast)
    .map(AzureStorageFileSystem.ContainerCreatorImpl::getName)
    .collect(Collectors.toList());

  List<String> expectedContainers = Arrays.asList("page1container1", "page1container2", "page1container3", "page2container1", "page2container2", "page2container3");
  assertEquals(expectedContainers, receivedContainers);
}
 
Example #21
Source File: MobileLoginHandler.java    From blynk-server with GNU General Public License v3.0 4 votes vote down vote up
private void facebookLogin(ChannelHandlerContext ctx, int messageId, String email,
                           String token, Version version) {
    asyncHttpClient.prepareGet(URL + token)
            .execute(new AsyncCompletionHandler<Response>() {
                @Override
                public Response onCompleted(Response response) {
                    if (response.getStatusCode() != 200) {
                        String errMessage = response.getResponseBody();
                        if (errMessage != null && errMessage.contains("expired")) {
                            log.warn("Facebook token expired for user {}.", email);
                        } else {
                            log.warn("Error getting facebook token for user {}. Reason : {}", email, errMessage);
                        }
                        ctx.writeAndFlush(notAllowed(messageId), ctx.voidPromise());
                        return response;
                    }

                    try {
                        String responseBody = response.getResponseBody();
                        FacebookTokenResponse facebookTokenResponse =
                                JsonParser.parseFacebookTokenResponse(responseBody);
                        if (email.equalsIgnoreCase(facebookTokenResponse.email)) {
                            User user = holder.userDao.getByName(email, AppNameUtil.BLYNK);
                            if (user == null) {
                                user = holder.userDao.addFacebookUser(email, AppNameUtil.BLYNK);
                            }

                            login(ctx, messageId, user, version);
                        }
                    } catch (Exception e) {
                        log.error("Error during facebook response parsing for user {}. Reason : {}",
                                email, response.getResponseBody());
                        ctx.writeAndFlush(notAllowed(messageId), ctx.voidPromise());
                    }

                    return response;
                }

                @Override
                public void onThrowable(Throwable t) {
                    log.error("Error performing facebook request. Token {} for user {}. Reason : {}",
                            token, email, t.getMessage());
                    ctx.writeAndFlush(notAllowed(messageId), ctx.voidPromise());
                }
            });
}
 
Example #22
Source File: TestAzureAsyncContainerProvider.java    From dremio-oss with Apache License 2.0 4 votes vote down vote up
@Test
public void testListContainersWithRetry() throws IOException, ExecutionException, InterruptedException {
  AsyncHttpClient client = mock(AsyncHttpClient.class);
  Response response = mock(Response.class);
  when(response.getHeader(any(String.class))).thenReturn("");
  HttpResponseStatus status = mock(HttpResponseStatus.class);
  when(status.getStatusCode()).thenReturn(206);
  HttpResponseStatus failedStatus = mock(HttpResponseStatus.class);
  when(failedStatus.getStatusCode()).thenReturn(500);

  byte[] dfsCoreResponseBodyBytes = readStaticResponse("dfs-core-container-response-page1.json");
  RandomBytesResponseDispatcher dfsCoreResponseDispatcher = new RandomBytesResponseDispatcher(dfsCoreResponseBodyBytes);

  CompletableFuture<Response> future = CompletableFuture.completedFuture(response);
  ListenableFuture<Response> resFuture = mock(ListenableFuture.class);
  when(resFuture.toCompletableFuture()).thenReturn(future);
  when(resFuture.get()).thenReturn(response);

  AtomicInteger retryAttemptNo = new AtomicInteger(0);
  when(client.executeRequest(any(Request.class), any(AsyncCompletionHandler.class))).then(invocationOnMock -> {
    AsyncCompletionHandler handler = invocationOnMock.getArgument(1, AsyncCompletionHandler.class);
    if (retryAttemptNo.incrementAndGet() < 10) {
      handler.onStatusReceived(failedStatus);
    } else {
      while (dfsCoreResponseDispatcher.isNotFinished()) {
        handler.onBodyPartReceived(dfsCoreResponseDispatcher.getNextBodyPart());
      }
      handler.onStatusReceived(status);
    }
    handler.onCompleted(response);
    return resFuture;
  });

  AzureStorageFileSystem parentClass = mock(AzureStorageFileSystem.class);
  AzureAuthTokenProvider authTokenProvider = getMockAuthTokenProvider();
  AzureAsyncContainerProvider containerProvider = new AzureAsyncContainerProvider(
    client, "azurestoragev2hier", authTokenProvider, parentClass, true);

  List<String> receivedContainers = containerProvider.getContainerCreators()
    .map(AzureStorageFileSystem.ContainerCreatorImpl.class::cast)
    .map(AzureStorageFileSystem.ContainerCreatorImpl::getName)
    .collect(Collectors.toList());

  List<String> expectedContainers = Arrays.asList("page1container1", "page1container2", "page1container3");
  assertEquals(expectedContainers, receivedContainers);
}
 
Example #23
Source File: GCMWrapper.java    From blynk-server with GNU General Public License v3.0 4 votes vote down vote up
public void send(GCMMessage messageBase, final Map<String, String> tokens, final String uid) {
    if (gcmURI == null) {
        log.error("Error sending push. Google cloud messaging properties not provided.");
        return;
    }

    String message;
    try {
        messageBase.setTitle(title);
        message = messageBase.toJson();
    } catch (JsonProcessingException e) {
        log.error("Error sending push. Wrong message format.");
        return;
    }

    httpclient.preparePost(gcmURI).setHeader("Authorization", apiKey)
            .setHeader(HttpHeaderNames.CONTENT_TYPE, "application/json; charset=utf-8")
            .setBody(message)
            .execute(new AsyncCompletionHandler<Response>() {
                @Override
                public Response onCompleted(Response response) throws Exception {
                    if (response.getStatusCode() == HttpResponseStatus.OK.code()) {
                        GCMResponseMessage gcmResponseMessage =
                                gcmResponseReader.readValue(response.getResponseBody());
                        if (gcmResponseMessage.failure == 1) {
                            String errorMessage =
                                    gcmResponseMessage.results != null && gcmResponseMessage.results.length > 0
                                            ? gcmResponseMessage.results[0].error
                                            : messageBase.getToken();
                            processError(errorMessage, tokens, uid);
                        }
                        return response;
                    }

                    return response;
                }

                @Override
                public void onThrowable(Throwable t) {
                    processError(t.getMessage(), tokens, uid);
                }
            });

}
 
Example #24
Source File: AsyncHttpRegistryClient.java    From edison-microservice with Apache License 2.0 4 votes vote down vote up
@Override
public void registerService() {
    stream(serviceRegistryProperties.getServers().split(","))
            .filter(server -> !isEmpty(server))
            .forEach(discoveryServer -> {
                try {
                    LOG.debug("Updating registration of service at '{}'", discoveryServer);
                    httpClient
                            .preparePut(discoveryServer + "/environments/" + edisonApplicationProperties.getEnvironment() + "/" + applicationInfo.name)
                            .setHeader("Content-Type", "application/vnd.otto.edison.links+json")
                            .setHeader("Accept", "application/vnd.otto.edison.links+json")
                            .setBody(
                                    "{\n" +
                                            "   \"groups\":[\"" + edisonApplicationProperties.getGroup() + "\"],\n" +
                                            "   \"expire\":" + serviceRegistryProperties.getExpireAfter() + ",\n" +
                                            "   \"links\":[{\n" +
                                            "      \"rel\":\"http://github.com/otto-de/edison/link-relations/microservice\",\n" +
                                            "      \"href\" : \"" + serviceRegistryProperties.getService() + "\",\n" +
                                            "      \"title\":\"" + applicationInfo.title + "\"\n" +
                                            "   }]  \n" +
                                            "}"
                            )
                            .execute(new AsyncCompletionHandler<Integer>() {
                                @Override
                                public Integer onCompleted(final Response response) throws Exception {
                                    if (response.getStatusCode() < 300) {
                                        LOG.info("Successfully updated registration at " + discoveryServer);
                                    } else {
                                        LOG.warn("Failed to update registration at '{}': Status='{}' '{}'", discoveryServer, response.getStatusCode(), response.getStatusText());
                                    }
                                    return response.getStatusCode();
                                }

                                @Override
                                public void onThrowable(final Throwable t) {
                                    LOG.error("Failed to register at '{}'", discoveryServer, t);
                                }
                            });
                } catch (final Exception e) {
                    LOG.error("Error updating registration", e);
                }
            });
}