Search in sources :

Example 76 with HttpMethod

use of org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpMethod in project jocean-http by isdom.

the class MessageUtil method interact.

public static Interact interact(final HttpClient client) {
    final InitiatorBuilder _initiatorBuilder = client.initiator();
    final AtomicBoolean _isSSLEnabled = new AtomicBoolean(false);
    final AtomicReference<Observable<Object>> _obsreqRef = new AtomicReference<>(fullRequestWithoutBody(HttpVersion.HTTP_1_1, HttpMethod.GET));
    final List<String> _nvs = new ArrayList<>();
    final AtomicReference<URI> _uriRef = new AtomicReference<>();
    return new Interact() {

        private void updateObsRequest(final Action1<Object> action) {
            _obsreqRef.set(_obsreqRef.get().doOnNext(action));
        }

        private void addQueryParams() {
            if (!_nvs.isEmpty()) {
                updateObsRequest(MessageUtil.addQueryParam(_nvs.toArray(new String[0])));
            }
        }

        private void extractUriWithHost(final Object... reqbeans) {
            if (null == _uriRef.get()) {
                for (Object bean : reqbeans) {
                    try {
                        final Path path = bean.getClass().getAnnotation(Path.class);
                        if (null != path) {
                            final URI uri = new URI(path.value());
                            if (null != uri.getHost()) {
                                uri(path.value());
                                return;
                            }
                        }
                    } catch (Exception e) {
                        LOG.warn("exception when extract uri from bean {}, detail: {}", bean, ExceptionUtils.exception2detail(e));
                    }
                }
            }
        }

        private void checkAddr() {
            if (null == _uriRef.get()) {
                throw new RuntimeException("remote address not set.");
            }
        }

        private InitiatorBuilder addSSLFeatureIfNeed(final InitiatorBuilder builder) {
            if (_isSSLEnabled.get()) {
                return builder;
            } else if ("https".equals(_uriRef.get().getScheme())) {
                return builder.feature(F_SSL);
            } else {
                return builder;
            }
        }

        @Override
        public Interact method(final HttpMethod method) {
            updateObsRequest(MessageUtil.setMethod(method));
            return this;
        }

        @Override
        public Interact uri(final String uriAsString) {
            try {
                final URI uri = new URI(uriAsString);
                _uriRef.set(uri);
                _initiatorBuilder.remoteAddress(uri2addr(uri));
                updateObsRequest(MessageUtil.setHost(uri));
            } catch (URISyntaxException e) {
                throw new RuntimeException(e);
            }
            return this;
        }

        @Override
        public Interact path(final String path) {
            updateObsRequest(MessageUtil.setPath(path));
            return this;
        }

        @Override
        public Interact paramAsQuery(final String name, final String value) {
            _nvs.add(name);
            _nvs.add(value);
            return this;
        }

        @Override
        public Interact reqbean(final Object... reqbeans) {
            updateObsRequest(MessageUtil.toRequest(reqbeans));
            extractUriWithHost(reqbeans);
            return this;
        }

        @Override
        public Interact body(final Observable<? extends MessageBody> body) {
            _obsreqRef.set(_obsreqRef.get().compose(MessageUtil.addBody(body)));
            return this;
        }

        @Override
        public Interact body(final Object bean, final ContentEncoder contentEncoder) {
            return body(toBody(bean, contentEncoder.contentType(), contentEncoder.encoder()));
        }

        // @Override
        // public Interact disposeBodyOnTerminate(final boolean doDispose) {
        // _doDisposeBody.set(doDispose);
        // return this;
        // }
        @Override
        public Interact onrequest(final Action1<Object> action) {
            updateObsRequest(action);
            return this;
        }

        @Override
        public Interact feature(final Feature... features) {
            _initiatorBuilder.feature(features);
            if (isSSLEnabled(features)) {
                _isSSLEnabled.set(true);
            }
            return this;
        }

        private boolean isSSLEnabled(final Feature... features) {
            for (Feature f : features) {
                if (f instanceof Feature.ENABLE_SSL) {
                    return true;
                }
            }
            return false;
        }

        private Observable<? extends Object> hookDisposeBody(final Observable<Object> obsreq, final HttpInitiator initiator) {
            return obsreq.doOnNext(DisposableWrapperUtil.disposeOnForAny(initiator));
        }

        private Observable<? extends DisposableWrapper<HttpObject>> defineInteraction(final HttpInitiator initiator) {
            return initiator.defineInteraction(hookDisposeBody(_obsreqRef.get(), initiator));
        }

        @Override
        public Observable<? extends Interaction> execution() {
            checkAddr();
            addQueryParams();
            return addSSLFeatureIfNeed(_initiatorBuilder).build().map(new Func1<HttpInitiator, Interaction>() {

                @Override
                public Interaction call(final HttpInitiator initiator) {
                    final Observable<? extends DisposableWrapper<HttpObject>> interaction = defineInteraction(initiator);
                    return new Interaction() {

                        @Override
                        public HttpInitiator initiator() {
                            return initiator;
                        }

                        @Override
                        public Observable<? extends DisposableWrapper<HttpObject>> execute() {
                            return interaction;
                        }
                    };
                }
            });
        }
    };
}
Also used : DisposableWrapper(org.jocean.idiom.DisposableWrapper) ArrayList(java.util.ArrayList) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) HttpInitiator(org.jocean.http.client.HttpClient.HttpInitiator) HttpObject(io.netty.handler.codec.http.HttpObject) Path(javax.ws.rs.Path) Action1(rx.functions.Action1) AtomicReference(java.util.concurrent.atomic.AtomicReference) Observable(rx.Observable) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HttpObject(io.netty.handler.codec.http.HttpObject) InitiatorBuilder(org.jocean.http.client.HttpClient.InitiatorBuilder) HttpMethod(io.netty.handler.codec.http.HttpMethod)

Example 77 with HttpMethod

use of org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpMethod in project janusgraph by JanusGraph.

the class HttpHMACAuthenticationHandler method channelRead.

@Override
public void channelRead(final ChannelHandlerContext ctx, final Object msg) {
    if (msg instanceof FullHttpRequest) {
        final FullHttpRequest req = (FullHttpRequest) msg;
        final HttpMethod method = req.getMethod();
        final Map<String, String> credentialsMap = getCredentialsMap(ctx, req);
        if (credentialsMap == null) {
            sendError(ctx, msg);
            return;
        }
        if ("/session".equals(req.getUri()) && method.equals(HttpMethod.GET)) {
            try {
                credentialsMap.put(PROPERTY_GENERATE_TOKEN, "true");
                authenticator.authenticate(credentialsMap);
            } catch (Exception e) {
                sendError(ctx, msg);
                return;
            }
            replyWithToken(ctx, msg, credentialsMap.get(PROPERTY_TOKEN));
        } else {
            try {
                authenticator.authenticate(credentialsMap);
                ctx.fireChannelRead(req);
            } catch (Exception e) {
                sendError(ctx, msg);
            }
        }
    }
}
Also used : FullHttpRequest(io.netty.handler.codec.http.FullHttpRequest) HttpMethod(io.netty.handler.codec.http.HttpMethod)

Example 78 with HttpMethod

use of org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpMethod in project riposte by Nike-Inc.

the class StreamingAsyncHttpClient method getFallbackSpanName.

@NotNull
protected String getFallbackSpanName(@NotNull HttpRequest downstreamRequest) {
    try {
        HttpMethod method = downstreamRequest.method();
        String methodName = (method == null) ? null : method.name();
        return HttpRequestTracingUtils.getFallbackSpanNameForHttpRequest("async_downstream_call", methodName);
    } catch (Throwable t) {
        logger.error("An unexpected error occurred while trying to extract fallback span name from Netty HttpRequest. " + "A hardcoded fallback name will be used as a last resort, however this error should be investigated " + "as it shouldn't be possible.", t);
        return "async_downstream_call-UNKNOWN_HTTP_METHOD";
    }
}
Also used : HttpMethod(io.netty.handler.codec.http.HttpMethod) NotNull(org.jetbrains.annotations.NotNull)

Example 79 with HttpMethod

use of org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpMethod in project riposte by Nike-Inc.

the class AsyncHttpClientHelperTest method getRequestBuilder_delegates_to_helper_with_default_circuit_breaker_args.

@Test
public void getRequestBuilder_delegates_to_helper_with_default_circuit_breaker_args() {
    // given
    String url = UUID.randomUUID().toString();
    HttpMethod method = HttpMethod.valueOf(UUID.randomUUID().toString());
    RequestBuilderWrapper rbwMock = mock(RequestBuilderWrapper.class);
    doReturn(rbwMock).when(helperSpy).getRequestBuilder(anyString(), any(HttpMethod.class), any(Optional.class), anyBoolean());
    // when
    RequestBuilderWrapper rbw = helperSpy.getRequestBuilder(url, method);
    // then
    verify(helperSpy).getRequestBuilder(url, method, Optional.empty(), false);
    assertThat(rbw).isSameAs(rbwMock);
}
Also used : Optional(java.util.Optional) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) HttpMethod(io.netty.handler.codec.http.HttpMethod) Test(org.junit.Test)

Example 80 with HttpMethod

use of org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpMethod 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 -> {
        // given
        String url = "http://localhost/some/path";
        HttpMethod method = HttpMethod.valueOf(methodName);
        Optional<CircuitBreaker<Response>> cbOpt = variation.getLeft();
        boolean disableCb = variation.getRight();
        // when
        RequestBuilderWrapper rbw = helperSpy.getRequestBuilder(url, method, cbOpt, disableCb);
        // then
        verifyRequestBuilderWrapperGeneratedAsExpected(rbw, url, methodName, cbOpt, disableCb);
    });
}
Also used : Response(org.asynchttpclient.Response) CircuitBreaker(com.nike.fastbreak.CircuitBreaker) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.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

HttpMethod (io.netty.handler.codec.http.HttpMethod)95 Test (org.junit.Test)51 HttpRequest (io.netty.handler.codec.http.HttpRequest)28 DefaultHttpRequest (io.netty.handler.codec.http.DefaultHttpRequest)25 FullHttpRequest (io.netty.handler.codec.http.FullHttpRequest)21 URI (java.net.URI)15 IOException (java.io.IOException)14 AtomicReference (java.util.concurrent.atomic.AtomicReference)13 DataProvider (com.tngtech.java.junit.dataprovider.DataProvider)11 HttpVersion (io.netty.handler.codec.http.HttpVersion)11 DefaultHttpClient (org.jocean.http.client.impl.DefaultHttpClient)11 TestChannelCreator (org.jocean.http.client.impl.TestChannelCreator)11 TestChannelPool (org.jocean.http.client.impl.TestChannelPool)11 DefaultSignalClient (org.jocean.http.rosa.impl.DefaultSignalClient)11 HttpTrade (org.jocean.http.server.HttpServerBuilder.HttpTrade)11 Subscription (rx.Subscription)11 Action2 (rx.functions.Action2)11 ByteBuf (io.netty.buffer.ByteBuf)10 DefaultFullHttpRequest (io.netty.handler.codec.http.DefaultFullHttpRequest)10 Map (java.util.Map)9