akka.http.javadsl.model.StatusCodes Java Examples
The following examples show how to use
akka.http.javadsl.model.StatusCodes.
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: DittoPublicKeyProviderTest.java From ditto with Eclipse Public License 2.0 | 6 votes |
private void mockSuccessfulPublicKeysRequestWithoutMatchingKeyId() { final JsonObject jsonWebKey = JsonObject.newBuilder() .set(JsonWebKey.JsonFields.KEY_TYPE, "RSA") .set(JsonWebKey.JsonFields.KEY_ALGORITHM, "HS256") .set(JsonWebKey.JsonFields.KEY_USAGE, "sig") .set(JsonWebKey.JsonFields.KEY_ID, "anotherId") .set(JsonWebKey.JsonFields.KEY_MODULUS, "pjdss8ZaDfEH6K6U7GeW2nxDqR4IP049fk1fK0lndimbMMVBdPv_hSpm8T8EtBDxrUdi1OHZfMhUixGaut-3nQ4GG9nM249oxhCtxqqNvEXrmQRGqczyLxuh-fKn9Fg--hS9UpazHpfVAFnB5aCfXoNhPuI8oByyFKMKaOVgHNqP5NBEqabiLftZD3W_lsFCPGuzr4Vp0YS7zS2hDYScC2oOMu4rGU1LcMZf39p3153Cq7bS2Xh6Y-vw5pwzFYZdjQxDn8x8BG3fJ6j8TGLXQsbKH1218_HcUJRvMwdpbUQG5nvA2GXVqLqdwp054Lzk9_B_f1lVrmOKuHjTNHq48w") .set(JsonWebKey.JsonFields.KEY_EXPONENT, "AQAB") .build(); final JsonArray keysArray = JsonArray.newBuilder().add(jsonWebKey).build(); final JsonObject keysJson = JsonObject.newBuilder().set("keys", keysArray).build(); final HttpResponse publicKeysResponse = HttpResponse.create() .withStatus(StatusCodes.OK) .withEntity(keysJson.toString()); when(httpClientMock.createSingleHttpRequest(PUBLIC_KEYS_REQUEST)) .thenReturn(CompletableFuture.completedFuture(publicKeysResponse)); }
Example #2
Source File: ContentTypeValidationDirectiveTest.java From ditto with Eclipse Public License 2.0 | 6 votes |
@Test public void testWithContentTypeWithoutCharset() { // Arrange final DittoHeaders dittoHeaders = DittoHeaders.empty(); final String type = MediaTypes.TEXT_PLAIN.toString(); final ContentType typeMissingCharset = MediaTypes.TEXT_PLAIN.toContentTypeWithMissingCharset(); // Act final TestRouteResult result = testRoute(extractRequestContext( ctx -> ensureValidContentType(Set.of(type), ctx, dittoHeaders, COMPLETE_OK))) .run(HttpRequest.PUT("someUrl").withEntity(typeMissingCharset, "something".getBytes())); // Assert result.assertStatusCode(StatusCodes.OK); }
Example #3
Source File: CorsEnablingDirective.java From ditto with Eclipse Public License 2.0 | 6 votes |
/** * Enables CORS - Cross-Origin Resource Sharing - for the wrapped {@code inner} Route. * * @param inner the inner route to be wrapped with the CORS enabling. * @return the new route wrapping {@code inner} with the CORS enabling. */ public Route enableCors(final Supplier<Route> inner) { return extractActorSystem(actorSystem -> { if (!httpConfig.isEnableCors()) { return inner.get(); } return Directives.optionalHeaderValueByType(AccessControlRequestHeaders.class, corsRequestHeaders -> { final ArrayList<HttpHeader> newHeaders = new ArrayList<>(CORS_HEADERS); corsRequestHeaders.ifPresent(toAdd -> newHeaders.add(AccessControlAllowHeaders.create( StreamSupport.stream(toAdd.getHeaders().spliterator(), false).toArray(String[]::new)) ) ); return route(options(() -> complete( HttpResponse.create().withStatus(StatusCodes.OK).addHeaders(newHeaders))), respondWithHeaders(newHeaders, inner) ); }); }); }
Example #4
Source File: ContentTypeValidationDirectiveTest.java From ditto with Eclipse Public License 2.0 | 6 votes |
@Test public void testWithUpperCaseContentTypeHeaderName() { // Arrange final DittoHeaders dittoHeaders = DittoHeaders.empty(); final String type = MediaTypes.APPLICATION_JSON.toString(); // Act final TestRouteResult result = testRoute(extractRequestContext( ctx -> ensureValidContentType(Set.of(type), ctx, dittoHeaders, COMPLETE_OK))) .run(HttpRequest.PUT("someUrl") .addHeader(HttpHeader.parse("CONTENT-TYPE", type)) .withEntity(ContentTypes.APPLICATION_OCTET_STREAM, "something".getBytes())); // Assert result.assertStatusCode(StatusCodes.OK); }
Example #5
Source File: AkkaHttpClientServiceShould.java From mutual-tls-ssl with Apache License 2.0 | 6 votes |
@Test public void executeRequest() { HttpResponse httpResponse = HttpResponse.create() .withEntity(ContentTypes.TEXT_PLAIN_UTF8, "Hello") .withStatus(StatusCodes.OK); when(akkaHttpClient.singleRequest(any(HttpRequest.class))).thenReturn(CompletableFuture.completedFuture(httpResponse)); ArgumentCaptor<HttpRequest> httpRequestArgumentCaptor = ArgumentCaptor.forClass(HttpRequest.class); ClientResponse clientResponse = victim.executeRequest(HTTP_URL); assertThat(clientResponse.getStatusCode()).isEqualTo(200); assertThat(clientResponse.getResponseBody()).isEqualTo("Hello"); verify(akkaHttpClient, times(1)).singleRequest(httpRequestArgumentCaptor.capture()); assertThat(httpRequestArgumentCaptor.getValue().method().value()).isEqualTo("GET"); assertThat(httpRequestArgumentCaptor.getValue().getHeaders()).containsExactly(HttpHeader.parse(TestConstants.HEADER_KEY_CLIENT_TYPE, AKKA_HTTP_CLIENT.getValue())); assertThat(httpRequestArgumentCaptor.getValue().getUri().toString()).isEqualTo(HTTP_URL); }
Example #6
Source File: DevOpsRouteTest.java From ditto with Eclipse Public License 2.0 | 6 votes |
@Test public void testPiggybackWithJsonException() { final String tooLongNumber = "89314404000484999942"; final String modifyAttribute = String.format("{\"type\":\"things.commands:modifyAttribute\"," + "\"thingId\":\"thing:id\"," + "\"attribute\":\"/attribute\"," + "\"value\":%s}", tooLongNumber); final String executePiggyBack = String.format("{\"type\":\"devops.commands:executePiggybackCommand\"," + "\"serviceName\":\"things\"," + "\"instance\":null," + "\"targetActorSelection\":\"1\"," + "\"piggybackCommand\":%s}", modifyAttribute); final RequestEntity requestEntity = HttpEntities.create(ContentTypes.APPLICATION_JSON, executePiggyBack); final TestRouteResult result = underTest.run(HttpRequest.POST("/devops/piggyback") .withEntity(requestEntity)); result.assertStatusCode(StatusCodes.BAD_REQUEST); }
Example #7
Source File: EncodingEnsuringDirective.java From ditto with Eclipse Public License 2.0 | 6 votes |
public static Route ensureEncoding(final Supplier<Route> inner) { return extractRequestContext(requestContext -> { final Uri uri = requestContext.getRequest().getUri(); try { // per default, Akka evaluates the query params "lazily" in the routes and throws an IllegalUriException // in case of error; we evaluate the query params explicitly here to be able to handle this error at // a central location uri.query(); } catch (final IllegalUriException e) { LOGGER.debug("URI parsing failed", e); final String rawRequestUri = HttpUtils.getRawRequestUri(requestContext.getRequest()); final String message = MessageFormat.format(URI_INVALID_TEMPLATE, rawRequestUri); return complete(StatusCodes.BAD_REQUEST, message); } return inner.get(); }); }
Example #8
Source File: ContentTypeValidationDirectiveTest.java From ditto with Eclipse Public License 2.0 | 6 votes |
@Test public void testValidContentType() { // Arrange final DittoHeaders dittoHeaders = DittoHeaders.empty(); final ContentType type = ContentTypes.APPLICATION_JSON; // Act final TestRouteResult result = testRoute(extractRequestContext( ctx -> ensureValidContentType(Set.of(type.mediaType().toString()), ctx, dittoHeaders, COMPLETE_OK))) .run(HttpRequest.PUT("someUrl").withEntity(type, "something".getBytes())); // Assert result.assertStatusCode(StatusCodes.OK); }
Example #9
Source File: OverallStatusRoute.java From ditto with Eclipse Public License 2.0 | 6 votes |
/** * Builds the {@code /status} route. * * @return the {@code /status} route. */ public Route buildOverallStatusRoute() { return rawPathPrefix(PathMatchers.slash().concat(PATH_OVERALL), () -> {// /overall/* final DevOpsBasicAuthenticationDirective devOpsBasicAuthenticationDirective = DevOpsBasicAuthenticationDirective.getInstance(devOpsConfig); return devOpsBasicAuthenticationDirective.authenticateDevOpsBasic(REALM_STATUS, get(() -> // GET // /overall/status // /overall/status/health // /overall/status/cluster rawPathPrefix(PathMatchers.slash().concat(PATH_STATUS), () -> concat( // /status pathEndOrSingleSlash(() -> completeWithFuture(createOverallStatusResponse())), // /status/health path(PATH_HEALTH, () -> completeWithFuture(createOverallHealthResponse())), // /status/cluster path(PATH_CLUSTER, () -> complete( HttpResponse.create().withStatus(StatusCodes.OK) .withEntity(ContentTypes.APPLICATION_JSON, clusterStateSupplier.get().toJson().toString())) ) )) )); }); }
Example #10
Source File: DittoPublicKeyProviderTest.java From ditto with Eclipse Public License 2.0 | 6 votes |
private void mockSuccessfulPublicKeysRequest() { final JsonObject jsonWebKey = JsonObject.newBuilder() .set(JsonWebKey.JsonFields.KEY_TYPE, "RSA") .set(JsonWebKey.JsonFields.KEY_ALGORITHM, "HS256") .set(JsonWebKey.JsonFields.KEY_USAGE, "sig") .set(JsonWebKey.JsonFields.KEY_ID, KEY_ID) .set(JsonWebKey.JsonFields.KEY_MODULUS, "pjdss8ZaDfEH6K6U7GeW2nxDqR4IP049fk1fK0lndimbMMVBdPv_hSpm8T8EtBDxrUdi1OHZfMhUixGaut-3nQ4GG9nM249oxhCtxqqNvEXrmQRGqczyLxuh-fKn9Fg--hS9UpazHpfVAFnB5aCfXoNhPuI8oByyFKMKaOVgHNqP5NBEqabiLftZD3W_lsFCPGuzr4Vp0YS7zS2hDYScC2oOMu4rGU1LcMZf39p3153Cq7bS2Xh6Y-vw5pwzFYZdjQxDn8x8BG3fJ6j8TGLXQsbKH1218_HcUJRvMwdpbUQG5nvA2GXVqLqdwp054Lzk9_B_f1lVrmOKuHjTNHq48w") .set(JsonWebKey.JsonFields.KEY_EXPONENT, "AQAB") .build(); final JsonArray keysArray = JsonArray.newBuilder().add(jsonWebKey).build(); final JsonObject keysJson = JsonObject.newBuilder().set("keys", keysArray).build(); final HttpResponse publicKeysResponse = HttpResponse.create() .withStatus(StatusCodes.OK) .withEntity(keysJson.toString()); when(httpClientMock.createSingleHttpRequest(PUBLIC_KEYS_REQUEST)) .thenReturn(CompletableFuture.completedFuture(publicKeysResponse)); }
Example #11
Source File: ThingsSseRouteBuilderTest.java From ditto with Eclipse Public License 2.0 | 6 votes |
@Test public void searchWithResumption() { final String lastEventId = "my:lastEventId"; final HttpHeader lastEventIdHeader = HttpHeader.parse("Last-Event-ID", lastEventId); final TestRouteResult routeResult = underTest.run( HttpRequest.GET(SEARCH_ROUTE) .addHeader(acceptHeader) .addHeader(lastEventIdHeader) ); final CompletableFuture<Void> assertions = CompletableFuture.runAsync(() -> { routeResult.assertMediaType(MediaTypes.TEXT_EVENT_STREAM); routeResult.assertStatusCode(StatusCodes.OK); }); final RetrieveThing retrieveThing = proxyActor.expectMsgClass(RetrieveThing.class); final Thing thing = Thing.newBuilder().setId(ThingId.of(lastEventId)).build(); proxyActor.reply(RetrieveThingResponse.of(ThingId.of(lastEventId), thing, retrieveThing.getDittoHeaders() )); final StreamThings streamThings = proxyActor.expectMsgClass(StreamThings.class); replySourceRef(proxyActor, Source.lazily(Source::empty)); assertions.join(); assertThat(streamThings.getSortValues()).contains(JsonArray.of(JsonValue.of(lastEventId))); }
Example #12
Source File: RootRouteTest.java From ditto with Eclipse Public License 2.0 | 6 votes |
@Test public void getThingWithVeryLongId() { final int numberOfUUIDs = 100; final StringBuilder pathBuilder = new StringBuilder(THINGS_2_PATH).append("/"); final StringBuilder idBuilder = new StringBuilder("namespace"); for (int i = 0; i < numberOfUUIDs; ++i) { idBuilder.append(':').append(UUID.randomUUID()); } pathBuilder.append(idBuilder); final ThingIdInvalidException expectedEx = ThingIdInvalidException.newBuilder(idBuilder.toString()) .dittoHeaders(DittoHeaders.empty()) .build(); final TestRouteResult result = rootTestRoute.run( withHttps(withPreAuthenticatedAuthentication(HttpRequest.GET(pathBuilder.toString())))); result.assertEntity(expectedEx.toJsonString()); result.assertStatusCode(StatusCodes.BAD_REQUEST); }
Example #13
Source File: HttpPushClientActorTest.java From ditto with Eclipse Public License 2.0 | 6 votes |
@Test public void placeholderReplacement() throws Exception { final Target target = TestConstants.Targets.TARGET_WITH_PLACEHOLDER .withAddress("PATCH:" + TestConstants.Targets.TARGET_WITH_PLACEHOLDER.getAddress()); connection = connection.toBuilder().setTargets(singletonList(target)).build(); new TestKit(actorSystem) {{ // GIVEN: local HTTP connection is connected final ActorRef underTest = actorSystem.actorOf(createClientActor(getRef(), getConnection(false))); underTest.tell(OpenConnection.of(connection.getId(), DittoHeaders.empty()), getRef()); expectMsg(new Status.Success(BaseClientState.CONNECTED)); // WHEN: a thing event is sent to a target with header mapping content-type=application/json final ThingModifiedEvent thingModifiedEvent = TestConstants.thingModified(Collections.emptyList()); final OutboundSignal outboundSignal = OutboundSignalFactory.newOutboundSignal(thingModifiedEvent, singletonList(target)); underTest.tell(outboundSignal, getRef()); // THEN: a POST-request is forwarded to the path defined in the target final HttpRequest thingModifiedRequest = requestQueue.take(); responseQueue.offer(HttpResponse.create().withStatus(StatusCodes.OK)); assertThat(thingModifiedRequest.getUri().getPathString()).isEqualTo("/target:ditto/thing@twin"); }}; }
Example #14
Source File: RootRouteTest.java From ditto with Eclipse Public License 2.0 | 5 votes |
@Test public void getNonExistingSearchUrl() { final HttpRequest request = withHttps(withPreAuthenticatedAuthentication(HttpRequest.GET(UNKNOWN_SEARCH_PATH))); final TestRouteResult result = rootTestRoute.run(request); result.assertStatusCode(StatusCodes.NOT_FOUND); }
Example #15
Source File: FeaturesRouteTest.java From ditto with Eclipse Public License 2.0 | 5 votes |
@Test public void putPropertyWithJsonPointerException() { final String featureJson = "{\"/wrongProperty\":\"value\"}"; final TestRouteResult result = underTest.run(HttpRequest.PUT(FEATURE_ENTRY_PROPERTIES_PATH) .withEntity(HttpEntities.create(ContentTypes.APPLICATION_JSON, featureJson))); result.assertStatusCode(StatusCodes.BAD_REQUEST); }
Example #16
Source File: RootRouteExceptionHandlerTest.java From ditto with Eclipse Public License 2.0 | 5 votes |
@Test public void handleCompletionExceptionWithUnhandledRuntimeExceptionAsCause() { final NumberFormatException numberFormatException = new NumberFormatException("42"); final CompletionException completionException = new CompletionException(numberFormatException); final TestRoute testRoute = getTestRoute(() -> { throw completionException; }); testRoute.run(HTTP_REQUEST) .assertStatusCode(StatusCodes.INTERNAL_SERVER_ERROR) .assertMediaType(MediaTypes.TEXT_PLAIN); Mockito.verifyNoInteractions(dreToHttpResponse); }
Example #17
Source File: FeaturesRouteTest.java From ditto with Eclipse Public License 2.0 | 5 votes |
@Test public void getPropertiesWithoutSlashButOtherText() { final HttpRequest request = HttpRequest.GET(FEATURE_ENTRY_PROPERTIES_PATH + "sfsdgsdg"); final TestRouteResult result = underTest.run(request); result.assertStatusCode(StatusCodes.NOT_FOUND); }
Example #18
Source File: RootRouteTest.java From ditto with Eclipse Public License 2.0 | 5 votes |
@Test public void getExceptionForDuplicateHeaderFields() { final HttpRequest httpRequest = HttpRequest.GET(THINGS_1_PATH_WITH_IDS) .addHeader(RawHeader.create("x-correlation-id", UUID.randomUUID().toString())) .addHeader(RawHeader.create("x-correlation-id", UUID.randomUUID().toString())); final TestRouteResult result = rootTestRoute.run(withHttps(withPreAuthenticatedAuthentication(httpRequest))); result.assertStatusCode(StatusCodes.BAD_REQUEST); }
Example #19
Source File: RootRouteExceptionHandlerTest.java From ditto with Eclipse Public License 2.0 | 5 votes |
@Test public void handleUnknownExceptionAsInternalServerError() { final TestRoute testRoute = getTestRoute(() -> { throw new NumberFormatException("42"); }); testRoute.run(HTTP_REQUEST) .assertStatusCode(StatusCodes.INTERNAL_SERVER_ERROR) .assertMediaType(MediaTypes.TEXT_PLAIN); Mockito.verifyNoInteractions(dreToHttpResponse); }
Example #20
Source File: RootRouteTest.java From ditto with Eclipse Public License 2.0 | 5 votes |
@Test public void getThingsUrlWithoutIds() { final TestRouteResult result = rootTestRoute.run(withHttps(withPreAuthenticatedAuthentication(HttpRequest.GET(THINGS_1_PATH)))); result.assertStatusCode(StatusCodes.BAD_REQUEST); }
Example #21
Source File: ThingsRouteTest.java From ditto with Eclipse Public License 2.0 | 5 votes |
@Test public void getAttributesWithTrailingSlash() { final HttpRequest request = HttpRequest.GET("/things/org.eclipse.ditto%3Adummy/attributes/"); final TestRouteResult result = underTest.run(request); result.assertStatusCode(StatusCodes.OK); final String entityString = result.entityString(); assertThat(entityString).contains(RetrieveAttributes.TYPE); }
Example #22
Source File: RootRouteTest.java From ditto with Eclipse Public License 2.0 | 5 votes |
@Test public void getThingsUrlWithIdsWithWrongVersionNumber() { final String thingsUrlWithIdsWithWrongVersionNumber = ROOT_PATH + RootRoute.HTTP_PATH_API_PREFIX + "/" + "nan" + "/" + ThingsRoute.PATH_THINGS + "?" + ThingsParameter.IDS + "=bumlux"; final TestRouteResult result = rootTestRoute.run( withHttps(withPreAuthenticatedAuthentication(HttpRequest.GET(thingsUrlWithIdsWithWrongVersionNumber)))); result.assertStatusCode(StatusCodes.NOT_FOUND); }
Example #23
Source File: FeaturesRouteTest.java From ditto with Eclipse Public License 2.0 | 5 votes |
@Test public void putPropertyWithEmptyPointer() { final HttpRequest request = HttpRequest.PUT(FEATURE_ENTRY_PROPERTIES_PATH + "//bar") .withEntity(ContentTypes.APPLICATION_JSON ,"\"bumlux\""); final TestRouteResult result = underTest.run(request); result.assertStatusCode(StatusCodes.BAD_REQUEST); }
Example #24
Source File: ThingsRouteTest.java From ditto with Eclipse Public License 2.0 | 5 votes |
@Test public void putNewThingWithAttributesSuccessfully() { final TestRouteResult result = underTest.run(HttpRequest.PUT("/things/org.eclipse.ditto%3Adummy") .withEntity(ContentTypes.APPLICATION_JSON, "{\"attributes\": {\"foo\": \"bar\"}}")); result.assertStatusCode(StatusCodes.OK); }
Example #25
Source File: ThingsRouteTest.java From ditto with Eclipse Public License 2.0 | 5 votes |
@Test public void createThingWithInvalidInitialDefinition() { final String body = "{\"definition\"org.eclipse.ditto:1234}"; final RequestEntity requestEntity = HttpEntities.create(ContentTypes.APPLICATION_JSON, body); final TestRouteResult result = underTest.run(HttpRequest.POST("/things").withEntity(requestEntity)); result.assertStatusCode(StatusCodes.BAD_REQUEST); }
Example #26
Source File: RootRouteTest.java From ditto with Eclipse Public License 2.0 | 5 votes |
@Test public void getExceptionDueToLargeHeaders() { final char[] chars = new char[8192]; Arrays.fill(chars, 'x'); final String largeString = new String(chars); final HttpRequest request = withPreAuthenticatedAuthentication(withHttps(HttpRequest.GET(THING_SEARCH_2_PATH) .withHeaders(Collections.singleton( akka.http.javadsl.model.HttpHeader.parse("x-correlation-id", largeString))))); final TestRouteResult result = rootTestRoute.run(request); result.assertStatusCode(StatusCodes.REQUEST_HEADER_FIELDS_TOO_LARGE); }
Example #27
Source File: ThingsRouteTest.java From ditto with Eclipse Public License 2.0 | 5 votes |
@Test public void putAttributeWithEmptyPointer() { final String body = "\"bumlux\""; final HttpRequest request = HttpRequest.PUT("/things/org.eclipse.ditto%3Adummy/attributes//bar") .withEntity(HttpEntities.create(ContentTypes.APPLICATION_JSON, body)); final TestRouteResult result = underTest.run(request); result.assertStatusCode(StatusCodes.BAD_REQUEST); }
Example #28
Source File: ThingsRouteTest.java From ditto with Eclipse Public License 2.0 | 5 votes |
@Test public void putAttributeWithJsonException() { final String tooLongNumber = "89314404000484999942"; final HttpRequest request = HttpRequest.PUT("/things/org.eclipse.ditto%3Adummy/attributes/attribute") .withEntity(HttpEntities.create(ContentTypes.APPLICATION_JSON, tooLongNumber)); final TestRouteResult result = underTest.run(request); result.assertStatusCode(StatusCodes.BAD_REQUEST); }
Example #29
Source File: ThingsRouteTest.java From ditto with Eclipse Public License 2.0 | 5 votes |
@Test public void putAttributeWithJsonPointerException() { final String attributeJson = "{\"/attributeTest\":\"test\"}"; final HttpRequest request = HttpRequest.PUT("/things/org.eclipse.ditto%3Adummy/attributes") .withEntity(HttpEntities.create(ContentTypes.APPLICATION_JSON, attributeJson)); final TestRouteResult result = underTest.run(request); result.assertStatusCode(StatusCodes.BAD_REQUEST); }
Example #30
Source File: ThingsSseRouteBuilderTest.java From ditto with Eclipse Public License 2.0 | 5 votes |
@Test public void putWithAcceptHeaderFails() { underTest.run(HttpRequest.PUT(THINGS_ROUTE).addHeader(acceptHeader)) .assertStatusCode(StatusCodes.METHOD_NOT_ALLOWED); underTest.run(HttpRequest.PUT(SEARCH_ROUTE).addHeader(acceptHeader)) .assertStatusCode(StatusCodes.METHOD_NOT_ALLOWED); }