use of javax.ws.rs.core.Context in project oxAuth by GluuFederation.
the class RevokeSessionRestWebService method requestRevokeSession.
@POST
@Path("/revoke_session")
@Produces({ MediaType.APPLICATION_JSON })
public Response requestRevokeSession(@FormParam("user_criterion_key") String userCriterionKey, @FormParam("user_criterion_value") String userCriterionValue, @Context HttpServletRequest request, @Context HttpServletResponse response, @Context SecurityContext sec) {
try {
log.debug("Attempting to revoke session: userCriterionKey = {}, userCriterionValue = {}, isSecure = {}", userCriterionKey, userCriterionValue, sec.isSecure());
validateAccess();
final User user = userService.getUserByAttribute(userCriterionKey, userCriterionValue);
if (user == null) {
log.trace("Unable to find user by {}={}", userCriterionKey, userCriterionValue);
// no error because we don't want to disclose internal AS info about users
return Response.ok().build();
}
List<SessionId> sessionIdList = sessionIdService.findByUser(user.getDn());
if (sessionIdList == null || sessionIdList.isEmpty()) {
log.trace("No sessions found for user uid: {}, dn: {}", user.getUserId(), user.getDn());
return Response.ok().build();
}
final List<SessionId> authenticatedSessions = sessionIdList.stream().filter(sessionId -> sessionId.getState() == SessionIdState.AUTHENTICATED).collect(Collectors.toList());
sessionIdService.remove(authenticatedSessions);
log.debug("Revoked {} user's sessions (user: {})", authenticatedSessions.size(), user.getUserId());
return Response.ok().build();
} catch (WebApplicationException e) {
throw e;
} catch (Exception e) {
log.error(e.getMessage(), e);
return Response.status(500).build();
}
}
use of javax.ws.rs.core.Context in project muikku by otavanopisto.
the class WorkspaceRESTService method getWorkspaceFileContent.
@GET
@Path("/workspaces/{WORKSPACEID}/workspacefile/{FILEIDENTIFIER}")
@RESTPermit(handling = Handling.INLINE)
public Response getWorkspaceFileContent(@PathParam("WORKSPACEID") Long workspaceId, @PathParam("FILEIDENTIFIER") String fileIdentifier, @Context Request request) {
WorkspaceEntity workspaceEntity = workspaceEntityController.findWorkspaceEntityById(workspaceId);
if (workspaceEntity == null)
return Response.status(Status.BAD_REQUEST).build();
WorkspaceEntityFile imageFile = workspaceEntityFileController.findWorkspaceEntityFile(workspaceEntity, fileIdentifier);
if (imageFile == null)
return Response.status(Status.NOT_FOUND).build();
StreamingOutput output = s -> fileController.outputFileToStream("workspace", imageFile.getDiskName(), s);
String contentType = imageFile.getContentType();
String tagIdentifier = String.format("%d-%s-%d", imageFile.getWorkspaceEntity(), imageFile.getDiskName(), imageFile.getLastModified().getTime());
EntityTag tag = new EntityTag(DigestUtils.md5Hex(String.valueOf(tagIdentifier)));
ResponseBuilder builder = request.evaluatePreconditions(tag);
if (builder != null) {
return builder.build();
}
CacheControl cacheControl = new CacheControl();
cacheControl.setMustRevalidate(true);
return Response.ok().cacheControl(cacheControl).tag(tag).type(contentType).entity(output).build();
}
use of javax.ws.rs.core.Context in project druid by druid-io.
the class OverlordResource method getTasks.
@GET
@Path("/tasks")
@Produces(MediaType.APPLICATION_JSON)
public Response getTasks(@QueryParam("state") final String state, @QueryParam("datasource") final String dataSource, @QueryParam("createdTimeInterval") final String createdTimeInterval, @QueryParam("max") final Integer maxCompletedTasks, @QueryParam("type") final String type, @Context final HttpServletRequest req) {
// check for valid state
if (state != null) {
if (!API_TASK_STATES.contains(StringUtils.toLowerCase(state))) {
return Response.status(Status.BAD_REQUEST).entity(StringUtils.format("Invalid state : %s, valid values are: %s", state, API_TASK_STATES)).build();
}
}
// fail fast if user not authorized to access datasource
if (dataSource != null) {
final ResourceAction resourceAction = new ResourceAction(new Resource(dataSource, ResourceType.DATASOURCE), Action.READ);
final Access authResult = AuthorizationUtils.authorizeResourceAction(req, resourceAction, authorizerMapper);
if (!authResult.isAllowed()) {
throw new WebApplicationException(Response.status(Response.Status.FORBIDDEN).entity(StringUtils.format("Access-Check-Result: %s", authResult.toString())).build());
}
}
List<TaskStatusPlus> finalTaskList = new ArrayList<>();
Function<AnyTask, TaskStatusPlus> activeTaskTransformFunc = workItem -> new TaskStatusPlus(workItem.getTaskId(), workItem.getTaskGroupId(), workItem.getTaskType(), workItem.getCreatedTime(), workItem.getQueueInsertionTime(), workItem.getTaskState(), workItem.getRunnerTaskState(), null, workItem.getLocation(), workItem.getDataSource(), null);
Function<TaskInfo<Task, TaskStatus>, TaskStatusPlus> completeTaskTransformFunc = taskInfo -> new TaskStatusPlus(taskInfo.getId(), taskInfo.getTask() == null ? null : taskInfo.getTask().getGroupId(), taskInfo.getTask() == null ? null : taskInfo.getTask().getType(), taskInfo.getCreatedTime(), // TaskStorage API doesn't yet allow it.
DateTimes.EPOCH, taskInfo.getStatus().getStatusCode(), RunnerTaskState.NONE, taskInfo.getStatus().getDuration(), taskInfo.getStatus().getLocation() == null ? TaskLocation.unknown() : taskInfo.getStatus().getLocation(), taskInfo.getDataSource(), taskInfo.getStatus().getErrorMsg());
// checking for complete tasks first to avoid querying active tasks if user only wants complete tasks
if (state == null || "complete".equals(StringUtils.toLowerCase(state))) {
Duration createdTimeDuration = null;
if (createdTimeInterval != null) {
final Interval theInterval = Intervals.of(StringUtils.replace(createdTimeInterval, "_", "/"));
createdTimeDuration = theInterval.toDuration();
}
final List<TaskInfo<Task, TaskStatus>> taskInfoList = taskStorageQueryAdapter.getCompletedTaskInfoByCreatedTimeDuration(maxCompletedTasks, createdTimeDuration, dataSource);
final List<TaskStatusPlus> completedTasks = taskInfoList.stream().map(completeTaskTransformFunc::apply).collect(Collectors.toList());
finalTaskList.addAll(completedTasks);
}
final List<TaskInfo<Task, TaskStatus>> allActiveTaskInfo;
final List<AnyTask> allActiveTasks = new ArrayList<>();
if (state == null || !"complete".equals(StringUtils.toLowerCase(state))) {
allActiveTaskInfo = taskStorageQueryAdapter.getActiveTaskInfo(dataSource);
for (final TaskInfo<Task, TaskStatus> task : allActiveTaskInfo) {
allActiveTasks.add(new AnyTask(task.getId(), task.getTask() == null ? null : task.getTask().getGroupId(), task.getTask() == null ? null : task.getTask().getType(), SettableFuture.create(), task.getDataSource(), null, null, task.getCreatedTime(), DateTimes.EPOCH, TaskLocation.unknown()));
}
}
if (state == null || "waiting".equals(StringUtils.toLowerCase(state))) {
final List<AnyTask> waitingWorkItems = filterActiveTasks(RunnerTaskState.WAITING, allActiveTasks);
List<TaskStatusPlus> transformedWaitingList = waitingWorkItems.stream().map(activeTaskTransformFunc::apply).collect(Collectors.toList());
finalTaskList.addAll(transformedWaitingList);
}
if (state == null || "pending".equals(StringUtils.toLowerCase(state))) {
final List<AnyTask> pendingWorkItems = filterActiveTasks(RunnerTaskState.PENDING, allActiveTasks);
List<TaskStatusPlus> transformedPendingList = pendingWorkItems.stream().map(activeTaskTransformFunc::apply).collect(Collectors.toList());
finalTaskList.addAll(transformedPendingList);
}
if (state == null || "running".equals(StringUtils.toLowerCase(state))) {
final List<AnyTask> runningWorkItems = filterActiveTasks(RunnerTaskState.RUNNING, allActiveTasks);
List<TaskStatusPlus> transformedRunningList = runningWorkItems.stream().map(activeTaskTransformFunc::apply).collect(Collectors.toList());
finalTaskList.addAll(transformedRunningList);
}
final List<TaskStatusPlus> authorizedList = securedTaskStatusPlus(finalTaskList, dataSource, type, req);
return Response.ok(authorizedList).build();
}
use of javax.ws.rs.core.Context in project druid by druid-io.
the class SqlResource method cancelQuery.
@DELETE
@Path("{id}")
@Produces(MediaType.APPLICATION_JSON)
public Response cancelQuery(@PathParam("id") String sqlQueryId, @Context final HttpServletRequest req) {
log.debug("Received cancel request for query [%s]", sqlQueryId);
List<SqlLifecycle> lifecycles = sqlLifecycleManager.getAll(sqlQueryId);
if (lifecycles.isEmpty()) {
return Response.status(Status.NOT_FOUND).build();
}
Set<ResourceAction> resources = lifecycles.stream().flatMap(lifecycle -> lifecycle.getRequiredResourceActions().stream()).collect(Collectors.toSet());
Access access = AuthorizationUtils.authorizeAllResourceActions(req, resources, authorizerMapper);
if (access.isAllowed()) {
// should remove only the lifecycles in the snapshot.
sqlLifecycleManager.removeAll(sqlQueryId, lifecycles);
lifecycles.forEach(SqlLifecycle::cancel);
return Response.status(Status.ACCEPTED).build();
} else {
return Response.status(Status.FORBIDDEN).build();
}
}
use of javax.ws.rs.core.Context in project component-runtime by Talend.
the class ExecutionResource method read.
/**
* Read inputs from an instance of mapper. The number of returned records if enforced to be limited to 1000.
* The format is a JSON based format where each like is a json record.
*
* @param family the component family.
* @param component the component name.
* @param size the maximum number of records to read.
* @param configuration the component configuration as key/values.
*/
@POST
@Deprecated
@Produces("talend/stream")
@Path("read/{family}/{component}")
public void read(@Suspended final AsyncResponse response, @Context final Providers providers, @PathParam("family") final String family, @PathParam("component") final String component, @QueryParam("size") @DefaultValue("50") final long size, final Map<String, String> configuration) {
final long maxSize = Math.min(size, MAX_RECORDS);
response.setTimeoutHandler(asyncResponse -> log.warn("Timeout on dataset retrieval"));
response.setTimeout(appConfiguration.datasetRetrieverTimeout(), SECONDS);
executorService.submit(() -> {
final Optional<Mapper> mapperOptional = manager.findMapper(family, component, getConfigComponentVersion(configuration), configuration);
if (!mapperOptional.isPresent()) {
response.resume(new WebApplicationException(Response.status(BAD_REQUEST).entity(new ErrorPayload(COMPONENT_MISSING, "Didn't find the input component")).build()));
return;
}
final Mapper mapper = mapperOptional.get();
mapper.start();
try {
final Input input = mapper.create();
try {
input.start();
response.resume((StreamingOutput) output -> {
Object data;
int current = 0;
while (current++ < maxSize && (data = input.next()) != null) {
if (CharSequence.class.isInstance(data) || Number.class.isInstance(data) || Boolean.class.isInstance(data)) {
final PrimitiveWrapper wrapper = new PrimitiveWrapper();
wrapper.setValue(data);
data = wrapper;
}
inlineStreamingMapper.toJson(data, output);
output.write(EOL);
}
});
} finally {
input.stop();
}
} finally {
mapper.stop();
}
});
}
Aggregations