/** * Given a list of acceptable media types, get an RDF syntax. * * @param acceptableTypes the types from HTTP headers * @param mimeType an additional "default" mimeType to match * @return an RDFSyntax */ public static Optional<RDFSyntax> getSyntax(final List<MediaType> acceptableTypes, final Optional<String> mimeType) { if (acceptableTypes.isEmpty()) { // TODO -- JDK9 refactor with Optional::or if (mimeType.isPresent()) { return empty(); } return of(TURTLE); } final Optional<MediaType> mt = mimeType.map(MediaType::valueOf); for (final MediaType type : acceptableTypes) { if (mt.filter(type::isCompatible).isPresent()) { return empty(); } final Optional<RDFSyntax> syntax = MEDIA_TYPES.stream().filter(type::isCompatible) .findFirst().map(MediaType::toString).flatMap(RDFSyntax::byMediaType); if (syntax.isPresent()) { return syntax; } } LOGGER.debug("Valid syntax not found among {} or {}", acceptableTypes, mimeType); throw new NotAcceptableException(); }
@Test public void testCreateException() { assertExceptionType(Response.Status.INTERNAL_SERVER_ERROR, InternalServerErrorException.class); assertExceptionType(Response.Status.NOT_FOUND, NotFoundException.class); assertExceptionType(Response.Status.FORBIDDEN, ForbiddenException.class); assertExceptionType(Response.Status.BAD_REQUEST, BadRequestException.class); assertExceptionType(Response.Status.METHOD_NOT_ALLOWED, NotAllowedException.class); assertExceptionType(Response.Status.UNAUTHORIZED, NotAuthorizedException.class); assertExceptionType(Response.Status.NOT_ACCEPTABLE, NotAcceptableException.class); assertExceptionType(Response.Status.UNSUPPORTED_MEDIA_TYPE, NotSupportedException.class); assertExceptionType(Response.Status.SERVICE_UNAVAILABLE, ServiceUnavailableException.class); assertExceptionType(Response.Status.TEMPORARY_REDIRECT, RedirectionException.class); assertExceptionType(Response.Status.LENGTH_REQUIRED, ClientErrorException.class); assertExceptionType(Response.Status.BAD_GATEWAY, ServerErrorException.class); assertExceptionType(Response.Status.NO_CONTENT, WebApplicationException.class); }
/** * {@inheritDoc} */ @Override public Response toResponse(final NotAcceptableException exception) { if (L.isDebugEnabled()) { L.debug(R.getString("D-REST-JERSEY-MAPPER#0005")); } ErrorMessage error = ErrorMessages.create(exception) .code(ErrorCode.NOT_ACCEPTABLE.code()) .resolve() .get(); L.warn(error.log(), exception); return Response.status(exception.getResponse().getStatusInfo()) .entity(error) .type(MediaType.APPLICATION_JSON) .build(); }
@Test public void testNotAcceptableLdprs() { when(mockHeaders.getAcceptableMediaTypes()).thenReturn(singletonList(APPLICATION_JSON_TYPE)); final GetHandler getHandler = new GetHandler(mockLdpRequest, mockResourceService, mockIoService, mockBinaryService, baseUrl); assertThrows(NotAcceptableException.class, () -> getHandler.getRepresentation(mockResource)); }
@Test public void testGetSyntaxError() { final List<MediaType> types = asList( new MediaType("application", "json"), new MediaType("text", "xml")); assertThrows(NotAcceptableException.class, () -> RdfUtils.getSyntax(types, empty())); }
@Test public void exceptionsAreMappedCorrectly() { assertThat(uut.httpRequestTags( event("GET", 500, new IllegalArgumentException(), "/app", (String[]) null))) .isEqualTo(tagsFrom("GET", "/app", 500, "IllegalArgumentException")); assertThat(uut.httpRequestTags(event("GET", 500, new IllegalArgumentException(new NullPointerException()), "/app", (String[]) null))) .isEqualTo(tagsFrom("GET", "/app", 500, "NullPointerException")); assertThat(uut.httpRequestTags( event("GET", 406, new NotAcceptableException(), "/app", (String[]) null))) .isEqualTo(tagsFrom("GET", "/app", 406, "NotAcceptableException")); }
@Test(expected = NotAcceptableException.class) public void testChangePasswordWrongEmail() throws AccountManagerException, PasswordChangeException { Response response = proxy.createAccount(new CreateAccountEntity(EMAIL_ADDRESS, VALID_PASSWORD, "engineer")); assertEquals(HttpStatus.SC_CREATED, response.getStatus()); response.close(); assertTrue(passwordStoreClient.authenticate(new EmailAddress(EMAIL_ADDRESS), new Password(VALID_PASSWORD))); assertFalse(proxy.changePassword(EMAIL_ADDRESS + "Wrong!", new ChangePasswordEntity(VALID_PASSWORD, VALID_PASSWORD + "New!"))); }
@Test(expected = NotAcceptableException.class) public void testChangePasswordTooWeakPassword() throws AccountManagerException, PasswordChangeException { Response response = proxy.createAccount(new CreateAccountEntity(EMAIL_ADDRESS, VALID_PASSWORD, "engineer")); assertEquals(HttpStatus.SC_CREATED, response.getStatus()); response.close(); assertTrue(passwordStoreClient.authenticate(new EmailAddress(EMAIL_ADDRESS), new Password(VALID_PASSWORD))); proxy.changePassword(EMAIL_ADDRESS, new ChangePasswordEntity(VALID_PASSWORD, TOO_WEAK_PASSWORD)); }
@Override public String createPassword(EmailAddress email, Password password) throws PasswordCreationException { try { PasswordCreationEntity passwordCreationEntity = new PasswordCreationEntity( email.getAddress(), password.getPassword()); return proxy.createPassword(passwordCreationEntity); } catch (NotAcceptableException e) { throw new PasswordCreationException("Could not create password.", e); } }
@Override public EmailAddress activatePassword(EmailAddress email, String activationKey) throws PasswordActivationException { try { return proxy.activatePassword(new PasswordActivationEntity(email, activationKey)); } catch (NotAcceptableException e) { throw new PasswordActivationException( "Could not activate password.", e); } }
@Override public boolean changePassword(EmailAddress email, Password oldPassword, Password newPassword) throws PasswordChangeException { try { return proxy.changePassword(new PasswordChangeEntity(email, oldPassword, newPassword)); } catch (NotAcceptableException e) { throw new PasswordChangeException("Could not change password.", e); } }
@Override public Password resetPassword(EmailAddress email) throws PasswordResetException { try { return proxy.resetPassword(email.getAddress()); } catch (NotAcceptableException e) { throw new PasswordResetException("Could not reset password.", e); } }
@Override public String createPassword(PasswordCreationEntity entity) throws PasswordCreationException { try { EmailAddress emailAddress = new EmailAddress(entity.getEmail()); Password password = new Password(entity.getPassword()); return passwordStore.createPassword(emailAddress, password); } catch (IllegalEmailAddressException e) { logger.error("Could not create password.", e); throw new NotAcceptableException("Invalid email address '" + entity.getEmail() + "'."); } }
@Override public boolean changePassword(PasswordChangeEntity entity) throws NotAcceptableException { try { return passwordStore.changePassword(entity.getEmail(), entity.getOldPassword(), entity.getNewPassword()); } catch (PasswordChangeException e) { throw new NotAcceptableException("Could not change password for '" + entity.getEmail() + "'.", e); } }
private static <T> T handleErrorStatus(Response response) { final int status = response.getStatus(); switch (status) { case 400: throw new BadRequestException(response); case 401: throw new NotAuthorizedException(response); case 404: throw new NotFoundException(response); case 405: throw new NotAllowedException(response); case 406: throw new NotAcceptableException(response); case 415: throw new NotSupportedException(response); case 500: throw new InternalServerErrorException(response); case 503: throw new ServiceUnavailableException(response); default: break; } if (status >= 400 && status < 500){ throw new ClientErrorException(response); } else if (status >= 500) { throw new ServerErrorException(response); } throw new WebApplicationException(response); }
private static void validate(Contact c) { if (c.getValidate() != null) { throw new NotAcceptableException(c.getValidate()); } if (c.getAddress().getValidate() != null) { throw new NotAcceptableException(c.getAddress().getValidate()); } for (Phone phone : c.getPhones()) { String err = phone.getValidate(); if (err != null) { throw new javax.ws.rs.NotAcceptableException(err); } } }
@Override @Transactional public void save(String template, String service, KeyValue apiObject) { RESTAssert.assertNotEmpty(template); RESTAssert.assertNotEmpty(service); RESTAssert.assertNotEmpty(apiObject.getKey()); if (ReservedConfigKeyStore.instance.isReserved(apiObject.getKey())) { throw new NotAcceptableException(); } EConfigValue ecv = null; if (!template.equalsIgnoreCase(ConfigValueImpl.RESERVED_GLOBAL)) { ecv = this.dcv.findBy(template, service, apiObject.getKey()); } else { ecv = this.dcv.findGlobal(service, apiObject.getKey()); } if (ecv == null) { ecv = new EConfigValue(); if (template.equalsIgnoreCase(ConfigValueImpl.RESERVED_GLOBAL)) { ecv.setTemplate(ConfigValueImpl.RESERVED_GLOBAL); } else { ecv.setTemplate(template); } ecv.setService(service); ecv.setConfigkey(apiObject.getKey()); } ecv.setValue(apiObject.getValue().toString()); this.dcv.save(ecv); }
@Override @Transactional public void save(String template, KeyValue apiObject) { RESTAssert.assertNotEmpty(template); RESTAssert.assertNotEmpty(apiObject.getKey()); if (ReservedConfigKeyStore.instance.isReserved(apiObject.getKey())) { throw new NotAcceptableException(); } EConfigValue ecv = null; if (!template.equalsIgnoreCase(ConfigValueImpl.RESERVED_GLOBAL)) { ecv = this.dcv.findKey(template, apiObject.getKey()); } else { ecv = this.dcv.findKey(apiObject.getKey()); } if (ecv == null) { ecv = new EConfigValue(); if (template.equalsIgnoreCase(ConfigValueImpl.RESERVED_GLOBAL)) { ecv.setTemplate(ConfigValueImpl.RESERVED_GLOBAL); } else { ecv.setTemplate(template); } ecv.setService(null); ecv.setConfigkey(apiObject.getKey()); } ecv.setValue(apiObject.getValue().toString()); this.dcv.save(ecv); }
@Override protected ApiErrorResponse toApiErrorResponse(NotAcceptableException exception) { return new ApiErrorResponse( "The requested media type is not available.", getCode(), getLocationType(), "Accept" ); }
@Test public void plaintext_request_not_acceptable() throws Exception { try { RestTest .target(getPort(), String.format("whois/autocomplete?query=%s&field=%s", "query", "nic-hdl")) .request(MediaType.TEXT_PLAIN_TYPE) .get(String.class); fail(); } catch (NotAcceptableException e) { // expected } }
@Override public APIError convert(NotAcceptableException exception) { return super.convert(exception); }
@Test(expected = NotAcceptableException.class) public void testResetPasswordWrongEmail() throws PasswordResetException { proxy.resetPassword(EMAIL_ADDRESS); }
@Override public Response toResponse(NotAcceptableException exception) { return ExceptionMapperUtils.buildResponse(exception, Response.Status.NOT_ACCEPTABLE); }
@GET public EmptyTest exception() { throw new NotAcceptableException(); }