@Override public Function<HttpResponse, CustomerSignInResult> resultMapper() { return httpResponse -> { if (httpResponse.getStatusCode() == 400) { //TODO this code needs reworking final ErrorResponse errorResponse = resultMapperOf(ErrorResponse.typeReference()).apply(httpResponse); if (errorResponse.getErrors().stream().anyMatch(error -> error.getCode().equals("InvalidCredentials"))) { throw new ErrorResponseException(errorResponse); } else { throw new SphereException(errorResponse.toString()); } } else { return super.resultMapper().apply(httpResponse); } }; }
public static void assertEventually(final Duration maxWaitTime, final Duration waitBeforeRetry, final Runnable block) { final long timeOutAt = System.currentTimeMillis() + maxWaitTime.toMillis(); while (true) { try { block.run(); // the block executed without throwing an exception, return return; } catch (AssertionError | ErrorResponseException e) { if (e instanceof ErrorResponseException && !((ErrorResponseException) e).hasErrorCode("SearchFacetPathNotFound")) { throw e; } if (System.currentTimeMillis() > timeOutAt) { throw e; } } try { Thread.sleep(waitBeforeRetry.toMillis()); } catch (InterruptedException e) { throw new RuntimeException(e); } } }
@Override protected boolean matchesSafely(final ErrorResponseException e) { boolean matches = false; if (!e.getErrors().isEmpty()) { final SphereError firstError = e.getErrors().get(0); try { firstError.as(error); matches = true; } catch (final IllegalArgumentException e1) { matches = false; } } return matches; }
@Test public void order() { withTaxedProduct(client(), product -> { final int itemsLeft = 3; final String sku = getSku(product); client().executeBlocking(InventoryEntryCreateCommand.of(InventoryEntryDraft.of(sku, itemsLeft))); final int itemCountToOrder = 5; final CartDraftDsl draft = CartDraft.of(DefaultCurrencyUnits.EUR) .withCountry(CountryCode.DE) .withInventoryMode(InventoryMode.RESERVE_ON_ORDER) .withShippingAddress(Address.of(CountryCode.DE)) .withLineItems(Collections.singletonList(LineItemDraft.of(product, 1, itemCountToOrder))); final Cart cart = client().executeBlocking(CartCreateCommand.of(draft)); final Throwable throwable = catchThrowable(() -> client().executeBlocking(OrderFromCartCreateCommand.of(cart))); assertThat(throwable).isInstanceOf(ErrorResponseException.class); final ErrorResponseException e = (ErrorResponseException) throwable; assertThat(e.hasErrorCode(OutOfStockError.CODE)); final OutOfStockError outOfStockError = e.getErrors().stream() .filter(err -> err.getCode().equals(OutOfStockError.CODE)) .findFirst().get().as(OutOfStockError.class); assertThat(outOfStockError.getSkus()).containsExactly(sku); assertThat(outOfStockError.getLineItems()).containsExactly(cart.getLineItems().get(0).getId()); }); }
@Test public void requiredValidation() { final FieldDefinition stringFieldDefinition = FieldDefinition.of(StringFieldType.of(), STRING_FIELD_NAME, en("label"), true, TextInputHint.SINGLE_LINE); final String typeKey = randomKey(); final TypeDraft typeDraft = TypeDraftBuilder.of(typeKey, en("name of the custom type"), TYPE_IDS) .description(en("description")) .fieldDefinitions(asList(stringFieldDefinition)) .build(); final Type type = client().executeBlocking(TypeCreateCommand.of(typeDraft)); withCategory(client(), category -> { assertThatThrownBy(() -> client().executeBlocking(CategoryUpdateCommand.of(category, SetCustomType.ofTypeIdAndObjects(type.getId(), Collections.emptyMap())))) .isInstanceOf(ErrorResponseException.class) .matches(e -> { final ErrorResponseException errorResponseException = (ErrorResponseException) e; final String errorCode = RequiredField.CODE; return errorResponseException.hasErrorCode(errorCode) && errorResponseException.getErrors().stream() .filter(err -> err.getCode().equals(errorCode)) .anyMatch(err -> STRING_FIELD_NAME.equals(err.as(RequiredField.class).getField())); }); }); client().executeBlocking(TypeDeleteCommand.of(type)); }
public static ExceptionFactory of() { final ExceptionFactory exceptionFactory = new ExceptionFactory() .when(r -> isServiceNotAvailable(r), r -> new ServiceUnavailableException(extractBody(r))) .whenStatus(401, r -> { final String body = extractBody(r); return body.contains("invalid_token") ? new InvalidTokenException() : new UnauthorizedException(body); }) .whenStatus(500, r -> new InternalServerErrorException(extractBody(r))) .whenStatus(502, r -> new BadGatewayException(extractBody(r))) .whenStatus(503, r -> new ServiceUnavailableException(extractBody(r))) .whenStatus(504, r -> new GatewayTimeoutException(extractBody(r))) .whenStatus(409, r -> new ConcurrentModificationException()) .whenStatus(400, r -> { final ErrorResponse errorResponse = JsonUtils.readObject(ErrorResponse.typeReference(), r.getResponseBody().get()); return new ErrorResponseException(errorResponse); } ) .whenStatus(404, r -> new NotFoundException()) //default .when(response -> true, r -> new SphereException("Can't parse backend response.")); return exceptionFactory; }
@Test public void invalidCurrentPassword() throws Exception { withCustomer(client(), customer -> { final String oldPassword = PASSWORD + randomInt(); final String newPassword = "newSecret"; final Throwable throwable = catchThrowable(() -> client().executeBlocking(CustomerChangePasswordCommand.of(customer, oldPassword, newPassword))); assertThat(throwable).isInstanceOf(ErrorResponseException.class); final ErrorResponseException errorResponseException = (ErrorResponseException) throwable; assertThat(errorResponseException.hasErrorCode(CustomerInvalidCurrentPassword.CODE)).isTrue(); }); }
assertThat(throwable).isInstanceOf(ErrorResponseException.class); final ErrorResponseException e = (ErrorResponseException) throwable; assertThat(e.hasErrorCode(PriceChangedError.CODE)); final PriceChangedError error = e.getErrors().stream() .filter(err -> err.getCode().equals(PriceChangedError.CODE)) .findFirst().get().as(PriceChangedError.class);
@Test public void customerAlreadyRegistered() { withCustomer(client(), customer -> { final String email = customer.getEmail(); final CustomerDraftDsl draft = CustomerDraftBuilder.of(email, "secret") .build(); final CustomerCreateCommand cmd = CustomerCreateCommand.of(draft); final Throwable throwable = catchThrowable(() -> client().executeBlocking(cmd)); assertThat(throwable).isInstanceOf(ErrorResponseException.class); final ErrorResponseException e = (ErrorResponseException) throwable; assertThat(e.getErrors().get(0).getCode()).isEqualTo(DuplicateFieldError.CODE); final DuplicateFieldError error = e.getErrors().get(0).as(DuplicateFieldError.class); assertThat(error.getDuplicateValue()).isEqualToIgnoringCase(email); assertThat(error.getField()).isEqualTo("email"); }); } }
public static ExceptionFactory of() { final ExceptionFactory exceptionFactory = new ExceptionFactory() .when(r -> isServiceNotAvailable(r), r -> new ServiceUnavailableException(extractBody(r))) .whenStatus(401, r -> { final String body = extractBody(r); return body.contains("invalid_token") ? new InvalidTokenException() : new UnauthorizedException(body,401); }) .whenStatus(403, r -> new ForbiddenException(extractBody(r))) .whenStatus(500, r -> new InternalServerErrorException(extractBody(r))) .whenStatus(502, r -> new BadGatewayException(extractBody(r))) .whenStatus(503, r -> new ServiceUnavailableException(extractBody(r))) .whenStatus(504, r -> new GatewayTimeoutException(extractBody(r))) .whenStatus(409, r -> { final ErrorResponse errorResponse = SphereJsonUtils.readObject(r.getResponseBody(), ErrorResponse.typeReference()); return new ConcurrentModificationException(errorResponse); }) .whenStatus(413, r -> new RequestEntityTooLargeException()) .whenStatus(400, r -> { final String body = extractBody(r); if (body.contains("invalid_scope")) { return new InvalidTokenException(); } final ErrorResponse errorResponse = SphereJsonUtils.readObject(r.getResponseBody(), ErrorResponse.typeReference()); return new ErrorResponseException(errorResponse); }) .whenStatus(404, r -> new NotFoundException()) //default .when(response -> true, r -> new SphereException("Can't parse backend response.")); return exceptionFactory; }
@Test public void executionWithInvalidEmail() throws Exception { withCustomer(client(), customer -> { assertThatThrownBy(() -> client().executeBlocking(CustomerSignInCommand.of("notpresent@null.sphere.io", PASSWORD))) .isInstanceOf(ErrorResponseException.class) .matches(e -> ((ErrorResponseException) e).hasErrorCode(CustomerInvalidCredentials.CODE)); }); }
public static ExceptionFactory of() { final ExceptionFactory exceptionFactory = new ExceptionFactory() .when(r -> isServiceNotAvailable(r), r -> new ServiceUnavailableException(extractBody(r))) .whenStatus(401, r -> { final String body = extractBody(r); return body.contains("invalid_token") ? new InvalidTokenException() : new UnauthorizedException(body); }) .whenStatus(500, r -> new InternalServerErrorException(extractBody(r))) .whenStatus(502, r -> new BadGatewayException(extractBody(r))) .whenStatus(503, r -> new ServiceUnavailableException(extractBody(r))) .whenStatus(504, r -> new GatewayTimeoutException(extractBody(r))) .whenStatus(409, r -> new ConcurrentModificationException()) .whenStatus(413, r -> new RequestEntityTooLargeException()) .whenStatus(400, r -> { final ErrorResponse errorResponse = SphereJsonUtils.readObject(r.getResponseBody(), ErrorResponse.typeReference()); return new ErrorResponseException(errorResponse); } ) .whenStatus(404, r -> new NotFoundException()) //default .when(response -> true, r -> new SphereException("Can't parse backend response.")); return exceptionFactory; }
@Test public void updateWithWrongType() throws Exception { final Product product = createProduct(); assertThatThrownBy(() -> client().executeBlocking(ProductUpdateCommand.of(product, SetAttribute.of(1, AttributeDraft.of(LAUNDRY_SYMBOLS_ATTR_NAME, "cold"))))) .isInstanceOf(ErrorResponseException.class) .matches(e -> ((ErrorResponseException)e).hasErrorCode(InvalidField.CODE)); }
public static ExceptionFactory of() { final ExceptionFactory exceptionFactory = new ExceptionFactory() .when(r -> isServiceNotAvailable(r), r -> new ServiceUnavailableException(extractBody(r))) .whenStatus(401, r -> { final String body = extractBody(r); return body.contains("invalid_token") ? new InvalidTokenException() : new UnauthorizedException(body,401); }) .whenStatus(403, r -> new ForbiddenException(extractBody(r))) .whenStatus(500, r -> new InternalServerErrorException(extractBody(r))) .whenStatus(502, r -> new BadGatewayException(extractBody(r))) .whenStatus(503, r -> new ServiceUnavailableException(extractBody(r))) .whenStatus(504, r -> new GatewayTimeoutException(extractBody(r))) .whenStatus(409, r -> { final ErrorResponse errorResponse = SphereJsonUtils.readObject(r.getResponseBody(), ErrorResponse.typeReference()); return new ConcurrentModificationException(errorResponse); }) .whenStatus(413, r -> new RequestEntityTooLargeException()) .whenStatus(400, r -> { final String body = extractBody(r); if (body.contains("invalid_scope")) { return new InvalidTokenException(); } final ErrorResponse errorResponse = SphereJsonUtils.readObject(r.getResponseBody(), ErrorResponse.typeReference()); return new ErrorResponseException(errorResponse); }) .whenStatus(404, r -> new NotFoundException()) //default .when(response -> true, r -> new SphereException("Can't parse backend response.")); return exceptionFactory; }
@Test public void order() { withDiscountCodeOfPredicate("totalPrice > \"800.00 EUR\"", (DiscountCode discountCode) -> withFilledCart(client(), cart -> { final Cart cartWithDiscountCode = client().executeBlocking(CartUpdateCommand.of(cart, AddDiscountCode.of(discountCode))); assertThat(cartWithDiscountCode.getTotalPrice()).isEqualTo(MoneyImpl.of("37.02", EUR)); assertThat(cartWithDiscountCode.getDiscountCodes()).hasSize(1); assertThat(cartWithDiscountCode.getDiscountCodes().get(0).getState()) .as("the discount (code) does not match the cart") .isEqualTo(DOES_NOT_MATCH_CART); final Throwable throwable = catchThrowable(() -> client().executeBlocking(OrderFromCartCreateCommand.of(cartWithDiscountCode))); assertThat(throwable).isInstanceOf(ErrorResponseException.class); final ErrorResponseException e = (ErrorResponseException) throwable; assertThat(e.hasErrorCode(DiscountCodeNonApplicableError.CODE)).isTrue(); })); }
private void demo(final SphereClient client, final String email) { final String wrongPassword = "wrong password"; final CustomerSignInCommand signInCommand = CustomerSignInCommand.of(email, wrongPassword); final CompletionStage<CustomerSignInResult> future = client.execute(signInCommand); future.whenCompleteAsync((signInResult, exception) -> { if (signInResult != null) { println("Signing worked"); } else if (exception instanceof ErrorResponseException) { final ErrorResponseException errorResponseException = (ErrorResponseException) exception; final String code = CustomerInvalidCredentials.CODE; if (errorResponseException.hasErrorCode(code)) { println("customer has invalid credentials"); } } }); }
@Test public void execution() throws Exception { withCustomer(client(), customer -> { final String oldPassword = PASSWORD; final String newPassword = "newSecret"; final Customer updatedCustomer = client().executeBlocking(CustomerChangePasswordCommand.of(customer, oldPassword, newPassword)); assertThat(customer.getPassword()).isNotEqualTo(updatedCustomer.getPassword()); final CustomerSignInResult signInResult = client().executeBlocking(CustomerSignInCommand.of(customer.getEmail(), newPassword)); assertThat(signInResult.getCustomer().hasSameIdAs(updatedCustomer)) .overridingErrorMessage("sign in works with new password") .isTrue(); final Throwable throwable = catchThrowable(() -> client().executeBlocking(CustomerSignInCommand.of(customer.getEmail(), oldPassword))); assertThat(throwable).isInstanceOf(ErrorResponseException.class); final ErrorResponseException errorResponseException = (ErrorResponseException) throwable; assertThat(errorResponseException.hasErrorCode(CustomerInvalidCredentials.CODE)).isTrue(); }); }
@Test public void invalidTypeCausesException() throws Exception { final ProductType productType = fetchProductTypeByName(); final ProductVariantDraft masterVariantDraft = ProductVariantDraftBuilder.of() .plusAttribute(COLOR_ATTR_NAME, 1)//1 is of illegal type and of illegal key .build(); final ProductDraft draft = ProductDraftBuilder .of(productType, en("basic shirt"), randomSlug(), masterVariantDraft) .build(); assertThatThrownBy(() -> client().executeBlocking(ProductCreateCommand.of(draft))) .isInstanceOf(ErrorResponseException.class) .matches(e -> ((ErrorResponseException)e).hasErrorCode(InvalidField.CODE)); }
@Test public void executionDemo() throws Exception { withCustomer(client(), customer -> { final SphereClient client = client(); demo(client, customer.getEmail()); final String oldPassword = PASSWORD; final String newPassword = "newSecret"; final Customer updatedCustomer = client().executeBlocking(CustomerChangePasswordCommand.of(customer, oldPassword, newPassword)); assertThat(customer.getPassword()).isNotEqualTo(updatedCustomer.getPassword()); final CustomerSignInResult signInResult = client().executeBlocking(CustomerSignInCommand.of(customer.getEmail(), newPassword)); assertThat(signInResult.getCustomer().hasSameIdAs(updatedCustomer)) .overridingErrorMessage("sign in works with new password") .isTrue(); try { client().executeBlocking(CustomerSignInCommand.of(customer.getEmail(), oldPassword)); fail(); } catch (final ErrorResponseException e) { assertThat(e.hasErrorCode(CustomerInvalidCredentials.CODE)).isTrue(); } }); }