下面列出了怎么用javax.ws.rs.NotSupportedException的API类实例代码及写法,或者点击链接到github查看源代码。
@GET
@Timed
@Path("{name}/conf")
@Produces(APPLICATION_JSON_WITH_CHARSET)
@RolesAllowed("admin")
public File getConf(@Context GraphManager manager,
@PathParam("name") String name) {
LOG.debug("Get graph configuration by name '{}'", name);
HugeGraph g = graph4admin(manager, name);
HugeConfig config = (HugeConfig) g.configuration();
File file = config.getFile();
if (file == null) {
throw new NotSupportedException("Can't access the api in " +
"a node which started with non local file config.");
}
return file;
}
@Override
public Response toResponse(Exception e) {
WrapperResponseEntity response = null;
if (e instanceof NotFoundException) {
response = new WrapperResponseEntity(ResponseCode.NOT_FOUND);
} else if (e instanceof NotAllowedException) {
response = new WrapperResponseEntity(ResponseCode.FORBIDDEN);
} else if (e instanceof JsonProcessingException) {
response = new WrapperResponseEntity(ResponseCode.ERROR_JSON);
} else if (e instanceof NotSupportedException) {
response = new WrapperResponseEntity(ResponseCode.UNSUPPORTED_MEDIA_TYPE);
} else {
response = excetionWrapper != null ? excetionWrapper.toResponse(e) : null;
if (response == null)
response = new WrapperResponseEntity(ResponseCode.INTERNAL_SERVER_ERROR);
}
return Response.status(response.httpStatus()).type(MediaType.APPLICATION_JSON)
.entity(response).build();
}
@RolesAllowed({"admin", "user"})
@PUT
@Path("/{id}")
public User updateUser(User user, @PathParam("id") String id) throws UserNotFoundException, IOException,
DACUnauthorizedException {
if (Strings.isNullOrEmpty(id)) {
throw new IllegalArgumentException("No user id provided");
}
final com.dremio.service.users.User savedUser = userGroupService.getUser(new UID(id));
if (!securityContext.isUserInRole("admin") && !securityContext.getUserPrincipal().getName().equals(savedUser.getUserName())) {
throw new DACUnauthorizedException(format("User %s is not allowed to update user %s",
securityContext.getUserPrincipal().getName(), savedUser.getUserName()));
}
if (!savedUser.getUserName().equals(user.getName())) {
throw new NotSupportedException("Changing of user name is not supported");
}
final com.dremio.service.users.User userConfig = userGroupService.updateUser(of(user, Optional.of(id)), user.getPassword());
return User.fromUser(userConfig);
}
/**
* Checks if files should be skipped
* @param fs file system abstraction
* @param fileName file name to check
* @return returns true if file already exists and export options are set to skip such files.
* @throws IOException
*/
private boolean skipFile(FileSystem fs, Path fileName)
throws IOException {
if (fs.exists(fileName)) {
switch (writeMode) {
case FAIL_IF_EXISTS:
throw new IOException(String.format("File '%s' already exists", fileName));
case SKIP:
return true;
case OVERWRITE:
return false;
default:
throw new NotSupportedException(String.format("Not supported write mode: %s", writeMode));
}
}
return false;
}
@Override
public Response toResponse(Exception e) {
WrapperResponseEntity response = null;
if (e instanceof NotFoundException) {
response = new WrapperResponseEntity(ResponseCode.NOT_FOUND);
} else if (e instanceof NotAllowedException) {
response = new WrapperResponseEntity(ResponseCode.FORBIDDEN);
} else if (e instanceof JsonProcessingException) {
response = new WrapperResponseEntity(ResponseCode.ERROR_JSON);
} else if (e instanceof NotSupportedException) {
response = new WrapperResponseEntity(ResponseCode.UNSUPPORTED_MEDIA_TYPE);
} else {
response = excetionWrapper != null ? excetionWrapper.toResponse(e) : null;
if(response == null)response = new WrapperResponseEntity(ResponseCode.INTERNAL_SERVER_ERROR);
}
return Response.status(response.httpStatus()).type(MediaType.APPLICATION_JSON).entity(response).build();
}
/**
* {@inheritDoc}
*/
@Override
public Response toResponse(final NotSupportedException exception) {
if (L.isDebugEnabled()) {
L.debug(R.getString("D-REST-JERSEY-MAPPER#0009"));
}
ErrorMessage error = ErrorMessages.create(exception)
.code(ErrorCode.UNSUPPORTED_MEDIA_TYPE.code())
.resolve()
.get();
L.warn(error.log(), exception);
return Response.status(exception.getResponse().getStatusInfo())
.entity(error)
.type(MediaType.APPLICATION_JSON)
.build();
}
public static boolean checkAndParseAction(String action) {
E.checkArgumentNotNull(action, "The action param can't be empty");
if (action.equals(ACTION_APPEND)) {
return true;
} else if (action.equals(ACTION_ELIMINATE)) {
return false;
} else {
throw new NotSupportedException(
String.format("Not support action '%s'", action));
}
}
/**
* Initialze the handler with a Trellis resource.
*
* @param parent the parent resource
* @param resource the Trellis resource
* @return a response builder
*/
public ResponseBuilder initialize(final Resource parent, final Resource resource) {
if (!supportsCreate && MISSING_RESOURCE.equals(resource)) {
// Can't patch non-existent resources
throw new NotFoundException();
} else if (!supportsCreate && DELETED_RESOURCE.equals(resource)) {
// Can't patch non-existent resources
throw new ClientErrorException(GONE);
} else if (updateBody == null) {
throw new BadRequestException("Missing body for update");
} else if (!supportsInteractionModel(LDP.RDFSource)) {
throw new BadRequestException(status(BAD_REQUEST)
.link(UnsupportedInteractionModel.getIRIString(), LDP.constrainedBy.getIRIString())
.entity("Unsupported interaction model provided").type(TEXT_PLAIN_TYPE).build());
} else if (syntax == null) {
// Get the incoming syntax and check that the underlying I/O service supports it
LOGGER.warn("Content-Type: {} not supported", getRequest().getContentType());
throw new NotSupportedException();
}
// Check the cache headers
if (exists(resource)) {
checkCache(resource.getModified(), generateEtag(resource));
setResource(resource);
resource.getContainer().ifPresent(p -> setParent(parent));
} else {
setResource(null);
setParent(parent);
}
return ok();
}
@Override
public void authorizeSchemaMetadata(UserAndGroups userAndGroups, SchemaMetadata schemaMetadata,
AccessType accessType) throws AuthorizationException {
String sGroup = schemaMetadata.getSchemaGroup();
String sName = schemaMetadata.getName();
Authorizer.SchemaMetadataResource schemaMetadataResource = new Authorizer.SchemaMetadataResource(sGroup, sName);
authorize(schemaMetadataResource, accessType, userAndGroups);
if(accessType == AccessType.DELETE) {
throw new NotSupportedException("AccessType.DELETE is not supported for authorizeSchemaMetadata method");
}
}
@Override
public DevfileDto readFrom(
Class<DevfileDto> type,
Type genericType,
Annotation[] annotations,
MediaType mediaType,
MultivaluedMap<String, String> httpHeaders,
InputStream entityStream)
throws IOException, WebApplicationException {
try {
if (mediaType.isCompatible(MediaType.APPLICATION_JSON_TYPE)) {
return asDto(
devfileManager.parseJson(
CharStreams.toString(
new InputStreamReader(entityStream, getCharsetOrUtf8(mediaType)))));
} else if (mediaType.isCompatible(MediaType.valueOf("text/yaml"))
|| mediaType.isCompatible(MediaType.valueOf("text/x-yaml"))) {
return asDto(
devfileManager.parseYaml(
CharStreams.toString(
new InputStreamReader(entityStream, getCharsetOrUtf8(mediaType)))));
}
} catch (DevfileFormatException e) {
throw new BadRequestException(e.getMessage());
}
throw new NotSupportedException("Unknown media type " + mediaType.toString());
}
@Test(
expectedExceptions = NotSupportedException.class,
expectedExceptionsMessageRegExp = "Unknown media type text/plain")
public void shouldThrowErrorOnInvalidMediaType() throws Exception {
devfileEntityProvider.readFrom(
DevfileDto.class,
DevfileDto.class,
null,
MediaType.TEXT_PLAIN_TYPE,
new MultivaluedHashMap<>(),
getClass().getClassLoader().getResourceAsStream("devfile/devfile.json"));
}
/**
* @see DataValueDescriptor#setValueFromResultSet
*
*/
public void setValueFromResultSet(ResultSet resultSet, int colNumber,
boolean isNullable) throws SQLException {
Array array = resultSet.getArray(colNumber);
int type = array.getBaseType();
throw new NotSupportedException("still need to implement " + array + " : " + type);
}
@Override
public void updateOtherDataCenterNodes(DataCenterNodes dataCenterNodes) {
throw new NotSupportedException("Node type SESSION not support function");
}
@Override
public void confirmNodeStatus(String connectId, String ip) {
throw new NotSupportedException("Node type META not support function");
}
@Test
public void whenWebApplicationException_thenUnsupportedMediaType() {
assertThat(mapper.toResponse(new NotSupportedException(Response.status(Status.UNSUPPORTED_MEDIA_TYPE).build()))
.getStatus(), is(Status.UNSUPPORTED_MEDIA_TYPE.getStatusCode()));
}
@Override
public Response toResponse(WebApplicationException exception) {
ServiceError error = newDto(ServiceError.class).withMessage(exception.getMessage());
if (exception instanceof BadRequestException) {
return Response.status(Response.Status.BAD_REQUEST)
.entity(DtoFactory.getInstance().toJson(error))
.type(MediaType.APPLICATION_JSON)
.build();
} else if (exception instanceof ForbiddenException) {
return Response.status(Response.Status.FORBIDDEN)
.entity(DtoFactory.getInstance().toJson(error))
.type(MediaType.APPLICATION_JSON)
.build();
} else if (exception instanceof NotFoundException) {
return Response.status(Response.Status.NOT_FOUND)
.entity(DtoFactory.getInstance().toJson(error))
.type(MediaType.APPLICATION_JSON)
.build();
} else if (exception instanceof NotAuthorizedException) {
return Response.status(Response.Status.UNAUTHORIZED)
.entity(DtoFactory.getInstance().toJson(error))
.type(MediaType.APPLICATION_JSON)
.build();
} else if (exception instanceof NotAcceptableException) {
return Response.status(Status.NOT_ACCEPTABLE)
.entity(DtoFactory.getInstance().toJson(error))
.type(MediaType.APPLICATION_JSON)
.build();
} else if (exception instanceof NotAllowedException) {
return Response.status(Status.METHOD_NOT_ALLOWED)
.entity(DtoFactory.getInstance().toJson(error))
.type(MediaType.APPLICATION_JSON)
.build();
} else if (exception instanceof NotSupportedException) {
return Response.status(Status.UNSUPPORTED_MEDIA_TYPE)
.entity(DtoFactory.getInstance().toJson(error))
.type(MediaType.APPLICATION_JSON)
.build();
} else {
return Response.serverError()
.entity(DtoFactory.getInstance().toJson(error))
.type(MediaType.APPLICATION_JSON)
.build();
}
}
@Override
public Response toResponse(NotSupportedException exception) {
return ExceptionMapperUtils.buildResponse(exception, Response.Status.UNSUPPORTED_MEDIA_TYPE);
}
@GET
public EmptyTest exception() {
throw new NotSupportedException();
}
public int enqueue(JobRequest jd)
{
throw new NotSupportedException();
}
@Override
public int enqueue(String applicationName, String userName)
{
throw new NotSupportedException();
}
@Override
public int getJobProgress(int jobId)
{
throw new NotSupportedException();
}
@Override
public List<InputStream> getJobDeliverablesContent(int jobId)
{
throw new NotSupportedException();
}
@Override
public Response toResponse( NotSupportedException e ) {
logger.error( "Unsupported media type", e );
return toResponse( UNSUPPORTED_MEDIA_TYPE, e );
}
public static NotSupportedException toNotSupportedException(Throwable cause, Response response) {
return new NotSupportedException(checkResponse(response, 415), cause);
}