Java Code Examples for org.eclipse.jetty.http.HttpStatus

The following examples show how to use org.eclipse.jetty.http.HttpStatus. These examples are extracted from open source projects. 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
@Test
void solveCassandraMappingInconsistencyShouldSolveNothingWhenNoInconsistencies() {
    with()
        .put(AliasRoutes.ROOT_PATH + SEPARATOR + USERNAME + "/sources/" + ALIAS_1);
    with()
        .put(AliasRoutes.ROOT_PATH + SEPARATOR + USERNAME + "/sources/" + ALIAS_2);

    String taskId = with()
        .queryParam("action", "SolveInconsistencies")
        .post(CassandraMappingsRoutes.ROOT_PATH)
        .jsonPath()
        .get("taskId");

    with()
        .basePath(TasksRoutes.BASE)
        .get(taskId + "/await");

    when()
        .get(AliasRoutes.ROOT_PATH + SEPARATOR + USERNAME)
    .then()
        .contentType(ContentType.JSON)
    .statusCode(HttpStatus.OK_200)
        .body("source", hasItems(ALIAS_1, ALIAS_2));
}
 
Example 2
Source Project: james-project   Source File: GroupsRoutesTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
void putMalformedGroupShouldReturnBadRequest() {
    Map<String, Object> errors = when()
        .put("not-an-address" + SEPARATOR + USER_A)
    .then()
        .statusCode(HttpStatus.BAD_REQUEST_400)
        .contentType(ContentType.JSON)
        .extract()
        .body()
        .jsonPath()
        .getMap(".");

    assertThat(errors)
        .containsEntry("statusCode", HttpStatus.BAD_REQUEST_400)
        .containsEntry("type", "InvalidArgument")
        .containsEntry("message", "The group is not an email address")
        .containsEntry("details", "Out of data at position 1 in 'not-an-address'");
}
 
Example 3
Source Project: james-project   Source File: AliasRoutesTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
void putSameSourceAndDestinationShouldReturnBadRequest() {
    Map<String, Object> errors = when()
        .put(BOB_ALIAS + SEPARATOR + "sources" + SEPARATOR + BOB_ALIAS)
    .then()
        .statusCode(HttpStatus.BAD_REQUEST_400)
        .contentType(ContentType.JSON)
        .extract()
        .body()
        .jsonPath()
        .getMap(".");

    assertThat(errors)
        .containsEntry("statusCode", HttpStatus.BAD_REQUEST_400)
        .containsEntry("type", "InvalidArgument")
        .containsEntry("message", "Source and destination can't be the same!");
}
 
Example 4
Source Project: james-project   Source File: TasksRoutesTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
void getAwaitShouldAwaitTaskCompletion() {
    TaskId taskId = taskManager.submit(new MemoryReferenceTask(() -> {
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        return Task.Result.COMPLETED;
    }));

    when()
        .get("/" + taskId.getValue() + "/await")
    .then()
        .statusCode(HttpStatus.OK_200)
        .body("status", is("completed"));
}
 
Example 5
Source Project: james-project   Source File: MappingRoutesTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
void getUserMappingShouldReturnEmptyWhenNoDomainOnUserParameter() throws RecipientRewriteTableException {
    recipientRewriteTable.addAddressMapping(
        MappingSource.fromUser(Username.of(ALICE_ADDRESS)), ALICE_USER);
    recipientRewriteTable.addAliasMapping(
        MappingSource.fromUser(Username.of(ALICE_ADDRESS)), ALICE_ALIAS);
    recipientRewriteTable.addGroupMapping(
        MappingSource.fromUser(Username.of(ALICE_ADDRESS)), ALICE_GROUP);

    String jsonBody = when()
            .get("/user/alice")
        .then()
            .contentType(ContentType.JSON)
            .statusCode(HttpStatus.OK_200)
        .extract()
            .body()
            .asString();

    assertThatJson(jsonBody)
        .when(Option.IGNORING_ARRAY_ORDER)
        .isEqualTo("[]");
}
 
Example 6
Source Project: james-project   Source File: DomainsRoutesTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
void deleteShouldRemoveTheGivenDomain() {
    with()
        .put(DOMAIN);

    when()
        .delete(DOMAIN)
    .then()
        .statusCode(HttpStatus.NO_CONTENT_204);

    when()
        .get()
    .then()
        .contentType(ContentType.JSON)
        .statusCode(HttpStatus.OK_200)
        .body(".", hasSize(0));
}
 
Example 7
Source Project: james-project   Source File: UserQuotaRoutesTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
void putSizeShouldRejectInvalid() {
    Map<String, Object> errors = with()
        .body("invalid")
        .put(QUOTA_USERS + "/" + BOB.asString() + "/" + SIZE)
    .then()
        .statusCode(HttpStatus.BAD_REQUEST_400)
        .contentType(ContentType.JSON)
        .extract()
        .body()
        .jsonPath()
        .getMap(".");

    assertThat(errors)
        .containsEntry("statusCode", HttpStatus.BAD_REQUEST_400)
        .containsEntry("type", "InvalidArgument")
        .containsEntry("message", "Invalid quota. Need to be an integer value greater or equal to -1")
        .containsEntry("details", "For input string: \"invalid\"");
}
 
Example 8
Source Project: james-project   Source File: DomainMappingsRoutesTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
void addSpecificDomainMappingWithInvalidDomainInPath() {
    Map<String, Object> errors =
        when()
            .get("[email protected]")
        .then()
            .statusCode(HttpStatus.BAD_REQUEST_400)
            .contentType(ContentType.JSON)
        .extract()
            .body()
            .jsonPath()
            .getMap(".");

    assertThat(errors)
        .containsEntry("statusCode", HttpStatus.BAD_REQUEST_400)
        .containsEntry("type", "InvalidArgument")
        .hasEntrySatisfying("message", o -> assertThat((String) o).matches("^The domain .* is invalid\\.$"));
}
 
Example 9
Source Project: james-project   Source File: UserQuotaRoutesTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
void getQuotaShouldReturnSizeWhenNoCount(WebAdminQuotaSearchTestSystem testSystem) throws MailboxException {
    MaxQuotaManager maxQuotaManager = testSystem.getQuotaSearchTestSystem().getMaxQuotaManager();
    UserQuotaRootResolver userQuotaRootResolver = testSystem.getQuotaSearchTestSystem().getQuotaRootResolver();

    int maxStorage = 42;
    maxQuotaManager.setMaxStorage(userQuotaRootResolver.forUser(BOB), QuotaSizeLimit.size(maxStorage));

    JsonPath jsonPath =
        when()
            .get(QUOTA_USERS + "/" + BOB.asString())
        .then()
            .statusCode(HttpStatus.OK_200)
            .contentType(ContentType.JSON)
        .extract()
            .jsonPath();

    SoftAssertions softly = new SoftAssertions();
    softly.assertThat(jsonPath.getLong("user." + SIZE)).isEqualTo(maxStorage);
    softly.assertThat(jsonPath.getObject("user." + COUNT, Long.class)).isNull();
    softly.assertAll();
}
 
Example 10
Source Project: cassandra-reaper   Source File: ClusterResourceTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testAddCluster() throws Exception {
  final MockObjects mocks = initMocks();

  ClusterResource clusterResource = new ClusterResource(mocks.context, mocks.cryptograph, EXECUTOR);

  Response response = clusterResource
      .addOrUpdateCluster(mocks.uriInfo, Optional.of(SEED_HOST),
              Optional.of(Cluster.DEFAULT_JMX_PORT),
              Optional.of(JMX_USERNAME),
              Optional.of(JMX_PASSWORD));

  Assertions.assertThat(response.getStatus()).isEqualTo(HttpStatus.CREATED_201);
  assertEquals(1, mocks.context.storage.getClusters().size());

  Cluster cluster = mocks.context.storage.getCluster(CLUSTER_NAME);
  assertNotNull("Did not find expected cluster", cluster);
  assertEquals(0, mocks.context.storage.getRepairRunsForCluster(cluster.getName(), Optional.of(1)).size());
  assertEquals(CLUSTER_NAME, cluster.getName());
  assertEquals(1, cluster.getSeedHosts().size());
  assertEquals(SEED_HOST, cluster.getSeedHosts().iterator().next());
  assertTrue(cluster.getJmxCredentials().isPresent());
  assertEquals(JMX_USERNAME, cluster.getJmxCredentials().get().getUsername());
  assertNotEquals(JMX_PASSWORD, cluster.getJmxCredentials().get().getPassword());
}
 
Example 11
Source Project: james-project   Source File: GlobalQuotaRoutesTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
void putQuotaWithNegativeCountShouldNotUpdatePreviousQuota() throws Exception {
    maxQuotaManager.setGlobalMaxMessage(QuotaCountLimit.count(42));
    maxQuotaManager.setGlobalMaxStorage(QuotaSizeLimit.size(43));

    given()
        .body("{\"count\":-2,\"size\":43}")
        .when()
        .put("/quota")
    .then()
        .statusCode(HttpStatus.BAD_REQUEST_400)
        .contentType(ContentType.JSON);

    assertThat(maxQuotaManager.getGlobalMaxMessage()).contains(QuotaCountLimit.count(42));
    assertThat(maxQuotaManager.getGlobalMaxStorage()).contains(QuotaSizeLimit.size(43));
}
 
Example 12
Source Project: james-project   Source File: DomainsRoutesTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
void putShouldReturnUserErrorWhenNameContainsInvalidUrlEncodedCharacters() {
    Map<String, Object> errors = when()
        .put(DOMAIN + "%GG" + DOMAIN)
    .then()
        .statusCode(HttpStatus.BAD_REQUEST_400)
        .contentType(ContentType.JSON)
        .extract()
        .body()
        .jsonPath()
        .getMap(".");

    assertThat(errors)
        .containsEntry("statusCode", HttpStatus.BAD_REQUEST_400)
        .containsEntry("type", "InvalidArgument")
        .containsEntry("message", "Invalid request for domain creation domain%GGdomain unable to url decode some characters");
}
 
Example 13
Source Project: james-project   Source File: AliasRoutesTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
void putMalformedUserDestinationShouldReturnBadRequest() {
    Map<String, Object> errors = when()
        .put("not-an-address" + SEPARATOR + "sources" + SEPARATOR + BOB_ALIAS)
    .then()
        .statusCode(HttpStatus.BAD_REQUEST_400)
        .contentType(ContentType.JSON)
        .extract()
        .body()
        .jsonPath()
        .getMap(".");

    assertThat(errors)
        .containsEntry("statusCode", HttpStatus.BAD_REQUEST_400)
        .containsEntry("type", "InvalidArgument")
        .containsEntry("message", "The alias is not an email address")
        .containsEntry("details", "Out of data at position 1 in 'not-an-address'");
}
 
Example 14
Source Project: james-project   Source File: EventDeadLettersRoutesTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
void postRedeliverGroupEventsShouldRemoveEventFromDeadLetters() {
    deadLetters.store(groupA, EVENT_1).block();

    String taskId = with()
        .queryParam("action", EVENTS_ACTION)
        .post("/events/deadLetter/groups/" + SERIALIZED_GROUP_A)
        .jsonPath()
        .get("taskId");

    given()
        .basePath(TasksRoutes.BASE)
    .when()
        .get(taskId + "/await")
    .then()
        .body("status", is("completed"))
        .body("additionalInformation.successfulRedeliveriesCount", is(1))
        .body("additionalInformation.failedRedeliveriesCount", is(0))
        .body("additionalInformation.group", is(SERIALIZED_GROUP_A));

    when()
        .get("/events/deadLetter/groups/" + SERIALIZED_GROUP_A + "/" + INSERTION_UUID_1)
    .then()
        .statusCode(HttpStatus.NOT_FOUND_404);
}
 
Example 15
Source Project: james-project   Source File: SieveQuotaRoutes.java    License: Apache License 2.0 6 votes vote down vote up
@GET
@Path(value = ROOT_PATH + "/{" + USER_ID + "}")
@ApiImplicitParams({
        @ApiImplicitParam(required = true, dataType = "string", name = USER_ID, paramType = "path")
})
@ApiResponses(value = {
        @ApiResponse(code = 200, message = "OK", response = Long.class),
        @ApiResponse(code = 204, message = "User sieve quota not set."),
        @ApiResponse(code = 404, message = "The user name does not exist"),
        @ApiResponse(code = 500, message = "Internal server error - Something went bad on the server side.")
})
public void defineGetPerUserSieveQuota(Service service) {
    service.get(USER_SIEVE_QUOTA_PATH, (request, response) -> {
        Username userId = getUsername(request.params(USER_ID));
        try {
            QuotaSizeLimit userQuota = sieveQuotaRepository.getQuota(userId);
            response.status(HttpStatus.OK_200);
            return userQuota.asLong();
        } catch (QuotaNotFoundException e) {
            return Responses.returnNoContent(response);
        }
    }, jsonTransformer);
}
 
Example 16
@Test
public void testHeader() throws Exception {
    mockResponse(HttpStatus.OK_200);

    // @formatter:off
    String result = HttpRequestBuilder.getFrom(URL)
            .withHeader("Authorization", "Bearer sometoken")
            .withHeader("X-Token", "test")
            .getContentAsString();
    // @formatter:on

    assertEquals("Some content", result);

    // verify the headers to be added to the request
    verify(requestMock).header("Authorization", "Bearer sometoken");
    verify(requestMock).header("X-Token", "test");
}
 
Example 17
@Test
void stoppingJamesServerShouldBeUnhealthy(GuiceJamesServer server) {
    Mono<Void> stopMono = Mono.fromRunnable(() -> { });
    try {
        configureRequestSpecification(server);

        stopMono = Mono.fromRunnable(server::stop);
        stopMono
            .publishOn(Schedulers.elastic())
            .subscribeWith(MonoProcessor.create());

        when()
            .get("/healthcheck")
            .then()
            .statusCode(HttpStatus.SERVICE_UNAVAILABLE_503);
    } finally {
        latch.countDown();
        stopMono.block();
    }
}
 
Example 18
Source Project: james-project   Source File: DomainMappingsRoutesTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
void getSpecificDomainMappingShouldReturnDomainMappings() throws RecipientRewriteTableException {
    String domain = "abc.com";
    String aliasDomain = "a.com";
    Mappings mappings = MappingsImpl.fromMappings(Mapping.domain(Domain.of(aliasDomain)));

    when(recipientRewriteTable.getStoredMappings(any())).thenReturn(mappings);

    List<String> body =
        when()
            .get(domain)
        .then()
            .contentType(ContentType.JSON)
            .statusCode(HttpStatus.OK_200)
            .extract()
            .jsonPath()
            .getList(".");

    assertThat(body).contains(aliasDomain);
}
 
Example 19
Source Project: james-project   Source File: UserQuotaRoutes.java    License: Apache License 2.0 6 votes vote down vote up
@PUT
@Path("/size")
@ApiOperation(value = "Updating per user mail size limitation")
@ApiImplicitParams({
        @ApiImplicitParam(required = true, dataType = "integer", paramType = "body")
})
@ApiResponses(value = {
        @ApiResponse(code = HttpStatus.NO_CONTENT_204, message = "OK. The value has been updated."),
        @ApiResponse(code = HttpStatus.BAD_REQUEST_400, message = "The body is not a positive integer nor -1."),
        @ApiResponse(code = HttpStatus.NOT_FOUND_404, message = "The user name does not exist."),
        @ApiResponse(code = HttpStatus.INTERNAL_SERVER_ERROR_500, message = "Internal server error - Something went bad on the server side.")
})
public void defineUpdateQuotaSize() {
    service.put(SIZE_ENDPOINT, (request, response) -> {
        Username username = checkUserExist(request);
        QuotaSizeLimit quotaSize = Quotas.quotaSize(request.body());
        userQuotaService.defineMaxSizeQuota(username, quotaSize);
        return Responses.returnNoContent(response);
    });
}
 
Example 20
Source Project: baleen   Source File: PipelineManagerServlet.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void delete(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException {
  String[] names = req.getParameterValues(PARAM_NAME);

  if (names == null || names.length == 0) {
    respondWithBadArguments(resp);
    return;
  }

  for (String name : names) {
    manager.remove(name);
  }

  respond(resp, HttpStatus.OK_200);
}
 
Example 21
Source Project: james-project   Source File: DomainQuotaRoutesTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
void getCountShouldReturnStoredValue() throws Exception {
    int value = 42;
    maxQuotaManager.setDomainMaxMessage(FOUND_LOCAL, QuotaCountLimit.count(value));

    Long actual =
        given()
            .get(QUOTA_DOMAINS + "/" + FOUND_LOCAL.name() + "/" + COUNT)
        .then()
            .statusCode(HttpStatus.OK_200)
            .contentType(ContentType.JSON)
            .extract()
            .as(Long.class);

    assertThat(actual).isEqualTo(value);
}
 
Example 22
Source Project: james-project   Source File: SieveScriptRoutesTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
void defineAddActiveSieveScriptSetActiveTrueWhenAddActivateParamTrue() throws Exception {
    given()
        .pathParam("userName", "userA")
        .pathParam("scriptName", "scriptA")
        .queryParam("activate", true)
        .body(sieveContent)
    .when()
        .put("sieve/{userName}/scripts/{scriptName}")
    .then()
        .statusCode(HttpStatus.NO_CONTENT_204);

    assertThat(getScriptContent(sieveRepository
        .getActive(Username.of("userA"))))
        .isEqualTo(new ScriptContent(sieveContent));
}
 
Example 23
Source Project: james-project   Source File: UserQuotaRoutesTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
void putQuotaShouldRemoveCount(WebAdminQuotaSearchTestSystem testSystem) throws Exception {
    MaxQuotaManager maxQuotaManager = testSystem.getQuotaSearchTestSystem().getMaxQuotaManager();
    UserQuotaRootResolver userQuotaRootResolver = testSystem.getQuotaSearchTestSystem().getQuotaRootResolver();

    maxQuotaManager.setMaxMessage(userQuotaRootResolver.forUser(BOB), QuotaCountLimit.count(52));

    with()
        .body("{\"count\":null,\"size\":42}")
        .put(QUOTA_USERS + "/" + BOB.asString())
    .then()
        .statusCode(HttpStatus.NO_CONTENT_204);

    SoftAssertions softly = new SoftAssertions();
    softly.assertThat(maxQuotaManager.getMaxMessage(userQuotaRootResolver.forUser(BOB)))
        .isEmpty();
    softly.assertThat(maxQuotaManager.getMaxStorage(userQuotaRootResolver.forUser(BOB)))
        .contains(QuotaSizeLimit.size(42));
    softly.assertAll();
}
 
Example 24
Source Project: james-project   Source File: DomainQuotaRoutesTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
void putCountShouldRejectNegativeOtherThanMinusOne() {
    Map<String, Object> errors = given()
        .body("-2")
        .put(QUOTA_DOMAINS + "/" + FOUND_LOCAL.name() + "/" + COUNT)
    .then()
        .statusCode(HttpStatus.BAD_REQUEST_400)
        .contentType(ContentType.JSON)
        .extract()
        .body()
        .jsonPath()
        .getMap(".");

    assertThat(errors)
        .containsEntry("statusCode", HttpStatus.BAD_REQUEST_400)
        .containsEntry("type", "InvalidArgument")
        .containsEntry("message", "Invalid quota. Need to be an integer value greater or equal to -1");
}
 
Example 25
Source Project: james-project   Source File: DomainMappingsRoutesTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
void getDomainMappingsShouldFilterNonDomainMappings() throws RecipientRewriteTableException {
    MappingSource mappingSource = MappingSource.fromDomain(Domain.of("abc.com"));
    String address = "[email protected]";

    recipientRewriteTable.addAddressMapping(mappingSource, address);
    recipientRewriteTable.addForwardMapping(mappingSource, address);
    recipientRewriteTable.addErrorMapping(mappingSource, address);
    recipientRewriteTable.addGroupMapping(mappingSource, address);
    recipientRewriteTable.addRegexMapping(mappingSource, address);

    when()
        .get()
    .then()
        .contentType(ContentType.JSON)
        .statusCode(HttpStatus.OK_200)
        .body(is("{}"));
}
 
Example 26
@Test
void healthCheckShouldReturn200WhenCalledRepeatedly() {
    given().get(HealthCheckRoutes.HEALTHCHECK);
    given().get(HealthCheckRoutes.HEALTHCHECK);
    given().get(HealthCheckRoutes.HEALTHCHECK);
    given().get(HealthCheckRoutes.HEALTHCHECK);
    given().get(HealthCheckRoutes.HEALTHCHECK);

    when()
        .get(HealthCheckRoutes.HEALTHCHECK)
    .then()
        .statusCode(HttpStatus.OK_200);
}
 
Example 27
Source Project: james-project   Source File: SieveQuotaRoutes.java    License: Apache License 2.0 5 votes vote down vote up
private Username getUsername(String usernameParameter) throws UsersRepositoryException {
    Username username = Username.of(usernameParameter);
    if (!usersRepository.contains(username)) {
        throw ErrorResponder.builder()
            .statusCode(HttpStatus.NOT_FOUND_404)
            .type(ErrorResponder.ErrorType.INVALID_ARGUMENT)
            .message("User %s does not exist", username)
            .haltError();
    }
    return username;
}
 
Example 28
Source Project: james-project   Source File: SieveQuotaRoutesTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
void removePerUserSieveQuotaShouldRemoveQuotaForUser() throws Exception {
    sieveRepository.setQuota(USERNAME_A, QuotaSizeLimit.size(1024));

    given()
        .delete("/sieve/quota/users/" + USER_NAME_A)
    .then()
        .statusCode(HttpStatus.NO_CONTENT_204);
}
 
Example 29
Source Project: james-project   Source File: UserQuotaRoutesTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
void getCountShouldReturnNoContentByDefault() {
    given()
        .get(QUOTA_USERS + "/" + BOB.asString() + "/" + COUNT)
    .then()
        .statusCode(HttpStatus.NO_CONTENT_204);
}
 
Example 30
Source Project: james-project   Source File: UserQuotaRoutesTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
void putCountShouldSetToInfiniteWhenMinusOne(WebAdminQuotaSearchTestSystem testSystem) throws Exception {
    MaxQuotaManager maxQuotaManager = testSystem.getQuotaSearchTestSystem().getMaxQuotaManager();
    UserQuotaRootResolver userQuotaRootResolver = testSystem.getQuotaSearchTestSystem().getQuotaRootResolver();

    with()
        .body("-1")
        .put(QUOTA_USERS + "/" + BOB.asString() + "/" + COUNT)
    .then()
        .statusCode(HttpStatus.NO_CONTENT_204);

    assertThat(maxQuotaManager.getMaxMessage(userQuotaRootResolver.forUser(BOB))).contains(QuotaCountLimit.unlimited());
}