use of javax.ws.rs.NotFoundException in project graylog2-server by Graylog2.
the class UsersResource method get.
@GET
@Path("{username}")
@ApiOperation(value = "Get user details", notes = "The user's permissions are only included if a user asks for his " + "own account or for users with the necessary permissions to edit permissions.")
@ApiResponses({ @ApiResponse(code = 404, message = "The user could not be found.") })
public UserSummary get(@ApiParam(name = "username", value = "The username to return information for.", required = true) @PathParam("username") String username) {
final User user = userService.load(username);
if (user == null) {
throw new NotFoundException("Couldn't find user " + username);
}
// if the requested username does not match the authenticated user, then we don't return permission information
final boolean allowedToSeePermissions = isPermitted(USERS_PERMISSIONSEDIT, username);
final boolean permissionsAllowed = getSubject().getPrincipal().toString().equals(username) || allowedToSeePermissions;
return toUserResponse(user, permissionsAllowed, Optional.empty());
}
use of javax.ws.rs.NotFoundException in project graylog2-server by Graylog2.
the class UsersResource method savePreferences.
@PUT
@Path("{username}/preferences")
@ApiOperation("Update a user's preferences set.")
@ApiResponses({ @ApiResponse(code = 400, message = "Missing or invalid permission data.") })
@AuditEvent(type = AuditEventTypes.USER_PREFERENCES_UPDATE)
public void savePreferences(@ApiParam(name = "username", value = "The name of the user to modify.", required = true) @PathParam("username") String username, @ApiParam(name = "JSON body", value = "The map of preferences to assign to the user.", required = true) UpdateUserPreferences preferencesRequest) throws ValidationException {
final User user = userService.load(username);
checkPermission(RestPermissions.USERS_EDIT, username);
if (user == null) {
throw new NotFoundException("Couldn't find user " + username);
}
user.setPreferences(preferencesRequest.preferences());
userService.save(user);
}
use of javax.ws.rs.NotFoundException in project graylog2-server by Graylog2.
the class UsersResource method revokeToken.
@DELETE
@RequiresPermissions(RestPermissions.USERS_TOKENREMOVE)
@Path("{username}/tokens/{token}")
@ApiOperation("Removes a token for a user")
@AuditEvent(type = AuditEventTypes.USER_ACCESS_TOKEN_DELETE)
public void revokeToken(@ApiParam(name = "username", required = true) @PathParam("username") String username, @ApiParam(name = "token", required = true) @PathParam("token") String token) {
_tokensCheckAndLoadUser(username);
final AccessToken accessToken = accessTokenService.load(token);
if (accessToken != null) {
accessTokenService.destroy(accessToken);
} else {
throw new NotFoundException("Couldn't find access token for user " + username);
}
}
use of javax.ws.rs.NotFoundException in project ddf by codice.
the class MetacardApplication method init.
@Override
public void init() {
get("/metacardtype", (req, res) -> {
return util.getJson(util.getMetacardTypeMap());
});
get("/metacard/:id", (req, res) -> {
String id = req.params(":id");
return util.metacardToJson(id);
});
get("/metacard/:id/attribute/validation", (req, res) -> {
String id = req.params(":id");
return util.getJson(validator.getValidation(util.getMetacard(id)));
});
get("/metacard/:id/validation", (req, res) -> {
String id = req.params(":id");
return util.getJson(validator.getFullValidation(util.getMetacard(id)));
});
post("/metacards", APPLICATION_JSON, (req, res) -> {
List<String> ids = JsonFactory.create().parser().parseList(String.class, req.body());
List<Metacard> metacards = util.getMetacards(ids, "*").entrySet().stream().map(Map.Entry::getValue).map(Result::getMetacard).collect(Collectors.toList());
return util.metacardsToJson(metacards);
});
delete("/metacards", APPLICATION_JSON, (req, res) -> {
List<String> ids = JsonFactory.create().parser().parseList(String.class, req.body());
DeleteResponse deleteResponse = catalogFramework.delete(new DeleteRequestImpl(new ArrayList<>(ids), Metacard.ID, null));
if (deleteResponse.getProcessingErrors() != null && !deleteResponse.getProcessingErrors().isEmpty()) {
res.status(500);
return ImmutableMap.of("message", "Unable to archive metacards.");
}
return ImmutableMap.of("message", "Successfully archived metacards.");
}, util::getJson);
patch("/metacards", APPLICATION_JSON, (req, res) -> {
List<MetacardChanges> metacardChanges = JsonFactory.createUseJSONDates().parser().parseList(MetacardChanges.class, req.body());
UpdateResponse updateResponse = patchMetacards(metacardChanges);
if (updateResponse.getProcessingErrors() != null && !updateResponse.getProcessingErrors().isEmpty()) {
res.status(500);
return updateResponse.getProcessingErrors();
}
return req.body();
});
put("/validate/attribute/:attribute", TEXT_PLAIN, (req, res) -> {
String attribute = req.params(":attribute");
String value = req.body();
return util.getJson(validator.validateAttribute(attribute, value));
});
get("/history/:id", (req, res) -> {
String id = req.params(":id");
List<Result> queryResponse = getMetacardHistory(id);
if (queryResponse.isEmpty()) {
res.status(204);
return "[]";
}
List<HistoryResponse> response = queryResponse.stream().map(Result::getMetacard).map(mc -> new HistoryResponse(mc.getId(), (String) mc.getAttribute(MetacardVersion.EDITED_BY).getValue(), (Date) mc.getAttribute(MetacardVersion.VERSIONED_ON).getValue())).sorted(Comparator.comparing(HistoryResponse::getVersioned)).collect(Collectors.toList());
return util.getJson(response);
});
get("/history/revert/:id/:revertid", (req, res) -> {
String id = req.params(":id");
String revertId = req.params(":revertid");
Metacard versionMetacard = util.getMetacard(revertId);
List<Result> queryResponse = getMetacardHistory(id);
if (queryResponse == null || queryResponse.isEmpty()) {
throw new NotFoundException("Could not find metacard with id: " + id);
}
Optional<Metacard> contentVersion = queryResponse.stream().map(Result::getMetacard).filter(mc -> getVersionedOnDate(mc).isAfter(getVersionedOnDate(versionMetacard)) || getVersionedOnDate(mc).equals(getVersionedOnDate(versionMetacard))).filter(mc -> CONTENT_ACTIONS.contains(Action.ofMetacard(mc))).filter(mc -> mc.getResourceURI() != null).filter(mc -> ContentItem.CONTENT_SCHEME.equals(mc.getResourceURI().getScheme())).sorted(Comparator.comparing((Metacard mc) -> util.parseToDate(mc.getAttribute(MetacardVersion.VERSIONED_ON).getValue()))).findFirst();
if (!contentVersion.isPresent()) {
/* no content versions, just restore metacard */
revertMetacard(versionMetacard, id, false);
} else {
revertContentandMetacard(contentVersion.get(), versionMetacard, id);
}
return util.metacardToJson(MetacardVersionImpl.toMetacard(versionMetacard, types));
});
get("/associations/:id", (req, res) -> {
String id = req.params(":id");
return util.getJson(associated.getAssociations(id));
});
put("/associations/:id", (req, res) -> {
String id = req.params(":id");
List<Associated.Edge> edges = JsonFactory.create().parser().parseList(Associated.Edge.class, req.body());
associated.putAssociations(id, edges);
return req.body();
});
post("/subscribe/:id", (req, res) -> {
String email = getSubjectEmail();
if (isEmpty(email)) {
throw new NotFoundException("Login to subscribe to workspace.");
}
String id = req.params(":id");
subscriptions.addEmail(id, email);
return ImmutableMap.of("message", String.format("Successfully subscribed to id = %s.", id));
}, util::getJson);
post("/unsubscribe/:id", (req, res) -> {
String email = getSubjectEmail();
if (isEmpty(email)) {
throw new NotFoundException("Login to un-subscribe from workspace.");
}
String id = req.params(":id");
subscriptions.removeEmail(id, email);
return ImmutableMap.of("message", String.format("Successfully un-subscribed to id = %s.", id));
}, util::getJson);
get("/workspaces/:id", (req, res) -> {
String id = req.params(":id");
String email = getSubjectEmail();
Metacard metacard = util.getMetacard(id);
// NOTE: the isEmpty is to guard against users with no email (such as guest).
boolean isSubscribed = !isEmpty(email) && subscriptions.getEmails(metacard.getId()).contains(email);
return ImmutableMap.builder().putAll(transformer.transform(metacard)).put("subscribed", isSubscribed).build();
}, util::getJson);
get("/workspaces", (req, res) -> {
String email = getSubjectEmail();
Map<String, Result> workspaceMetacards = util.getMetacardsByFilter(WorkspaceAttributes.WORKSPACE_TAG);
// NOTE: the isEmpty is to guard against users with no email (such as guest).
Set<String> ids = isEmpty(email) ? Collections.emptySet() : subscriptions.getSubscriptions(email);
return workspaceMetacards.entrySet().stream().map(Map.Entry::getValue).map(Result::getMetacard).map(metacard -> {
boolean isSubscribed = ids.contains(metacard.getId());
try {
return ImmutableMap.builder().putAll(transformer.transform(metacard)).put("subscribed", isSubscribed).build();
} catch (RuntimeException e) {
LOGGER.debug("Could not transform metacard. WARNING: This indicates there is invalid data in the system. Metacard title: '{}', id:'{}'", metacard.getTitle(), metacard.getId(), e);
}
return null;
}).filter(Objects::nonNull).collect(Collectors.toList());
}, util::getJson);
post("/workspaces", APPLICATION_JSON, (req, res) -> {
Map<String, Object> incoming = JsonFactory.create().parser().parseMap(req.body());
Metacard saved = saveMetacard(transformer.transform(incoming));
Map<String, Object> response = transformer.transform(saved);
res.status(201);
return util.getJson(response);
});
put("/workspaces/:id", APPLICATION_JSON, (req, res) -> {
String id = req.params(":id");
Map<String, Object> workspace = JsonFactory.create().parser().parseMap(req.body());
Metacard metacard = transformer.transform(workspace);
metacard.setAttribute(new AttributeImpl(Metacard.ID, id));
Metacard updated = updateMetacard(id, metacard);
return util.getJson(transformer.transform(updated));
});
delete("/workspaces/:id", APPLICATION_JSON, (req, res) -> {
String id = req.params(":id");
catalogFramework.delete(new DeleteRequestImpl(id));
return ImmutableMap.of("message", "Successfully deleted.");
}, util::getJson);
get("/enumerations/metacardtype/:type", APPLICATION_JSON, (req, res) -> {
return util.getJson(enumExtractor.getEnumerations(req.params(":type")));
});
get("/enumerations/attribute/:attribute", APPLICATION_JSON, (req, res) -> {
return util.getJson(enumExtractor.getAttributeEnumerations(req.params(":attribute")));
});
get("/localcatalogid", (req, res) -> {
return String.format("{\"%s\":\"%s\"}", "local-catalog-id", catalogFramework.getId());
});
after((req, res) -> {
res.type(APPLICATION_JSON);
});
exception(IngestException.class, (ex, req, res) -> {
res.status(404);
res.header(CONTENT_TYPE, APPLICATION_JSON);
LOGGER.debug("Failed to ingest metacard", ex);
res.body(util.getJson(ImmutableMap.of("message", UPDATE_ERROR_MESSAGE)));
});
exception(NotFoundException.class, (ex, req, res) -> {
res.status(404);
res.header(CONTENT_TYPE, APPLICATION_JSON);
LOGGER.debug("Failed to find metacard.", ex);
res.body(util.getJson(ImmutableMap.of("message", ex.getMessage())));
});
exception(NumberFormatException.class, (ex, req, res) -> {
res.status(400);
res.header(CONTENT_TYPE, APPLICATION_JSON);
res.body(util.getJson(ImmutableMap.of("message", "Invalid values for numbers")));
});
exception(RuntimeException.class, (ex, req, res) -> {
LOGGER.debug("Exception occured.", ex);
res.status(404);
res.header(CONTENT_TYPE, APPLICATION_JSON);
res.body(util.getJson(ImmutableMap.of("message", "Could not find what you were looking for")));
});
}
use of javax.ws.rs.NotFoundException in project jersey by jersey.
the class ServerRuntime method process.
/**
* Process a container request.
*
* @param request container request to be processed.
*/
public void process(final ContainerRequest request) {
TracingUtils.initTracingSupport(tracingConfig, tracingThreshold, request);
TracingUtils.logStart(request);
final UriRoutingContext routingContext = request.getUriRoutingContext();
RequestEventBuilder monitoringEventBuilder = EmptyRequestEventBuilder.INSTANCE;
RequestEventListener monitoringEventListener = null;
if (applicationEventListener != null) {
monitoringEventBuilder = new RequestEventImpl.Builder().setContainerRequest(request).setExtendedUriInfo(routingContext);
monitoringEventListener = applicationEventListener.onRequest(monitoringEventBuilder.build(RequestEvent.Type.START));
}
request.setProcessingProviders(processingProviders);
final RequestProcessingContext context = new RequestProcessingContext(injectionManager, request, routingContext, monitoringEventBuilder, monitoringEventListener);
request.checkState();
final Responder responder = new Responder(context, ServerRuntime.this);
final RequestScope.Instance requestScopeInstance = requestScope.createInstance();
// TODO: Will we need EXTERNAL_REQUEST_SCOPE after the injection task?
final AsyncResponderHolder asyncResponderHolder = new AsyncResponderHolder(responder, externalRequestScope, requestScopeInstance, externalRequestScope.open(injectionManager));
context.initAsyncContext(asyncResponderHolder);
requestScope.runInScope(requestScopeInstance, new Runnable() {
@Override
public void run() {
try {
// for later resolving of relative location URIs
if (!disableLocationHeaderRelativeUriResolution) {
final URI uriToUse = rfc7231LocationHeaderRelativeUriResolution ? request.getRequestUri() : request.getBaseUri();
OutboundJaxrsResponse.Builder.setBaseUri(uriToUse);
}
final Ref<Endpoint> endpointRef = Refs.emptyRef();
final RequestProcessingContext data = Stages.process(context, requestProcessingRoot, endpointRef);
final Endpoint endpoint = endpointRef.get();
if (endpoint == null) {
// not found
throw new NotFoundException();
}
final ContainerResponse response = endpoint.apply(data);
if (!asyncResponderHolder.isAsync()) {
responder.process(response);
} else {
externalRequestScope.suspend(asyncResponderHolder.externalContext, injectionManager);
}
} catch (final Throwable throwable) {
responder.process(throwable);
} finally {
asyncResponderHolder.release();
// clear base URI from the thread
OutboundJaxrsResponse.Builder.clearBaseUri();
}
}
});
}
Aggregations