Java 类javax.ws.rs.NotFoundException 实例源码
项目:message-broker
文件:QueuesApiDelegate.java
public Response deleteQueue(String queueName, Boolean ifUnused, Boolean ifEmpty) {
if (Objects.isNull(ifUnused)) {
ifUnused = true;
}
if (Objects.isNull(ifEmpty)) {
ifEmpty = true;
}
try {
if (broker.deleteQueue(queueName, ifUnused, ifEmpty)) {
return Response.ok().build();
} else {
throw new NotFoundException("Queue " + queueName + " doesn't exist.");
}
} catch (BrokerException e) {
throw new BadRequestException(e.getMessage(), e);
}
}
项目:trellis
文件:MultipartUploader.java
/**
* Add a segment of a binary.
*
* <p>Note: the response will be a json structure, such as:</p>
* <pre>{
* "digest": "a-hash"
* }</pre>
*
* @param id the upload session identifier
* @param partNumber the part number
* @param part the input stream
* @return a response
*/
@PUT
@Timed
@Path("{partNumber}")
@Produces("application/json")
public String uploadPart(@PathParam("id") final String id,
@PathParam("partNumber") final Integer partNumber,
final InputStream part) {
final JsonObjectBuilder builder = Json.createObjectBuilder();
if (!binaryService.uploadSessionExists(id)) {
throw new NotFoundException();
}
final String digest = binaryService.uploadPart(id, partNumber, part);
return builder.add("digest", digest).build().toString();
}
项目:act-platform
文件:NotFoundMapper.java
@Override
public Response toResponse(NotFoundException ex) {
if (ex.getCause() instanceof IllegalArgumentException) {
// If a URL parameter cannot be decoded (e.g. an invalid UUID) an IllegalArgumentException will be wrapped inside
// a NotFoundException. But a 412 should be returned in this case.
return ResultStash.builder()
.setStatus(Response.Status.PRECONDITION_FAILED)
.addActionError("Invalid URL parameter detected.", "invalid.url.parameter")
.buildResponse();
}
return ResultStash.builder()
.setStatus(Response.Status.NOT_FOUND)
.addActionError("Requested URL does not exist.", "url.not.exist")
.buildResponse();
}
项目:lra-service
文件:Coordinator.java
@GET
@Path("{LraId}")
@Produces(MediaType.TEXT_PLAIN)
@ApiOperation(value = "Obtain the status of an LRA as a string",
response = String.class)
@ApiResponses( {
@ApiResponse( code = 404, message =
"The coordinator has no knowledge of this LRA" ),
@ApiResponse( code = 204, message =
"The LRA exists and has not yet been asked to close or cancel "
+ " - compare this response with a 200 response.s"),
@ApiResponse( code = 200, message =
"The LRA exists. The status is reported in the content body.")
} )
public Response getLRAStatus(
@ApiParam( value = "The unique identifier of the LRA", required = true )
@PathParam("LraId")String lraId) throws NotFoundException {
CompensatorStatus status = lraService.getTransaction(toURL(lraId)).getLRAStatus();
if (status == null)
return Response.noContent().build(); // 204 means the LRA is still active
return Response.ok(status.name()).build();
}
项目:lra-service
文件:Coordinator.java
@PUT
@Path("{LraId}/renew")
@ApiOperation(value = "Update the TimeLimit for an existing LRA",
notes = "LRAs can be automatically cancelled if they aren't closed or cancelled before the TimeLimit\n"
+ "specified at creation time is reached.\n"
+ "The time limit can be updated.\n")
@ApiResponses({
@ApiResponse( code = 200, message = "If the LRA timelimit has been updated" ),
@ApiResponse( code = 404, message = "The coordinator has no knowledge of this LRA" ),
@ApiResponse( code = 412, message = "The LRA is not longer active (ie in the complete or compensate messages have been sent" )
} )
public Response renewTimeLimit(
@ApiParam( value = "The new time limit for the LRA", required = true )
@QueryParam(TIMELIMIT_PARAM_NAME) @DefaultValue("0") Long timelimit,
@PathParam("LraId")String lraId) throws NotFoundException {
return Response.status(lraService.renewTimeLimit(toURL(lraId), timelimit)).build();
}
项目:lra-service
文件:Coordinator.java
@PUT
@Path("{LraId}/close")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Attempt to close an LRA",
notes = "Trigger the successful completion of the LRA. All"
+" compensators will be dropped by the coordinator."
+" The complete message will be sent to the compensators."
+" Upon termination, the URL is implicitly deleted."
+" The invoker cannot know for sure whether the lra completed or compensated without enlisting a participant.",
response = Boolean.class)
@ApiResponses( {
@ApiResponse( code = 404, message = "The coordinator has no knowledge of this LRA" ),
@ApiResponse( code = 200, message = "The complete message was sent to all coordinators" )
} )
public Response closeLRA(
@ApiParam( value = "The unique identifier of the LRA", required = true )
@PathParam("LraId")String txId) throws NotFoundException {
return endLRA(toURL(txId), false, false);
}
项目:lra-service
文件:Coordinator.java
@PUT
@Path("{LraId}/cancel")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Attempt to cancel an LRA",
notes = " Trigger the compensation of the LRA. All"
+ " compensators will be triggered by the coordinator (ie the compensate message will be sent to each compensators)."
+ " Upon termination, the URL is implicitly deleted."
+ " The invoker cannot know for sure whether the lra completed or compensated without enlisting a participant.",
response = Boolean.class)
@ApiResponses( {
@ApiResponse( code = 404, message = "The coordinator has no knowledge of this LRA" ),
@ApiResponse( code = 200, message = "The compensate message was sent to all coordinators" )
} )
public Response cancelLRA(
@ApiParam( value = "The unique identifier of the LRA", required = true )
@PathParam("LraId")String lraId) throws NotFoundException {
return endLRA(toURL(lraId), true, false);
}
项目:com-liferay-apio-architect
文件:RootEndpointImpl.java
private <T> Try<NestedCollectionRoutes<T>> _getNestedCollectionRoutesTry(
String name, String nestedName) {
Try<Optional<NestedCollectionRoutes<T>>> optionalTry = Try.success(
_nestedCollectionRouterManager.getNestedCollectionRoutesOptional(
name, nestedName));
return optionalTry.map(
Optional::get
).recoverWith(
__ -> _getReusableNestedCollectionRoutesTry(nestedName)
).mapFailMatching(
NoSuchElementException.class,
() -> new NotFoundException("No resource found for path " + name)
);
}
项目:lra-service
文件:Coordinator.java
private Response joinLRA(URL lraId, long timeLimit, String compensatorUrl, String linkHeader, String userData)
throws NotFoundException {
final String recoveryUrlBase = String.format("http://%s/%s/",
context.getRequestUri().getAuthority(), NarayanaLRAClient.RECOVERY_COORDINATOR_PATH_NAME);
StringBuilder recoveryUrl = new StringBuilder();
int status = lraService.joinLRA(recoveryUrl, lraId, timeLimit, compensatorUrl, linkHeader, recoveryUrlBase, userData);
try {
return Response.status(status)
.entity(recoveryUrl)
.location(new URI(recoveryUrl.toString()))
.header(LRA_HTTP_RECOVERY_HEADER, recoveryUrl)
.build();
} catch (URISyntaxException e) {
LRALogger.i18NLogger.error_invalidRecoveryUrlToJoinLRA(recoveryUrl.toString(), lraId);
throw new GenericLRAException(lraId, Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), "Invalid recovery URL", e);
}
}
项目:minijax
文件:MinijaxApplication.java
public Response handle(final MinijaxRequestContext context) {
final MinijaxResourceMethod rm = findRoute(context.getMethod(), (MinijaxUriInfo) context.getUriInfo());
if (rm == null) {
return toResponse(context, new NotFoundException());
}
context.setResourceMethod(rm);
try {
if (securityContextClass != null) {
context.setSecurityContext(get(securityContextClass));
}
runRequestFilters(context);
checkSecurity(context);
final Response response = toResponse(rm, rm.invoke(context));
runResponseFilters(context, response);
return response;
} catch (final Exception ex) {
LOG.debug(ex.getMessage(), ex);
return toResponse(context, ex);
}
}
项目:athena
文件:PortChainResourceTest.java
/**
* Tests that a fetch of a non-existent port chain object throws an exception.
*/
@Test
public void testBadGet() {
expect(portChainService.getPortChain(anyObject()))
.andReturn(null).anyTimes();
replay(portChainService);
WebTarget wt = target();
try {
wt.path("port_chains/78dcd363-fc23-aeb6-f44b-56dc5aafb3ae")
.request().get(String.class);
fail("Fetch of non-existent port chain did not throw an exception");
} catch (NotFoundException ex) {
assertThat(ex.getMessage(),
containsString("HTTP 404 Not Found"));
}
}
项目:verify-matching-service-adapter
文件:ExceptionExceptionMapper.java
@Override
public Response toResponse(Exception exception) {
if (exception instanceof NotFoundException) {
return Response.status(Response.Status.NOT_FOUND).build();
}
UUID eventId = UUID.randomUUID();
LOG.error(MessageFormat.format("{0} - Exception while processing request.", eventId), exception);
StringBuilder sb = new StringBuilder();
sb.append(exception.getClass().getName());
if (configuration.getReturnStackTraceInResponse()) {
sb.append(" : ");
sb.append(exception.getMessage());
sb.append("\n");
for (StackTraceElement element : exception.getStackTrace()) {
sb.append("! ");
sb.append(element.toString());
sb.append("\n");
}
}
return Response.serverError().entity(sb.toString()).build();
}
项目:athena
文件:IntentsResourceTest.java
/**
* Tests that a fetch of a non-existent intent object throws an exception.
*/
@Test
public void testBadGet() {
expect(mockIntentService.getIntent(Key.of(0, APP_ID)))
.andReturn(null)
.anyTimes();
replay(mockIntentService);
WebTarget wt = target();
try {
wt.path("intents/0").request().get(String.class);
fail("Fetch of non-existent intent did not throw an exception");
} catch (NotFoundException ex) {
assertThat(ex.getMessage(),
containsString("HTTP 404 Not Found"));
}
}
项目:athena
文件:FlowsResourceTest.java
/**
* Tests that a fetch of a non-existent device object throws an exception.
*/
@Test
public void testBadGet() {
expect(mockFlowService.getFlowEntries(anyObject()))
.andReturn(null).anyTimes();
replay(mockFlowService);
replay(mockDeviceService);
WebTarget wt = target();
try {
wt.path("flows/0").request().get(String.class);
fail("Fetch of non-existent device did not throw an exception");
} catch (NotFoundException ex) {
assertThat(ex.getMessage(),
containsString("HTTP 404 Not Found"));
}
}
项目:athena
文件:PortPairGroupResourceTest.java
/**
* Tests that a fetch of a non-existent port pair group object throws an exception.
*/
@Test
public void testBadGet() {
expect(portPairGroupService.getPortPairGroup(anyObject()))
.andReturn(null).anyTimes();
replay(portPairGroupService);
WebTarget wt = target();
try {
wt.path("port_pair_groups/78dcd363-fc23-aeb6-f44b-56dc5aafb3ae")
.request().get(String.class);
fail("Fetch of non-existent port pair group did not throw an exception");
} catch (NotFoundException ex) {
assertThat(ex.getMessage(),
containsString("HTTP 404 Not Found"));
}
}
项目:athena
文件:DeviceKeyWebResourceTest.java
/**
* Tests that a DELETE of a non-existent device key throws an exception.
*/
@Test
public void testDeleteNonExistentDeviceKey() {
expect(mockDeviceKeyService.getDeviceKey(anyObject()))
.andReturn(null)
.anyTimes();
expectLastCall();
replay(mockDeviceKeyService);
replay(mockDeviceKeyAdminService);
WebTarget wt = target();
try {
wt.path("keys/" + "NON_EXISTENT_DEVICE_KEY").request()
.delete(String.class);
fail("Delete of a non-existent device key did not throw an exception");
} catch (NotFoundException ex) {
assertThat(ex.getMessage(), containsString("HTTP 404 Not Found"));
}
verify(mockDeviceKeyService);
verify(mockDeviceKeyAdminService);
}
项目:com-liferay-apio-architect
文件:WebPageElementNestedCollectionResource.java
private Optional<User> _getUserOptional(JournalArticle journalArticle) {
try {
return Optional.ofNullable(
_userService.getUserById(journalArticle.getUserId()));
}
catch (NoSuchUserException | PrincipalException e) {
throw new NotFoundException(
"Unable to get user " + journalArticle.getUserId(), e);
}
catch (PortalException pe) {
throw new ServerErrorException(500, pe);
}
}
项目:InComb
文件:NewsRecordService.java
/**
* Returns the {@link News} with the given id.
* @param id the content id of the {@link News}.
* @param userId the {@link User} which wants to see the {@link News}.
* @param con the {@link Connection} to get the {@link News}.
* @return {@link News}
* @throws NotFoundException if {@link News} doesn't exists.
*/
@GET
public Response getNews(@PathParam("id") final long id, @QueryParam("userId") final long userId,
@Context final Connection con) {
final News news = new NewsDao(con).getNews(id);
if(news == null) {
throw new NotFoundException("News with id " + id + " not found.");
}
return ok(new NewsModel(news, userId, con));
}
项目:trellis
文件:MultipartUploader.java
/**
* Get a list of the uploads.
*
* <p>Note: the response structure will be like this:</p>
* <pre>{
* "1": "somehash",
* "2": "otherhash",
* "3": "anotherhash"
* }</pre>
*
* @param id the upload id
* @return a response
*/
@GET
@Timed
@Produces("application/json")
public String listUploads(@PathParam("id") final String id) {
final JsonObjectBuilder builder = Json.createObjectBuilder();
if (!binaryService.uploadSessionExists(id)) {
throw new NotFoundException();
}
binaryService.listParts(id).forEach(x -> builder.add(x.getKey().toString(), x.getValue()));
return builder.build().toString();
}
项目:trellis
文件:MultipartUploader.java
/**
* Abort an upload process.
*
* @param id the upload identifier
*/
@DELETE
@Timed
public void abortUpload(@PathParam("id") final String id) {
if (!binaryService.uploadSessionExists(id)) {
throw new NotFoundException();
}
binaryService.abortUpload(id);
}
项目:verify-hub
文件:PolicyExceptionMapper.java
@Override
public final Response toResponse(TException exception) {
if (exception instanceof NotFoundException) {
return Response.status(Response.Status.NOT_FOUND).build();
} else if (noSessionIdInQueryStringOrPathParam() && inARequestWhereWeExpectContext()) {
LOG.error(MessageFormat.format("No Session Id found for request to: {0}", httpServletRequest.getRequestURI()), exception);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
}
return handleException(exception);
}
项目:micrometer
文件:MetricsRequestEventListener.java
@Override
public void onEvent(RequestEvent event) {
ContainerRequest containerRequest = event.getContainerRequest();
Set<Timed> timedAnnotations;
switch (event.getType()) {
case ON_EXCEPTION:
if(!(event.getException() instanceof NotFoundException)) {
break;
}
case REQUEST_MATCHED:
timedAnnotations = annotations(event);
timedAnnotationsOnRequest.put(containerRequest, timedAnnotations);
shortTaskSample.put(containerRequest, Timer.start(registry));
List<LongTaskTimer.Sample> longTaskSamples = longTaskTimers(timedAnnotations, event).stream().map(LongTaskTimer::start).collect(Collectors.toList());
if (!longTaskSamples.isEmpty()) {
this.longTaskSamples.put(containerRequest, longTaskSamples);
}
break;
case FINISHED:
timedAnnotations = timedAnnotationsOnRequest.remove(containerRequest);
Timer.Sample shortSample = shortTaskSample.remove(containerRequest);
if (shortSample != null) {
for (Timer timer : shortTimers(timedAnnotations, event)) {
shortSample.stop(timer);
}
}
Collection<LongTaskTimer.Sample> longSamples = this.longTaskSamples.remove(containerRequest);
if (longSamples != null) {
for (LongTaskTimer.Sample longSample : longSamples) {
longSample.stop();
}
}
break;
}
}
项目:coddy
文件:NotFoundMapper.java
@Override
public Response toResponse(NotFoundException e) {
return Response.status(Response.Status.NOT_FOUND)
.entity(new org.crunchytorch.coddy.application.data.Response(org.crunchytorch.coddy.application.data.Response.PAGE_NOT_FOUND))
.type(MediaType.APPLICATION_JSON)
.build();
}
项目:message-broker
文件:ResourceNotFoundMapper.java
@Override public Response toResponse(NotFoundException exception) {
LOGGER.debug("Resource not found.", exception);
Map<String, Object> errorResponse = new HashMap<>();
errorResponse.put("message", exception.getMessage());
return Response.status(Response.Status.NOT_FOUND)
.entity(errorResponse)
.type(MediaType.APPLICATION_JSON_TYPE)
.build();
}
项目:message-broker
文件:QueuesApiDelegate.java
public Response getQueue(String queueName) {
QueueHandler queueHandler = broker.getQueue(queueName);
if (Objects.isNull(queueHandler)) {
throw new NotFoundException("Queue " + queueName + " not found");
}
QueueMetadata queueMetadata = toQueueMetadata(queueHandler);
return Response.ok().entity(queueMetadata).build();
}
项目:message-broker
文件:QueuesApiDelegate.java
public Response getAllConsumers(String queueName) {
QueueHandler queueHandler = broker.getQueue(queueName);
if (Objects.isNull(queueHandler)) {
throw new NotFoundException("Unknown queue Name " + queueName);
}
Collection<Consumer> consumers = queueHandler.getConsumers();
List<ConsumerMetadata> consumerMetadataList = new ArrayList<>(consumers.size());
for (Consumer consumer : consumers) {
consumerMetadataList.add(toConsumerMetadata(consumer));
}
return Response.ok().entity(consumerMetadataList).build();
}
项目:com-liferay-apio-architect
文件:BlogPostingNestedCollectionResource.java
private BlogsEntry _getBlogsEntry(Long blogsEntryId) {
try {
return _blogsService.getEntry(blogsEntryId);
}
catch (NoSuchEntryException | PrincipalException e) {
throw new NotFoundException(
"Unable to get blogs entry " + blogsEntryId, e);
}
catch (PortalException pe) {
throw new ServerErrorException(500, pe);
}
}
项目:docker-java-multistage
文件:PersonDatabase.java
public Person getPerson(int id) {
if (id < persons.size()) {
return persons.get(id);
}
throw new NotFoundException("Person with id \"" + id + "\" not found.");
}
项目:com-liferay-apio-architect
文件:BlogPostingCollectionResource.java
private BlogPosting _updateBlogPosting(
Long blogPostingId, BlogPostingForm blogPostingForm) {
Optional<BlogPosting> optional = BlogPosting.updateBlogPosting(
blogPostingId, blogPostingForm.getArticleBody(),
blogPostingForm.getCreator(),
blogPostingForm.getAlternativeHeadline(),
blogPostingForm.getHeadline());
return optional.orElseThrow(
() -> new NotFoundException(
"Unable to get blog posting " + blogPostingId));
}
项目:com-liferay-apio-architect
文件:PersonCollectionResource.java
private User _getUser(Long userId) {
try {
return _userLocalService.getUserById(userId);
}
catch (NoSuchUserException | PrincipalException e) {
throw new NotFoundException("Unable to get user " + userId, e);
}
catch (PortalException pe) {
throw new ServerErrorException(500, pe);
}
}
项目:lra-service
文件:Coordinator.java
@GET
@Path("/status/{LraId}")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Indicates whether an LRA is active",
response = Boolean.class)
@ApiResponses( {
@ApiResponse( code = 404, message = "The coordinator has no knowledge of this LRA" ),
@ApiResponse( code = 200, message = "If the LRA exists" )
} )
public Boolean isActiveLRA(
@ApiParam( value = "The unique identifier of the LRA", required = true )
@PathParam("LraId")String lraId) throws NotFoundException {
return lraService.getTransaction(toURL(lraId)).isActive();
}
项目:com-liferay-apio-architect
文件:BlogPostingCollectionResource.java
private BlogPosting _getBlogPosting(Long blogPostingId) {
Optional<BlogPosting> optional = BlogPosting.getBlogPosting(
blogPostingId);
return optional.orElseThrow(
() -> new NotFoundException(
"Unable to get blog posting " + blogPostingId));
}
项目:core-config-seed
文件:EdgeXConfigSeedApplication.java
public boolean isConfigInitialized(KeyValueClient kvClient) {
try {
List<String> configList = kvClient.getKeys(globalPrefix);
if (!configList.isEmpty()) {
LOGGER.info("%s exists! The configuration data has been initialized.", globalPrefix);
return true;
}
} catch (NotFoundException e) {
LOGGER.info("%s doesn't exist! Start importing configuration data.", globalPrefix);
}
return false;
}
项目:apm-client
文件:Writer.java
private void send(Collection<Trace> traces) {
try {
apmApi.reportTraces(traces);
} catch (NotFoundException | NotSupportedException cee) {
// 404, 415
if (apmApi instanceof ApmApi0_3) {
log.info("falling back to json");
fallbackTo0_2();
send(traces);
}
} catch (BadRequestException bre) {
log.error("{}: {}", bre.getMessage(), traces);
}
}
项目:app-ms
文件:SwaggerResource.java
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("/{version}")
public Swagger swagger(@PathParam("version") final String version,
@Context final UriInfo uriInfo) {
if (!collator.isPathExists(version)) {
throw new NotFoundException();
}
return collator.getSwagger(version, uriInfo);
}
项目:com-liferay-apio-architect
文件:AggregateRatingPathIdentifierMapper.java
@Override
public AggregateRatingIdentifier map(Path path) {
String id = path.getId();
String[] components = id.split(":");
if (components.length != 2) {
throw new BadRequestException(
id + " should be a string with the form \"name:classPK\"");
}
Optional<Class<Object>> optional =
_modelClassManager.getModelClassOptional(components[0]);
Class<Object> modelClass = optional.orElseThrow(
() -> new NotFoundException(
"No resource found for path " + components[0]));
Try<Long> longTry = Try.fromFallible(
() -> Long.parseLong(components[1]));
Long classPK = longTry.orElseThrow(
() -> new BadRequestException(
"Unable to convert " + id + " to a long class PK"));
return AggregateRatingIdentifier.create(modelClass.getName(), classPK);
}
项目:com-liferay-apio-architect
文件:RootEndpointImpl.java
@Override
public Try<Form> getUpdaterFormTry(String name) {
Try<ItemRoutes<Object>> itemRoutesTry = _getItemRoutesTry(name);
return itemRoutesTry.map(
ItemRoutes::getFormOptional
).map(
Optional::get
).mapFailMatching(
NoSuchElementException.class, NotFoundException::new
);
}
项目:osc-core
文件:NotFoundExceptionMapper.java
@Override
public Response toResponse(NotFoundException e) {
return Response
.status(Response.Status.NOT_FOUND)
.type(getMediaType(headers, MediaType.APPLICATION_JSON_TYPE))
.entity(getErrorCodeDto(e))
.build();
}
项目:dropwizard-pagination
文件:ItemResource.java
public ItemResource(ItemsModel itemsModel, String id) {
this.id = id;
this.itemsModel = itemsModel;
try {
itemModel = itemsModel.getItem(id);
} catch (IndexOutOfBoundsException ex) {
throw new NotFoundException();
}
}
项目:device-bluetooth
文件:ProvisionServiceImpl.java
private DeviceProfile fetchProfile(String deviceProfileName) {
try {
return deviceProfileClient.deviceProfileForName(deviceProfileName);
} catch (NotFoundException nfE) {
return null;
}
}