io.micronaut.http.HttpRequest Java Examples
The following examples show how to use
io.micronaut.http.HttpRequest.
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: RequestAttributeArgumentBinder.java From micronaut-spring with Apache License 2.0 | 6 votes |
@Override public BindingResult<Object> bind(ArgumentConversionContext<Object> context, HttpRequest<?> source) { final AnnotationMetadata annotationMetadata = context.getAnnotationMetadata(); final boolean required = annotationMetadata.getValue("required", boolean.class).orElse(true); final String name = annotationMetadata.getValue(RequestAttribute.class, String.class).orElseGet(() -> annotationMetadata.getValue(RequestAttribute.class, "name", String.class).orElse(context.getArgument().getName()) ); return new BindingResult<Object>() { @Override public Optional<Object> getValue() { return source.getAttributes().get(name, context); } @Override public boolean isSatisfied() { return !required; } }; }
Example #2
Source File: GraphQLWsMessageHandler.java From micronaut-graphql with Apache License 2.0 | 6 votes |
@SuppressWarnings("rawtypes") private Publisher<GraphQLWsResponse> executeRequest( String operationId, GraphQLRequestBody payload, WebSocketSession session) { GraphQLInvocationData invocationData = new GraphQLInvocationData( payload.getQuery(), payload.getOperationName(), payload.getVariables()); HttpRequest httpRequest = session .get(HTTP_REQUEST_KEY, HttpRequest.class) .orElseThrow(() -> new RuntimeException("HttpRequest could not be retrieved from websocket session")); Publisher<ExecutionResult> executionResult = graphQLInvocation.invoke(invocationData, httpRequest); Publisher<GraphQLResponseBody> responseBody = graphQLExecutionResultHandler .handleExecutionResult(executionResult); return Flowable.fromPublisher(responseBody) .flatMap(body -> responseSender.send(operationId, body, session)); }
Example #3
Source File: AdapterTest.java From java-slack-sdk with MIT License | 6 votes |
@Test public void toSlackRequest() { AppConfig config = AppConfig.builder().build(); SlackAppMicronautAdapter adapter = new SlackAppMicronautAdapter(config); HttpRequest<String> req = mock(HttpRequest.class); Map<String, String> rawHeaders = new HashMap<>(); rawHeaders.put("X-Slack-Signature", "xxxxxxx"); SimpleHttpHeaders headers = new SimpleHttpHeaders(rawHeaders, new DefaultConversionService()); when(req.getHeaders()).thenReturn(headers); Map<CharSequence, List<String>> params = new HashMap<>(); params.put("foo", Arrays.asList("bar", "baz")); SimpleHttpParameters parameters = new SimpleHttpParameters(params, new DefaultConversionService()); when(req.getParameters()).thenReturn(parameters); Request<?> slackRequest = adapter.toSlackRequest(req, "token=random&ssl_check=1"); assertNotNull(slackRequest); assertEquals("token=random&ssl_check=1", slackRequest.getRequestBodyAsString()); assertEquals("xxxxxxx", slackRequest.getHeaders().getFirstValue("X-Slack-Signature")); assertEquals("bar", slackRequest.getQueryString().get("foo").get(0)); }
Example #4
Source File: CustomLoginHandlerTest.java From micronaut-microservices-poc with Apache License 2.0 | 6 votes |
@Test public void customLoginHandler() { //when: HttpRequest request = HttpRequest.create(HttpMethod.POST, "/login") .accept(MediaType.APPLICATION_JSON_TYPE) .body(new UsernamePasswordCredentials("jimmy.solid", "secret")); HttpResponse<CustomBearerAccessRefreshToken> rsp = httpClient.toBlocking().exchange(request, CustomBearerAccessRefreshToken.class); //then: assertThat(rsp.getStatus().getCode()).isEqualTo(200); assertThat(rsp.body()).isNotNull(); assertThat(rsp.body().getAccessToken()).isNotNull(); assertThat(rsp.body().getRefreshToken()).isNotNull(); assertThat(rsp.body().getAvatar()).isNotNull(); assertThat(rsp.body().getAvatar()).isEqualTo("static/avatars/jimmy_solid.png"); }
Example #5
Source File: CommandsTest.java From java-slack-sdk with MIT License | 6 votes |
@Test public void invalidSignature() { MutableHttpRequest<String> request = HttpRequest.POST("/slack/events", ""); request.header("Content-Type", "application/x-www-form-urlencoded"); String timestamp = "" + (System.currentTimeMillis() / 1000 - 30 * 60); request.header(SlackSignature.HeaderNames.X_SLACK_REQUEST_TIMESTAMP, timestamp); String signature = signatureGenerator.generate(timestamp, helloBody); request.header(SlackSignature.HeaderNames.X_SLACK_SIGNATURE, signature); request.body(helloBody); try { client.toBlocking().exchange(request, String.class); Assertions.fail(); } catch (HttpClientResponseException e) { Assertions.assertEquals(401, e.getStatus().getCode()); Assertions.assertEquals("{\"error\":\"invalid request\"}", e.getResponse().getBody().get()); } }
Example #6
Source File: DefaultGraphQLInvocation.java From micronaut-graphql with Apache License 2.0 | 6 votes |
/** * {@inheritDoc} */ @Override public Publisher<ExecutionResult> invoke(GraphQLInvocationData invocationData, HttpRequest httpRequest) { ExecutionInput.Builder executionInputBuilder = ExecutionInput.newExecutionInput() .query(invocationData.getQuery()) .operationName(invocationData.getOperationName()) .variables(invocationData.getVariables()); if (dataLoaderRegistry != null) { executionInputBuilder.dataLoaderRegistry(dataLoaderRegistry.get()); } ExecutionInput executionInput = executionInputBuilder.build(); return Flowable.fromPublisher(graphQLExecutionInputCustomizer.customize(executionInput, httpRequest)) .flatMap(customizedExecutionInput -> Publishers.fromCompletableFuture(() -> { try { return graphQL.executeAsync(customizedExecutionInput); } catch (Throwable e) { CompletableFuture future = new CompletableFuture(); future.completeExceptionally(e); return future; } })); }
Example #7
Source File: SlackAppMicronautAdapter.java From java-slack-sdk with MIT License | 6 votes |
public Request<?> toSlackRequest(HttpRequest<?> req, String requestBody) { RequestHeaders headers = new RequestHeaders( req.getHeaders() != null ? req.getHeaders().asMap() : Collections.emptyMap()); InetSocketAddress isa = req.getRemoteAddress(); String remoteAddress = null; if (isa != null && isa.getAddress() != null) { remoteAddress = toString(isa.getAddress().getAddress()); } SlackRequestParser.HttpRequest rawRequest = SlackRequestParser.HttpRequest.builder() .requestUri(req.getPath()) .queryString(req.getParameters() != null ? req.getParameters().asMap() : Collections.emptyMap()) .headers(headers) .requestBody(requestBody) .remoteAddress(remoteAddress) .build(); return requestParser.parse(rawRequest); }
Example #8
Source File: FromCustomizer.java From micronaut-graphql with Apache License 2.0 | 5 votes |
@SuppressWarnings("rawtypes") @Override public Publisher<ExecutionInput> customize(ExecutionInput executionInput, HttpRequest httpRequest) { return Publishers.just(executionInput.transform( builder -> builder.context(httpRequest.getRemoteAddress().toString()) )); }
Example #9
Source File: GraphQLController.java From micronaut-graphql with Apache License 2.0 | 5 votes |
/** * Executes the GraphQL request and returns the serialized {@link GraphQLResponseBody}. * * @param query the GraphQL query * @param operationName the GraphQL operation name * @param variables the GraphQL variables * @param httpRequest the HTTP request * @return the serialized GraphQL response */ private Publisher<String> executeRequest( String query, String operationName, Map<String, Object> variables, HttpRequest httpRequest) { GraphQLInvocationData invocationData = new GraphQLInvocationData(query, operationName, variables); Publisher<ExecutionResult> executionResult = graphQLInvocation.invoke(invocationData, httpRequest); Publisher<GraphQLResponseBody> responseBody = graphQLExecutionResultHandler.handleExecutionResult(executionResult); return Publishers.map(responseBody, graphQLJsonSerializer::serialize); }
Example #10
Source File: CustomClaimsTest.java From micronaut-microservices-poc with Apache License 2.0 | 5 votes |
@Test public void testCustomClaimsArePresentInJwt() { //when: HttpRequest request = HttpRequest.create(HttpMethod.POST, "/login") .accept(MediaType.APPLICATION_JSON_TYPE) .body(new UsernamePasswordCredentials("jimmy.solid", "secret")); HttpResponse<AccessRefreshToken> rsp = httpClient.toBlocking().exchange(request, AccessRefreshToken.class); //then: assertThat(rsp.getStatus().getCode()).isEqualTo(200); assertThat(rsp.body()).isNotNull(); assertThat(rsp.body().getAccessToken()).isNotNull(); assertThat(rsp.body().getRefreshToken()).isNotNull(); //when: String accessToken = rsp.body().getAccessToken(); JwtTokenValidator tokenValidator = server.getApplicationContext().getBean(JwtTokenValidator.class); Authentication authentication = Flowable.fromPublisher(tokenValidator.validateToken(accessToken)).blockingFirst(); //then: assertThat(authentication.getAttributes()).isNotNull(); assertThat(authentication.getAttributes()).containsKey("roles"); assertThat(authentication.getAttributes()).containsKey("iss"); assertThat(authentication.getAttributes()).containsKey("exp"); assertThat(authentication.getAttributes()).containsKey("iat"); assertThat(authentication.getAttributes()).containsKey("avatar"); assertThat(authentication.getAttributes().get("avatar")).isEqualTo("static/avatars/jimmy_solid.png"); }
Example #11
Source File: LoginTest.java From micronaut-microservices-poc with Apache License 2.0 | 5 votes |
@Test public void cantLoginWithInvalidCredentials() { try { UsernamePasswordCredentials upc = new UsernamePasswordCredentials("jimmy.solid","secret111"); HttpRequest loginRequest = HttpRequest.POST("/login", upc); HttpResponse<BearerAccessRefreshToken> rsp = httpClient.toBlocking().exchange(loginRequest, BearerAccessRefreshToken.class); fail(); } catch (HttpClientResponseException ex) { assertThat(ex.getStatus().getCode()).isEqualTo(HttpStatus.UNAUTHORIZED.getCode()); } }
Example #12
Source File: LoginTest.java From micronaut-microservices-poc with Apache License 2.0 | 5 votes |
@Test public void canLoginWithValidCredentials() { UsernamePasswordCredentials upc = new UsernamePasswordCredentials("jimmy.solid","secret"); HttpRequest loginRequest = HttpRequest.POST("/login", upc); HttpResponse<BearerAccessRefreshToken> rsp = httpClient.toBlocking().exchange(loginRequest, BearerAccessRefreshToken.class); assertThat(rsp.getStatus().getCode()).isEqualTo(200); assertThat(rsp.getBody().get().getUsername()).isEqualTo("jimmy.solid"); }
Example #13
Source File: CommandsTest.java From java-slack-sdk with MIT License | 5 votes |
@Test public void command() { MutableHttpRequest<String> request = HttpRequest.POST("/slack/events", ""); request.header("Content-Type", "application/x-www-form-urlencoded"); String timestamp = "" + (System.currentTimeMillis() / 1000); request.header(SlackSignature.HeaderNames.X_SLACK_REQUEST_TIMESTAMP, timestamp); String signature = signatureGenerator.generate(timestamp, helloBody); request.header(SlackSignature.HeaderNames.X_SLACK_SIGNATURE, signature); request.body(helloBody); HttpResponse<String> response = client.toBlocking().exchange(request, String.class); Assertions.assertEquals(200, response.getStatus().getCode()); Assertions.assertEquals("{\"text\":\"Thanks!\"}", response.getBody().get()); }
Example #14
Source File: CommandsTest.java From java-slack-sdk with MIT License | 5 votes |
@Test public void regexp_matching() { MutableHttpRequest<String> request = HttpRequest.POST("/slack/events", ""); request.header("Content-Type", "application/x-www-form-urlencoded"); String timestamp = "" + (System.currentTimeMillis() / 1000); request.header(SlackSignature.HeaderNames.X_SLACK_REQUEST_TIMESTAMP, timestamp); String signature = signatureGenerator.generate(timestamp, submissionBody); request.header(SlackSignature.HeaderNames.X_SLACK_SIGNATURE, signature); request.body(submissionBody); HttpResponse<String> response = client.toBlocking().exchange(request, String.class); Assertions.assertEquals(200, response.getStatus().getCode()); Assertions.assertEquals("{\"text\":\"/submission-no.2019\"}", response.getBody().get()); }
Example #15
Source File: AwsProxyRequestArgumentBinder.java From micronaut-aws with Apache License 2.0 | 5 votes |
@Override public BindingResult<AwsProxyRequest> bind(ArgumentConversionContext<AwsProxyRequest> context, HttpRequest<?> source) { if (source instanceof MicronautAwsProxyRequest) { final AwsProxyRequest awsProxyRequest = ((MicronautAwsProxyRequest<?>) source).getAwsProxyRequest(); return () -> Optional.ofNullable(awsProxyRequest); } return BindingResult.UNSATISFIED; }
Example #16
Source File: AwsProxyRequestContextArgumentBinder.java From micronaut-aws with Apache License 2.0 | 5 votes |
@Override public BindingResult<AwsProxyRequestContext> bind(ArgumentConversionContext<AwsProxyRequestContext> context, HttpRequest<?> source) { if (source instanceof MicronautAwsProxyRequest) { final AwsProxyRequest awsProxyRequest = ((MicronautAwsProxyRequest<?>) source).getAwsProxyRequest(); return () -> Optional.ofNullable(awsProxyRequest.getRequestContext()); } return BindingResult.UNSATISFIED; }
Example #17
Source File: AwsLambdaRuntimeApi.java From micronaut-aws with Apache License 2.0 | 5 votes |
/** * * @param requestId Lambda Request Identifier * @param errorMessage Error Message * @param errorType Error Type * @param lambdaFunctionErrorType Lambda Function Error Type * @return A request to the invocation error path to inform in JSON format about the error which was thrown during the function execution. */ default HttpRequest<AwsLambdaRuntimeApiError> invocationErrorRequest(@Nonnull String requestId, @Nullable String errorMessage, @Nullable String errorType, @Nullable String lambdaFunctionErrorType) { AwsLambdaRuntimeApiError error = new AwsLambdaRuntimeApiError(errorMessage, errorType); MutableHttpRequest<AwsLambdaRuntimeApiError> request = HttpRequest.POST(errorUri(requestId), error); if (lambdaFunctionErrorType != null) { return request.header(LAMBDA_RUNTIME_FUNCTION_ERROR_TYPE, lambdaFunctionErrorType); } return request; }
Example #18
Source File: AwsLambdaRuntimeApi.java From micronaut-aws with Apache License 2.0 | 5 votes |
/** * * @param errorMessage Error Message * @param errorType Error Type * @param lambdaFunctionErrorType Lambda Function Error Type * @return A post request which should be send if the runtime encounters an error during initialization to post an error message to the initialization error path. */ default HttpRequest<AwsLambdaRuntimeApiError> initializationErrorRequest(@Nullable String errorMessage, @Nullable String errorType, @Nullable String lambdaFunctionErrorType) { AwsLambdaRuntimeApiError error = new AwsLambdaRuntimeApiError(errorMessage, errorType); MutableHttpRequest<AwsLambdaRuntimeApiError> request = HttpRequest.POST(INIT_ERROR_URI, error); if (lambdaFunctionErrorType != null) { return request.header(LAMBDA_RUNTIME_FUNCTION_ERROR_TYPE, lambdaFunctionErrorType); } return request; }
Example #19
Source File: ControllerTest.java From java-slack-sdk with MIT License | 5 votes |
@Test public void test() throws Exception { AppConfig config = AppConfig.builder().signingSecret("secret").build(); SlackAppController controller = new SlackAppController(new App(config), new SlackAppMicronautAdapter(config)); assertNotNull(controller); HttpRequest<String> req = mock(HttpRequest.class); SimpleHttpHeaders headers = new SimpleHttpHeaders(new HashMap<>(), new DefaultConversionService()); when(req.getHeaders()).thenReturn(headers); SimpleHttpParameters parameters = new SimpleHttpParameters(new HashMap<>(), new DefaultConversionService()); when(req.getParameters()).thenReturn(parameters); HttpResponse<String> response = controller.dispatch(req, "token=random&ssl_check=1"); assertEquals(200, response.getStatus().getCode()); }
Example #20
Source File: GraphQLController.java From micronaut-graphql with Apache License 2.0 | 5 votes |
/** * Handles GraphQL {@code GET} requests. * * @param query the GraphQL query * @param operationName the GraphQL operation name * @param variables the GraphQL variables * @param httpRequest the HTTP request * @return the GraphQL response */ @Get(produces = APPLICATION_JSON, single = true) public Publisher<String> get( @QueryValue("query") String query, @Nullable @QueryValue("operationName") String operationName, @Nullable @QueryValue("variables") String variables, HttpRequest httpRequest) { // https://graphql.org/learn/serving-over-http/#get-request // // When receiving an HTTP GET request, the GraphQL query should be specified in the "query" query string. // For example, if we wanted to execute the following GraphQL query: // // { // me { // name // } // } // // This request could be sent via an HTTP GET like so: // // http://myapi/graphql?query={me{name}} // // Query variables can be sent as a JSON-encoded string in an additional query parameter called "variables". // If the query contains several named operations, // an "operationName" query parameter can be used to control which one should be executed. return executeRequest(query, operationName, convertVariablesJson(variables), httpRequest); }
Example #21
Source File: AdapterTest.java From java-slack-sdk with MIT License | 5 votes |
@Test public void toSlackRequest_with_remote_address() throws UnknownHostException { AppConfig config = AppConfig.builder().build(); SlackAppMicronautAdapter adapter = new SlackAppMicronautAdapter(config); HttpRequest<String> req = mock(HttpRequest.class); InetSocketAddress isa = new InetSocketAddress("localhost", 443); when(req.getRemoteAddress()).thenReturn(isa); Request<?> slackRequest = adapter.toSlackRequest(req, "token=random&ssl_check=1"); assertNotNull(slackRequest); assertEquals("127.0.0.1", slackRequest.getClientIpAddress()); }
Example #22
Source File: ModelRequestArgumentBinder.java From micronaut-spring with Apache License 2.0 | 5 votes |
@Override public BindingResult<Model> bind(ArgumentConversionContext<Model> context, HttpRequest<?> source) { final Optional<Model> attribute = source.getAttribute(ATTRIBUTE, Model.class); if (!attribute.isPresent()) { final ConcurrentModel concurrentModel = new ConcurrentModel(); source.setAttribute(ATTRIBUTE, concurrentModel); return () -> Optional.of(concurrentModel); } return () -> attribute; }
Example #23
Source File: GraphQLWsController.java From micronaut-graphql with Apache License 2.0 | 5 votes |
/** * Called when the connection is opened. We store the original request, since it might be needed for the * GraphQLInvocation. * * @param session WebSocketSession * @param request HttpRequest */ @OnOpen @SuppressWarnings("rawtypes") public void onOpen(WebSocketSession session, HttpRequest request) { session.put(HTTP_REQUEST_KEY, request); state.init(session); LOG.trace("Opened websocket connection with id {}", session.getId()); }
Example #24
Source File: MicronautNettyChannelResolver.java From micronaut-spring with Apache License 2.0 | 5 votes |
@Override public Optional<Channel> resolveChannel(HttpRequest<?> request) { if (request instanceof NettyHttpRequest) { final Channel channel = ((NettyHttpRequest<?>) request).getChannelHandlerContext().channel(); return Optional.of(channel); } return Optional.empty(); }
Example #25
Source File: MicronautNettyChannelResolver.java From micronaut-spring with Apache License 2.0 | 5 votes |
@Override public Optional<HttpContentProcessor<ByteBufHolder>> resolveContentProcessor(HttpRequest<?> request) { if (request instanceof NettyHttpRequest) { final NettyHttpRequest<?> nettyHttpRequest = (NettyHttpRequest<?>) request; return Optional.of( new DefaultHttpContentProcessor( nettyHttpRequest, serverConfiguration ) ); } return Optional.empty(); }
Example #26
Source File: MicronautServerHttpRequest.java From micronaut-spring with Apache License 2.0 | 5 votes |
/** * Default constructor. * @param request The request to adapt * @param channelResolver The channel resolver */ public MicronautServerHttpRequest( HttpRequest<?> request, ChannelResolver channelResolver) { super(request.getUri(), null, initHeaders(request)); this.request = request; this.channelResolver = channelResolver; }
Example #27
Source File: MicronautServerHttpRequest.java From micronaut-spring with Apache License 2.0 | 5 votes |
private static HttpHeaders initHeaders(HttpRequest<?> request) { final HttpHeaders httpHeaders = new HttpHeaders(); final io.micronaut.http.HttpHeaders micronautHeaders = request.getHeaders(); micronautHeaders.forEach(entry -> { final String key = entry.getKey(); final List<String> value = entry.getValue(); httpHeaders.addAll(key, value); }); return httpHeaders; }
Example #28
Source File: OwnerControllerTest.java From database-rider with Apache License 2.0 | 5 votes |
@Test void testListInitialOwners() { List<Owner> results = client.retrieve(HttpRequest.GET("/"), Argument.listOf(Owner.class)).blockingFirst(); Assertions.assertEquals( 2, results.size() ); }
Example #29
Source File: ServerHttpRequestBinder.java From micronaut-spring with Apache License 2.0 | 5 votes |
@Override public BindingResult<ServerHttpRequest> bind(ArgumentConversionContext<ServerHttpRequest> context, HttpRequest<?> source) { return () -> Optional.of(new MicronautServerHttpRequest( source, channelResolver )); }
Example #30
Source File: ModelMapRequestArgumentBinder.java From micronaut-spring with Apache License 2.0 | 5 votes |
@Override public BindingResult<ModelMap> bind(ArgumentConversionContext<ModelMap> context, HttpRequest<?> source) { final Optional<ModelMap> attribute = source.getAttribute(ATTRIBUTE, ModelMap.class); if (!attribute.isPresent()) { final ModelMap modelMap = new ModelMap(); source.setAttribute(ATTRIBUTE, modelMap); return () -> Optional.of(modelMap); } return () -> attribute; }