Search in sources :

Example 6 with Response

use of org.apache.apex.shaded.ning19.com.ning.http.client.Response in project killbill by killbill.

the class TestSecurity method testDynamicUserRolesInternal.

private void testDynamicUserRolesInternal(final String username, final String password, final String roleDefinition, final List<String> permissions, final boolean expectPermissionSuccess) throws Exception {
    Response response = killBillClient.addRoleDefinition(new RoleDefinition(roleDefinition, permissions), createdBy, reason, comment);
    Assert.assertEquals(response.getStatusCode(), 201);
    response = killBillClient.addUserRoles(new UserRoles(username, password, ImmutableList.of(roleDefinition)), createdBy, reason, comment);
    Assert.assertEquals(response.getStatusCode(), 201);
    // Now 'login' as new user (along with roles to make an API call requiring permissions), and check behavior
    logout();
    login(username, password);
    boolean success = false;
    try {
        final String catalogPath = Resources.getResource("SpyCarBasic.xml").getPath();
        killBillClient.uploadXMLCatalog(catalogPath, createdBy, reason, comment);
        success = true;
    } catch (final Exception e) {
        if (expectPermissionSuccess || !e.getMessage().startsWith("java.lang.IllegalArgumentException: Unauthorized")) {
            throw e;
        }
    } finally {
        Assert.assertTrue(success == expectPermissionSuccess);
    }
}
Also used : Response(com.ning.http.client.Response) UserRoles(org.killbill.billing.client.model.UserRoles) RoleDefinition(org.killbill.billing.client.model.RoleDefinition) KillBillClientException(org.killbill.billing.client.KillBillClientException)

Example 7 with Response

use of org.apache.apex.shaded.ning19.com.ning.http.client.Response in project killbill by killbill.

the class TestSecurity method testUserPermission.

@Test(groups = "slow")
public void testUserPermission() throws KillBillClientException {
    final String roleDefinition = "notEnoughToAddUserAndRoles";
    final List<String> permissions = new ArrayList<String>();
    for (Permission cur : Permission.values()) {
        if (!cur.getGroup().equals("user")) {
            permissions.add(cur.toString());
        }
    }
    Response response = killBillClient.addRoleDefinition(new RoleDefinition(roleDefinition, permissions), createdBy, reason, comment);
    Assert.assertEquals(response.getStatusCode(), 201);
    final String username = "candy";
    final String password = "lolipop";
    response = killBillClient.addUserRoles(new UserRoles(username, password, ImmutableList.of(roleDefinition)), createdBy, reason, comment);
    Assert.assertEquals(response.getStatusCode(), 201);
    // Now 'login' as new user (along with roles to make an API call requiring permissions), and check behavior
    logout();
    login(username, password);
    boolean success = false;
    try {
        killBillClient.addRoleDefinition(new RoleDefinition("dsfdsfds", ImmutableList.of("*")), createdBy, reason, comment);
        success = true;
    } catch (final Exception e) {
    } finally {
        Assert.assertFalse(success);
    }
    success = false;
    try {
        killBillClient.addUserRoles(new UserRoles("sdsd", "sdsdsd", ImmutableList.of(roleDefinition)), createdBy, reason, comment);
        success = true;
    } catch (final Exception e) {
    } finally {
        Assert.assertFalse(success);
    }
}
Also used : Response(com.ning.http.client.Response) UserRoles(org.killbill.billing.client.model.UserRoles) ArrayList(java.util.ArrayList) Permission(org.killbill.billing.security.Permission) RoleDefinition(org.killbill.billing.client.model.RoleDefinition) KillBillClientException(org.killbill.billing.client.KillBillClientException) Test(org.testng.annotations.Test)

Example 8 with Response

use of org.apache.apex.shaded.ning19.com.ning.http.client.Response in project NabAlive by jcheype.

the class MeteoApplication method httpCall.

public void httpCall(final String mac, final String city, final String country, final String unit, final String key, final String lang) throws UnsupportedEncodingException {
    StringBuilder url = new StringBuilder(BASE_URL);
    url.append("?weather=").append(URLEncoder.encode(city + "," + country, "UTF-8"));
    url.append("&hl=fr");
    logger.debug("making httpCall: {}", url);
    try {
        asyncHttpClient.prepareGet(url.toString()).execute(new AsyncCompletionHandler<Response>() {

            @Override
            public Response onCompleted(Response response) throws Exception {
                DocumentBuilder builder = builderLocal.get();
                String responseBody = response.getResponseBody("ISO-8859-1");
                StringReader reader = new StringReader(responseBody);
                InputSource is = new InputSource(reader);
                Document document = builder.parse(is);
                NodeList forecastConditions = document.getElementsByTagName("forecast_conditions");
                MeteoResult meteoResult = new MeteoResult(getNodeValue(forecastConditions.item(0).getChildNodes(), "low"), getNodeValue(forecastConditions.item(0).getChildNodes(), "high"), getNodeValue(forecastConditions.item(0).getChildNodes(), "icon"), getNodeValue(forecastConditions.item(1).getChildNodes(), "low"), getNodeValue(forecastConditions.item(1).getChildNodes(), "high"), getNodeValue(forecastConditions.item(1).getChildNodes(), "icon"), unit);
                meteoCache.asMap().putIfAbsent(key, meteoResult);
                sendMeteo(mac, meteoResult, lang);
                return response;
            }

            @Override
            public void onThrowable(Throwable t) {
                logger.error("error in meteo, http received", t);
            }
        });
    } catch (IOException e) {
        logger.error("error in meteo, http call", e);
    }
}
Also used : InputSource(org.xml.sax.InputSource) NodeList(org.w3c.dom.NodeList) IOException(java.io.IOException) Document(org.w3c.dom.Document) IOException(java.io.IOException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) Response(com.ning.http.client.Response) DocumentBuilder(javax.xml.parsers.DocumentBuilder) StringReader(java.io.StringReader)

Example 9 with Response

use of org.apache.apex.shaded.ning19.com.ning.http.client.Response in project riposte by Nike-Inc.

the class AsyncHttpClientHelper method getCircuitBreaker.

protected Optional<CircuitBreaker<Response>> getCircuitBreaker(RequestBuilderWrapper requestBuilderWrapper) {
    if (requestBuilderWrapper.disableCircuitBreaker)
        return Optional.empty();
    //      custom one is not specified.
    if (requestBuilderWrapper.customCircuitBreaker.isPresent())
        return requestBuilderWrapper.customCircuitBreaker;
    // No custom circuit breaker. Use the default for the given request's host.
    Uri uri = Uri.create(requestBuilderWrapper.url);
    String host = uri.getHost();
    EventLoop nettyEventLoop = requestBuilderWrapper.getCtx() == null ? null : requestBuilderWrapper.getCtx().channel().eventLoop();
    CircuitBreaker<Integer> defaultStatusCodeCircuitBreaker = getDefaultHttpStatusCodeCircuitBreakerForKey(host, Optional.ofNullable(nettyEventLoop), Optional.ofNullable(nettyEventLoop));
    return Optional.of(new CircuitBreakerDelegate<>(defaultStatusCodeCircuitBreaker, response -> (response == null ? null : response.getStatusCode())));
}
Also used : AtomicInteger(java.util.concurrent.atomic.AtomicInteger) HttpProcessingState(com.nike.riposte.server.http.HttpProcessingState) Span(com.nike.wingtips.Span) CircuitBreakerDelegate(com.nike.fastbreak.CircuitBreakerDelegate) NameResolver(com.ning.http.client.NameResolver) ManualModeTask(com.nike.fastbreak.CircuitBreaker.ManualModeTask) LoggerFactory(org.slf4j.LoggerFactory) TraceHeaders(com.nike.wingtips.TraceHeaders) Tracer(com.nike.wingtips.Tracer) CompletableFuture(java.util.concurrent.CompletableFuture) Deque(java.util.Deque) CircuitBreakerOpenException(com.nike.fastbreak.exception.CircuitBreakerOpenException) ConcurrentMap(java.util.concurrent.ConcurrentMap) InetAddress(java.net.InetAddress) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Map(java.util.Map) AsyncHttpClient(com.ning.http.client.AsyncHttpClient) AsyncHttpClientConfig(com.ning.http.client.AsyncHttpClientConfig) Response(com.ning.http.client.Response) Logger(org.slf4j.Logger) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HttpMethod(io.netty.handler.codec.http.HttpMethod) CircuitBreakerForHttpStatusCode.getDefaultHttpStatusCodeCircuitBreakerForKey(com.nike.fastbreak.CircuitBreakerForHttpStatusCode.getDefaultHttpStatusCodeCircuitBreakerForKey) EventLoop(io.netty.channel.EventLoop) UnknownHostException(java.net.UnknownHostException) TimeUnit(java.util.concurrent.TimeUnit) ChannelAttributes(com.nike.riposte.server.channelpipeline.ChannelAttributes) CircuitBreaker(com.nike.fastbreak.CircuitBreaker) MDC(org.slf4j.MDC) Optional(java.util.Optional) Uri(com.ning.http.client.uri.Uri) EventLoop(io.netty.channel.EventLoop) Uri(com.ning.http.client.uri.Uri)

Example 10 with Response

use of org.apache.apex.shaded.ning19.com.ning.http.client.Response in project riposte by Nike-Inc.

the class AsyncHttpClientHelperTest method getRequestBuilder_with_circuit_breaker_args_sets_values_as_expected.

@DataProvider(value = { "CONNECT", "DELETE", "GET", "HEAD", "POST", "OPTIONS", "PUT", "PATCH", "TRACE", "FOO_METHOD_DOES_NOT_EXIST" }, splitBy = "\\|")
@Test
public void getRequestBuilder_with_circuit_breaker_args_sets_values_as_expected(String methodName) {
    CircuitBreaker<Response> cbMock = mock(CircuitBreaker.class);
    List<Pair<Optional<CircuitBreaker<Response>>, Boolean>> variations = Arrays.asList(Pair.of(Optional.empty(), true), Pair.of(Optional.empty(), false), Pair.of(Optional.of(cbMock), true), Pair.of(Optional.of(cbMock), false));
    variations.forEach(variation -> {
        String url = "http://localhost/some/path";
        HttpMethod method = HttpMethod.valueOf(methodName);
        Optional<CircuitBreaker<Response>> cbOpt = variation.getLeft();
        boolean disableCb = variation.getRight();
        RequestBuilderWrapper rbw = helperSpy.getRequestBuilder(url, method, cbOpt, disableCb);
        verifyRequestBuilderWrapperGeneratedAsExpected(rbw, url, methodName, cbOpt, disableCb);
    });
}
Also used : Response(com.ning.http.client.Response) CircuitBreaker(com.nike.fastbreak.CircuitBreaker) Matchers.anyString(org.mockito.Matchers.anyString) HttpMethod(io.netty.handler.codec.http.HttpMethod) Pair(com.nike.internal.util.Pair) DataProvider(com.tngtech.java.junit.dataprovider.DataProvider) Test(org.junit.Test)

Aggregations

Response (com.ning.http.client.Response)33 Test (org.junit.Test)10 IOException (java.io.IOException)9 AsyncHttpClient (com.ning.http.client.AsyncHttpClient)7 Test (org.testng.annotations.Test)7 AsyncHttpClientConfig (com.ning.http.client.AsyncHttpClientConfig)4 Request (com.ning.http.client.Request)4 RequestBuilder (com.ning.http.client.RequestBuilder)4 DataProvider (com.tngtech.java.junit.dataprovider.DataProvider)4 HttpMethod (io.netty.handler.codec.http.HttpMethod)4 Map (java.util.Map)4 NodesInfoResponse (org.elasticsearch.action.admin.cluster.node.info.NodesInfoResponse)4 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)3 CircuitBreaker (com.nike.fastbreak.CircuitBreaker)3 Span (com.nike.wingtips.Span)3 AsyncCompletionHandler (com.ning.http.client.AsyncCompletionHandler)3 NettyAsyncHttpProvider (com.ning.http.client.providers.netty.NettyAsyncHttpProvider)3 CompletableFuture (java.util.concurrent.CompletableFuture)3 JsonObject (javax.json.JsonObject)3 JsonReader (javax.json.JsonReader)3