com.ning.http.client.Response Java Examples

The following examples show how to use com.ning.http.client.Response. 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: WrappedUserResponseParser.java    From Singularity with Apache License 2.0 6 votes vote down vote up
SingularityUserPermissionsResponse parse(Response response) throws IOException {
  if (response.getStatusCode() > 299) {
    throw WebExceptions.unauthorized(
      String.format("Got status code %d when verifying jwt", response.getStatusCode())
    );
  } else {
    String responseBody = response.getResponseBody();
    SingularityUserPermissionsResponse permissionsResponse = objectMapper.readValue(
      responseBody,
      SingularityUserPermissionsResponse.class
    );
    if (!permissionsResponse.getUser().isPresent()) {
      throw WebExceptions.unauthorized(
        String.format("No user present in response %s", permissionsResponse)
      );
    }
    if (!permissionsResponse.getUser().get().isAuthenticated()) {
      throw WebExceptions.unauthorized(
        String.format("User not authenticated (response: %s)", permissionsResponse)
      );
    }
    return permissionsResponse;
  }
}
 
Example #2
Source File: ParsecHttpRequestRetryCallableTest.java    From parsec-libraries with Apache License 2.0 6 votes vote down vote up
@Test
public void testAutoRetryForHttpStatus500() throws Exception {
    request = new ParsecAsyncHttpRequest.Builder()
        .addRetryStatusCode(500)
        .build();
    setMockClientReturnStatusCode(500);

    ParsecHttpRequestRetryCallable<Response> parsecHttpRequestRetryCallable =
        new ParsecHttpRequestRetryCallable<>(mockClient, request);
    Response response = parsecHttpRequestRetryCallable.call();
    List<Response> responses = parsecHttpRequestRetryCallable.getResponses();

    // Default max retries is 3
    assertEquals(responses.size(), 4);
    assertEquals(response.getStatusCode(), 500);
}
 
Example #3
Source File: CCTSpec.java    From bdt with Apache License 2.0 6 votes vote down vote up
/**
 * Scale service from deploy-api
 *
 * @param service   : service to be scaled
 * @param instances : number of instance to scale to
 * @throws Exception
 */
@Given("^I scale service '(.+?)' to '(\\d+)' instances")
public void scaleService(String service, Integer instances) throws Exception {
    // Set REST connection
    commonspec.setCCTConnection(null, null);

    if (ThreadProperty.get("deploy_api_id") == null) {
        fail("deploy_api_id variable is not set. Check deploy-api is installed and @dcos annotation is working properly.");
    }
    String endPoint = "/service/" + ThreadProperty.get("deploy_api_id") + "/deploy/scale?instances=" + instances + "&serviceName=" + service;
    Future<Response> response;
    response = commonspec.generateRequest("PUT", false, null, null, endPoint, "", null, "");
    commonspec.setResponse("PUT", response.get());

    if (commonspec.getResponse().getStatusCode() != 200 && commonspec.getResponse().getStatusCode() != 201) {
        logger.error("Request failed to endpoint: " + endPoint + " with status code: " + commonspec.getResponse().getStatusCode() + " and response: " + commonspec.getResponse().getResponse());
        throw new Exception("Request failed to endpoint: " + endPoint + " with status code: " + commonspec.getResponse().getStatusCode() + " and response: " + commonspec.getResponse().getResponse());
    }
}
 
Example #4
Source File: QConfigAdminClient.java    From qconfig with MIT License 6 votes vote down vote up
@Override
protected Snapshot<String> parse(Response response) throws Exception {
    int code = Integer.parseInt(response.getHeader(Constants.CODE));
    logger.debug("response code is {}", code);
    String message = response.getResponseBody(Constants.UTF_8.name());
    logger.debug("response message is {}", message);
    if (code == ApiResponseCode.OK_CODE) {
        JsonNode jsonNode = objectMapper.readTree(message);
        JsonNode profileNode = jsonNode.get("profile");
        JsonNode versionNode = jsonNode.get("version");
        JsonNode contentNode = jsonNode.get("content");
        JsonNode statusNode = jsonNode.get("statuscode");
        if (profileNode != null
                && versionNode != null
                && contentNode != null
                && statusNode != null) {
            return new Snapshot<String>(profileNode.asText(), versionNode.asLong(), contentNode.asText(), StatusType.codeOf(statusNode.asInt()));
        }
    }
    return null;
}
 
Example #5
Source File: DatastoreImpl.java    From async-datastore-client with Apache License 2.0 6 votes vote down vote up
private ListenableFuture<MutationResult> executeAsyncMutations(final List<Mutation> mutations, final ListenableFuture<TransactionResult> txn) {
  final ListenableFuture<Response> httpResponse = Futures.transformAsync(txn, result -> {
    final CommitRequest.Builder request = CommitRequest.newBuilder();
    if (mutations != null) {
      request.addAllMutations(mutations);
    }

    final ByteString transaction = result.getTransaction();
    if (transaction != null) {
      request.setTransaction(transaction);
    } else {
      request.setMode(CommitRequest.Mode.NON_TRANSACTIONAL);
    }
    final ProtoHttpContent payload = new ProtoHttpContent(request.build());
    return ListenableFutureAdapter.asGuavaFuture(prepareRequest("commit", payload).execute());
  }, MoreExecutors.directExecutor());
  return Futures.transformAsync(httpResponse, response -> {
    if (!isSuccessful(response.getStatusCode())) {
      throw new DatastoreException(response.getStatusCode(), response.getResponseBody());
    }
    final CommitResponse commit = CommitResponse.parseFrom(streamResponse(response));
    return Futures.immediateFuture(MutationResult.build(commit));
  }, MoreExecutors.directExecutor());
}
 
Example #6
Source File: DruidRestUtils.java    From yuzhouwan with Apache License 2.0 6 votes vote down vote up
/**
 * Query Druid with Post.
 *
 * @param url     <Broker>:<Port, default: 8082>
 * @param json    query json
 * @param timeOut the timeout of http connection, default unit is millisecond
 * @param charset charset
 * @return the result of query
 */
public static String post(String url, String json, Long timeOut, TimeUnit timeUnit, String charset) {
    Future<Response> f = null;
    try (AsyncHttpClient asyncHttpClient = new AsyncHttpClient()) {
        AsyncHttpClient.BoundRequestBuilder builder = asyncHttpClient.preparePost(url);
        builder.setBodyEncoding(StandardCharsets.UTF_8.name()).setBody(json);
        return (f = builder.execute()).get(timeOut == null ? DEFEAT_TIMEOUT : timeOut,
                timeUnit == null ? DEFEAT_UNIT : timeUnit)
                .getResponseBody(charset == null ? StandardCharsets.UTF_8.name() : charset);
    } catch (Exception e) {
        _log.error(ExceptionUtils.errorInfo(e));
        throw new RuntimeException(e);
    } finally {
        if (f != null) f.cancel(true);
    }
}
 
Example #7
Source File: QConfigHttpServerClient.java    From qconfig with MIT License 6 votes vote down vote up
protected TypedCheckResult parse(Response response) throws IOException {
    LineReader reader = new LineReader(new StringReader(response.getResponseBody(Constants.UTF_8.name())));
    Map<Meta, VersionProfile> result = new HashMap<Meta, VersionProfile>();
    String line;
    try {
        while ((line = reader.readLine()) != null) {
            append(result, line);
        }
    } catch (IOException e) {
        //ignore
    }


    if (Constants.PULL.equals(response.getHeader(Constants.UPDATE_TYPE))) {
        return new TypedCheckResult(result, TypedCheckResult.Type.PULL);
    } else {
        return new TypedCheckResult(result, TypedCheckResult.Type.UPDATE);
    }
}
 
Example #8
Source File: QConfigHttpServerClient.java    From qconfig with MIT License 6 votes vote down vote up
@Override
protected boolean process(Response response) {
    if (response.getStatusCode() == HttpStatus.SC_NOT_MODIFIED) {
        set(TypedCheckResult.EMPTY);
        return true;
    }

    if (response.getStatusCode() != HttpStatus.SC_OK) {
        logger.warn("response status code is {}", response.getStatusCode());
        return false;
    }

    try {
        set(parse(response));
    } catch (IOException e) {
        logger.warn("parse response error", e);
        return false;
    }
    return true;
}
 
Example #9
Source File: JsonAsyncHttpPinotClientTransport.java    From incubator-pinot with Apache License 2.0 6 votes vote down vote up
@Override
public BrokerResponse get(long timeout, TimeUnit unit)
    throws ExecutionException {
  try {
    LOGGER.debug("Sending query {} to {}", _query, _url);

    Response httpResponse = _response.get(timeout, unit);

    LOGGER.debug("Completed query, HTTP status is {}", httpResponse.getStatusCode());

    if (httpResponse.getStatusCode() != 200) {
      throw new PinotClientException(
          "Pinot returned HTTP status " + httpResponse.getStatusCode() + ", expected 200");
    }

    String responseBody = httpResponse.getResponseBody("UTF-8");
    return BrokerResponse.fromJson(OBJECT_READER.readTree(responseBody));
  } catch (Exception e) {
    throw new ExecutionException(e);
  }
}
 
Example #10
Source File: RequestBuilderWrapperTest.java    From riposte with Apache License 2.0 6 votes vote down vote up
@Test
public void get_set_CustomCircuitBreaker_works_as_expected() {
    // given
    requestBuilderWrapper = new RequestBuilderWrapper(
            url,
            httpMethod,
            requestBuilder,
            customCircuitBreaker,
            disableCircuitBreaker);

    Optional<CircuitBreaker<Response>> alteredCircuitBreaker = Optional.of(new CircuitBreakerImpl<>());

    // when
    requestBuilderWrapper.setCustomCircuitBreaker(alteredCircuitBreaker);

    // then
    assertThat(requestBuilderWrapper.getCustomCircuitBreaker()).isEqualTo(alteredCircuitBreaker);
}
 
Example #11
Source File: AsyncTrelloHttpClient.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(UrlExpander.expandUrl(url, params)).execute(
                new AsyncCompletionHandler<T>() {

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

                    @Override
                    public void onThrowable(Throwable t) {
                        throw new TrelloHttpException(t);
                    }
                });
        return f.get();
    } catch (IOException | InterruptedException | ExecutionException e) {
        throw new TrelloHttpException(e);
    }
}
 
Example #12
Source File: HttpRequestClient.java    From qconfig with MIT License 6 votes vote down vote up
public <R> JsonV2<R> get(String url, Map<String, String> params, TypeReference<JsonV2<R>> typeReference) {
    AsyncHttpClient.BoundRequestBuilder prepareGet = httpClient.prepareGet(url);
    prepareGet.setHeader("Accept", "application/json");
    prepareGet.setHeader("Content-Type", "application/json; charset=utf-8");
    if (!CollectionUtils.isEmpty(params)) {
        for (Map.Entry<String, String> param : params.entrySet()) {
            prepareGet.addQueryParam(param.getKey(), param.getValue());
        }
    }
    Request request = prepareGet.build();
    try {
        Response response = httpClient.executeRequest(request).get(TIMEOUT_MS, TimeUnit.MILLISECONDS);
        int statusCode = response.getStatusCode();
        if (statusCode != Constants.OK_STATUS) {
            throw new RuntimeException(String.format("http request error,url:%s,status code:%d",url,statusCode));
        }
        return mapper.readValue(response.getResponseBody(DEFAULT_CHARSET), typeReference);
    }  catch (Exception e) {
        logger.error("request failOf, url [{}], params {}", url, params, e);
        throw new RuntimeException(e);
    }
}
 
Example #13
Source File: NingAsyncHttpRequest.java    From junit-servers with MIT License 6 votes vote down vote up
@Override
protected HttpResponse doExecute() throws Exception {
	final HttpUrl endpoint = getEndpoint();
	final String scheme = endpoint.getScheme();
	final String userInfo = null;
	final String host = endpoint.getHost();
	final int port = endpoint.getPort();
	final String path = UTF8UrlEncoder.encodePath(endpoint.getPath());
	final String query = null;
	final Uri uri = new Uri(scheme, userInfo, host, port, path, query);

	final String method = getMethod().getVerb();
	final RequestBuilder builder = new RequestBuilder(method, true).setUri(uri);

	handleQueryParameters(builder);
	handleBody(builder);
	handleHeaders(builder);
	handleCookies(builder);

	final Request request = builder.build();
	final long start = nanoTime();
	final Response response = client.executeRequest(request).get();
	final long duration = nanoTime() - start;

	return NingAsyncHttpResponseFactory.of(response, duration);
}
 
Example #14
Source File: Configs.java    From bistoury with GNU General Public License v3.0 6 votes vote down vote up
private static ProxyConfig getProxyConfig(String bistouryHost) {
    String url = "http://" + bistouryHost + PROXY_URI;
    try {
        AsyncHttpClient client = AsyncHttpClientHolder.getInstance();
        AsyncHttpClient.BoundRequestBuilder builder = client.prepareGet(url);
        builder.setHeader("content-type", "application/json;charset=utf-8");
        Response response = client.executeRequest(builder.build()).get();
        if (response.getStatusCode() != 200) {
            logger.error("get proxy config error, http code [{}], url [{}]", response.getStatusCode(), url);
            return null;
        }

        JsonResult<ProxyConfig> result = JacksonSerializer.deSerialize(response.getResponseBody("utf8"), PROXY_REFERENCE);
        if (!result.isOK()) {
            logger.error("get proxy config error, status code [{}], url [{}]", result.getStatus(), url);
            return null;
        }

        return result.getData();
    } catch (Throwable e) {
        logger.error("get proxy config error, url [{}]", url, e);
        return null;
    }
}
 
Example #15
Source File: Zendesk.java    From scava with Eclipse Public License 2.0 6 votes vote down vote up
protected AsyncCompletionHandler<List<SearchResultEntity>> handleSearchList(final String name) {
    return new AsyncCompletionHandler<List<SearchResultEntity>>() {
        @Override
        public List<SearchResultEntity> onCompleted(Response response) throws Exception {
            logResponse(response);
            if (isStatus2xx(response)) {
                List<SearchResultEntity> values = new ArrayList<SearchResultEntity>();
                for (JsonNode node : mapper.readTree(response.getResponseBodyAsStream()).get(name)) {
                    Class<? extends SearchResultEntity> clazz = searchResultTypes.get(node.get("result_type"));
                    if (clazz != null) {
                        values.add(mapper.convertValue(node, clazz));
                    }
                }
                return values;
            }
            throw new ZendeskResponseException(response);
        }
    };
}
 
Example #16
Source File: TestServerFixture.java    From fixd with Apache License 2.0 6 votes vote down vote up
@Test
public void testCustomHandlerRedirectsWithStatusCode() throws Exception {

    server.handle(Method.GET, "/")
          .with(new HttpRequestHandler() {
            public void handle(HttpRequest request, HttpResponse response) {
                
                response.redirect("http://localhost:8080/new-location", 301);
            }
        });
    
    Response resp = client.prepareGet("http://localhost:8080/")
                    .setFollowRedirects(false)
                    .execute().get();
    
    assertEquals(301, resp.getStatusCode());
    assertEquals("http://localhost:8080/new-location", resp.getHeader("Location"));
}
 
Example #17
Source File: BaseClient.java    From bdt with Apache License 2.0 6 votes vote down vote up
public <T> BaseResponseList<T> mapList(Response response, Class<T> type) throws Exception {
    List<T> r;
    BaseResponseList<T> rList = new BaseResponseList<>();

    try {
        r = mapper.readValue(response.getResponseBody(), new TypeReference<List<T>>() { });
    } catch (Exception e) {
        log.warn(e.getMessage());
        log.warn("Error mapping response to " + type.getCanonicalName() + ". Setting empty...");
        r = r = new ArrayList<>();
    }

    rList.setList(r);
    rList.setHttpStatus(response.getStatusCode());
    rList.setRawResponse(response.getResponseBody());
    return rList;
}
 
Example #18
Source File: SingularityWebhookAuthenticator.java    From Singularity with Apache License 2.0 6 votes vote down vote up
private SingularityUserPermissionsResponse verifyUncached(String authHeaderValue) {
  try {
    Response response = asyncHttpClient
      .prepareGet(webhookAuthConfiguration.getAuthVerificationUrl())
      .addHeader("Authorization", authHeaderValue)
      .execute()
      .get();
    SingularityUserPermissionsResponse permissionsResponse = responseParser.parse(
      response
    );
    permissionsCache.put(authHeaderValue, permissionsResponse);
    return permissionsResponse;
  } catch (Throwable t) {
    if (LOG.isTraceEnabled()) {
      LOG.trace("Exception verifying token", t);
    }
    if (t instanceof WebApplicationException) {
      throw (WebApplicationException) t;
    } else {
      throw new RuntimeException(t);
    }
  }
}
 
Example #19
Source File: BaseClient.java    From bdt with Apache License 2.0 5 votes vote down vote up
public <T extends BaseResponse> T map(Response response, Class<T> type) throws Exception {
    T r;

    try {
        r = mapper.readValue(response.getResponseBody(), type);
    } catch (Exception e) {
        log.warn(e.getMessage());
        log.warn("Error mapping response to " + type.getCanonicalName() + ". Setting empty...");
        r = type.newInstance();
    }

    r.setHttpStatus(response.getStatusCode());
    r.setRawResponse(response.getResponseBody());
    return r;
}
 
Example #20
Source File: LoggingAsyncHandlerWrapper.java    From parsec-libraries with Apache License 2.0 5 votes vote down vote up
private void logResponseOrThrowable(Request ningRequest, Response ningResponse, Throwable throwable, ParsecAsyncProgress progress) {

        if (!loggingPredicate.test(ningRequest, new ResponseOrThrowable(ningResponse, throwable))) {
            return;
        }

        Map<String, Object> additionalArgs = createAdditionalArgs(progress,  throwable);
        String messageToLog = formatter.format(ningRequest, ningResponse, additionalArgs);
        if(traceLogger.isTraceEnabled()) {
            traceLogger.trace(messageToLog);
        }
    }
 
Example #21
Source File: ConfigurationApiClient.java    From bdt with Apache License 2.0 5 votes vote down vote up
public CalicoConfiguration createNetwork(String data) throws Exception {
    String url = "https://".concat(ThreadProperty.get("EOS_ACCESS_POINT"))
            .concat(":" + getPort()).concat("/service/cct-configuration-api/network");

    Response response = post(url, data);
    return map(response, CalicoConfiguration.class);
}
 
Example #22
Source File: DeployApiClient.java    From bdt with Apache License 2.0 5 votes vote down vote up
public TearDownResponse tearDown(String serviceId) throws Exception {
    String url = "https://".concat(ThreadProperty.get("EOS_ACCESS_POINT"))
            .concat(":" + getPort())
            .concat("/service/").concat(ThreadProperty.get("deploy_api_id")).concat("/deploy/teardown?frameworkName=");
    url =  url.concat(serviceId);

    Response response = delete(url);
    return map(response, TearDownResponse.class);
}
 
Example #23
Source File: AsyncUtil.java    From httpsig-java with The Unlicense 5 votes vote down vote up
/**
 * Executes and replays a login request until one is found which satisfies the
 * {@link net.adamcin.httpsig.api.Challenge} being returned by the server, or until there are no more keys in the
 * keychain.
 * @param client the {@link AsyncHttpClient} to which the {@link Signer} will be attached
 * @param signer the {@link Signer} used for login and subsequent signature authentication
 * @param loginRequest the login {@link Request} to be executed and replayed while rotating the keychain
 * @return a {@link Future} expecting a {@link Response}
 * @throws IOException if a request throws an exception
 */
public static Future<Response> login(final AsyncHttpClient client,
                                     final Signer signer,
                                     final Request loginRequest)
        throws IOException {

    return login(client, signer, loginRequest, new AsyncCompletionHandler<Response>() {
        @Override
        public Response onCompleted(Response response) throws Exception {
            return response;
        }
    });
}
 
Example #24
Source File: CCTSpec.java    From bdt with Apache License 2.0 5 votes vote down vote up
/**
 * Get info for all networks
 *
 * @param envVar    : thread variable where to save info (OPTIONAL)
 * @param fileName  : file name where to save info (OPTIONAL)
 * @throws Exception
 */
@Given("^I get all networks( and save it in environment variable '(.*?)')?( and save it in file '(.*?)')?$")
public void getAllNetworks(String envVar, String fileName) throws Exception {
    // Set REST connection
    commonspec.setCCTConnection(null, null);

    String endPoint = "/service/" + ThreadProperty.get("configuration_api_id") + "/network/all";
    Future<Response> response;

    response = commonspec.generateRequest("GET", false, null, null, endPoint, "", null, "");
    commonspec.setResponse("GET", response.get());

    if (commonspec.getResponse().getStatusCode() != 200) {
        logger.error("Request failed to endpoint: " + endPoint + " with status code: " + commonspec.getResponse().getStatusCode() + " and response: " + commonspec.getResponse().getResponse());
        throw new Exception("Request failed to endpoint: " + endPoint + " with status code: " + commonspec.getResponse().getStatusCode() + " and response: " + commonspec.getResponse().getResponse());
    }

    String json = commonspec.getResponse().getResponse();

    if (envVar != null) {
        ThreadProperty.set(envVar, json);
    }

    if (fileName != null) {
        writeInFile(json, fileName);
    }
}
 
Example #25
Source File: TestServerFixture.java    From fixd with Apache License 2.0 5 votes vote down vote up
@Test
public void testSimplePostWithRequestParameter() throws Exception {

    server.handle(Method.POST, "/greeting", "application/x-www-form-urlencoded")
          .with(200, "text/plain", "Hello [request?name]");
   
    Response resp = client.preparePost("http://localhost:8080/greeting")
                    .addParameter("name", "Tim")
                    .execute().get();
   
    assertEquals("Hello Tim", resp.getResponseBody().trim());
}
 
Example #26
Source File: AsyncHttpClientLambdaAware.java    From blog-non-blocking-rest-service-with-spring-mvc with Apache License 2.0 5 votes vote down vote up
public ListenableFuture<Response> execute(String url, final Completed c, final Error e) throws IOException {
    return asyncHttpClient.prepareGet(url).execute(new AsyncCompletionHandler<Response>() {

        @Override
        public Response onCompleted(Response response) throws Exception {
            return c.onCompleted(response);
        }

        @Override
        public void onThrowable(Throwable t) {
            e.onThrowable(t);
        }

    });
}
 
Example #27
Source File: AggregatorEventHandler.java    From blog-non-blocking-rest-service-with-spring-mvc with Apache License 2.0 5 votes vote down vote up
public void onResult(int id, Response response) {

        try {
            // TODO: Handle status codes other than 200...
            int httpStatus = response.getStatusCode();
            log.logEndProcessingStepNonBlocking(id, httpStatus);

            // If many requests completes at the same time the following code must be executed in sequence for one thread at a time
            // Since we don't have any Actor-like mechanism to rely on (for the time being...) we simply ensure that the code block is executed by one thread at a time by an old school synchronized block
            // Since the processing in the block is very limited it will not cause a bottleneck.
            synchronized (result) {
                // Count down, aggregate answer and return if all answers (also cancel timer)...
                int noOfRes = noOfResults.incrementAndGet();

                // Perform the aggregation...
                log.logMessage("Safely adding response #" + id);
                result += response.getResponseBody() + '\n';

                if (noOfRes >= noOfCalls) {
                    onAllCompleted();
                }
            }



        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
 
Example #28
Source File: AsyncHttpClientHelper.java    From riposte with Apache License 2.0 5 votes vote down vote up
/**
 * Sets the {@link SpanNamingAndTaggingStrategy} that should be used when this class surrounds outbound calls
 * with subspans (i.e. when {@link #performSubSpanAroundDownstreamCalls} is true). The standard/default
 * class that is used is {@link DefaultAsyncHttpClientHelperSpanNamingAndTaggingStrategy} - if you want to
 * adjust something, you will probably want to start with that class as a base.
 *
 * @param spanNamingAndTaggingStrategy The strategy to use.
 * @return This same instance being called, to enable fluent setup.
 */
public AsyncHttpClientHelper setSpanNamingAndTaggingStrategy(
    SpanNamingAndTaggingStrategy<RequestBuilderWrapper, Response, Span> spanNamingAndTaggingStrategy
) {
    if (spanNamingAndTaggingStrategy == null) {
        throw new IllegalArgumentException("spanNamingAndTaggingStrategy cannot be null");
    }
    
    this.spanNamingAndTaggingStrategy = spanNamingAndTaggingStrategy;
    return this;
}
 
Example #29
Source File: MiosUnitConnector.java    From openhab1-addons with Eclipse Public License 2.0 5 votes vote down vote up
private void callMios(String url) {
    logger.debug("callMios: Would like to fire off the URL '{}'", url);

    try {
        @SuppressWarnings("unused")
        Future<Integer> f = getAsyncHttpClient().prepareGet(url).execute(new AsyncCompletionHandler<Integer>() {
            @Override
            public Integer onCompleted(Response response) throws Exception {

                // Yes, their content-type really does come back with just "xml", but we'll add "text/xml" for
                // when/if they ever fix that bug...
                if (!(response.getStatusCode() == 200 && ("text/xml".equals(response.getContentType())
                        || "xml".equals(response.getContentType())))) {
                    logger.debug("callMios: Error in HTTP Response code {}, content-type {}:\n{}",
                            new Object[] { response.getStatusCode(), response.getContentType(),
                                    response.hasResponseBody() ? response.getResponseBody() : "No Body" });
                }
                return response.getStatusCode();
            }

            @Override
            public void onThrowable(Throwable t) {
                logger.warn("callMios: Exception Throwable occurred fetching content: {}", t.getMessage(), t);
            }
        }

        );

        // TODO: Run it and walk away?
        //
        // Work out a better model to gather information about the
        // success/fail of the call, log details (etc) so things can be
        // diagnosed.
    } catch (Exception e) {
        logger.warn("callMios: Exception Error occurred fetching content: {}", e.getMessage(), e);
    }
}
 
Example #30
Source File: DeployApiClient.java    From bdt with Apache License 2.0 5 votes vote down vote up
public BaseResponseList<DeployedApp> getDeployedApps() throws Exception {
    String url = "https://".concat(ThreadProperty.get("EOS_ACCESS_POINT"))
            .concat(":" + getPort())
            .concat("/service/").concat(ThreadProperty.get("deploy_api_id")).concat("/deployments");

    Response response = get(url);
    return mapList(response, DeployedApp.class);
}