Search in sources :

Example 66 with Context

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();
    }
}
Also used : UserService(org.gluu.oxauth.service.UserService) Arrays(java.util.Arrays) Logger(org.slf4j.Logger) Context(javax.ws.rs.core.Context) SessionClient(org.gluu.oxauth.model.session.SessionClient) Identity(org.gluu.oxauth.security.Identity) HttpServletResponse(javax.servlet.http.HttpServletResponse) SecurityContext(javax.ws.rs.core.SecurityContext) Collectors(java.util.stream.Collectors) ScopeService(org.gluu.oxauth.service.ScopeService) SessionId(org.gluu.oxauth.model.common.SessionId) SessionIdState(org.gluu.oxauth.model.common.SessionIdState) Constants(org.gluu.oxauth.model.config.Constants) Inject(javax.inject.Inject) HttpServletRequest(javax.servlet.http.HttpServletRequest) MediaType(javax.ws.rs.core.MediaType) List(java.util.List) SessionIdService(org.gluu.oxauth.service.SessionIdService) javax.ws.rs(javax.ws.rs) Response(javax.ws.rs.core.Response) User(org.gluu.oxauth.model.common.User) ErrorResponseFactory(org.gluu.oxauth.model.error.ErrorResponseFactory) EndSessionErrorResponseType(org.gluu.oxauth.model.session.EndSessionErrorResponseType) ArrayUtils(org.apache.commons.lang.ArrayUtils) User(org.gluu.oxauth.model.common.User) SessionId(org.gluu.oxauth.model.common.SessionId)

Example 67 with Context

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();
}
Also used : WorkspaceEntityFileRESTModel(fi.otavanopisto.muikku.plugins.workspace.rest.model.WorkspaceEntityFileRESTModel) Arrays(java.util.Arrays) Produces(javax.ws.rs.Produces) WorkspaceCompositeReply(fi.otavanopisto.muikku.plugins.workspace.rest.model.WorkspaceCompositeReply) EnvironmentRoleArchetype(fi.otavanopisto.muikku.model.users.EnvironmentRoleArchetype) WorkspaceMaterialFileFieldAnswerFile(fi.otavanopisto.muikku.plugins.workspace.model.WorkspaceMaterialFileFieldAnswerFile) WorkspaceEntity(fi.otavanopisto.muikku.model.workspace.WorkspaceEntity) Material(fi.otavanopisto.muikku.plugins.material.model.Material) Flag(fi.otavanopisto.muikku.model.users.Flag) StringUtils(org.apache.commons.lang3.StringUtils) User(fi.otavanopisto.muikku.schooldata.entity.User) WorkspaceEntityFileController(fi.otavanopisto.muikku.plugins.workspace.WorkspaceEntityFileController) WorkspaceMaterialAudioFieldAnswerClip(fi.otavanopisto.muikku.plugins.workspace.model.WorkspaceMaterialAudioFieldAnswerClip) Map(java.util.Map) CourseMetaController(fi.otavanopisto.muikku.schooldata.CourseMetaController) WorkspaceMaterialCompositeReply(fi.otavanopisto.muikku.plugins.workspace.rest.model.WorkspaceMaterialCompositeReply) Instance(javax.enterprise.inject.Instance) WorkspaceDetails(fi.otavanopisto.muikku.plugins.workspace.rest.model.WorkspaceDetails) WorkspaceFeeInfo(fi.otavanopisto.muikku.plugins.workspace.rest.model.WorkspaceFeeInfo) WorkspaceFolder(fi.otavanopisto.muikku.plugins.workspace.model.WorkspaceFolder) WorkspaceEntityController(fi.otavanopisto.muikku.schooldata.WorkspaceEntityController) AssessmentRequestController(fi.otavanopisto.muikku.plugins.assessmentrequest.AssessmentRequestController) SchoolDataIdentifier(fi.otavanopisto.muikku.schooldata.SchoolDataIdentifier) HtmlMaterial(fi.otavanopisto.muikku.plugins.material.model.HtmlMaterial) Set(java.util.Set) TempFileUtils(fi.otavanopisto.muikku.files.TempFileUtils) IOUtils(org.apache.commons.io.IOUtils) WorkspaceMaterialProducer(fi.otavanopisto.muikku.model.workspace.WorkspaceMaterialProducer) WorkspaceType(fi.otavanopisto.muikku.schooldata.entity.WorkspaceType) WorkspaceFieldIOException(fi.otavanopisto.muikku.plugins.workspace.fieldio.WorkspaceFieldIOException) DatatypeConverter(javax.xml.bind.DatatypeConverter) WorkspaceIndexer(fi.otavanopisto.muikku.plugins.search.WorkspaceIndexer) ZipOutputStream(java.util.zip.ZipOutputStream) GET(javax.ws.rs.GET) MuikkuPermissions(fi.otavanopisto.muikku.security.MuikkuPermissions) WorkspaceMaterialField(fi.otavanopisto.muikku.plugins.workspace.model.WorkspaceMaterialField) RESTPermitUnimplemented(fi.otavanopisto.muikku.rest.RESTPermitUnimplemented) Handling(fi.otavanopisto.security.rest.RESTPermit.Handling) WorkspaceVisitController(fi.otavanopisto.muikku.plugins.workspace.WorkspaceVisitController) ArrayList(java.util.ArrayList) SessionController(fi.otavanopisto.muikku.session.SessionController) WorkspaceJournalEntryRESTModel(fi.otavanopisto.muikku.plugins.workspace.rest.model.WorkspaceJournalEntryRESTModel) RESTPermit(fi.otavanopisto.security.rest.RESTPermit) WorkspaceMaterialReplyController(fi.otavanopisto.muikku.plugins.workspace.WorkspaceMaterialReplyController) ResponseBuilder(javax.ws.rs.core.Response.ResponseBuilder) WorkspaceMaterialFieldAnswer(fi.otavanopisto.muikku.plugins.workspace.rest.model.WorkspaceMaterialFieldAnswer) IOException(java.io.IOException) MaterialViewRestrict(fi.otavanopisto.muikku.plugins.material.model.MaterialViewRestrict) WorkspaceMaterial(fi.otavanopisto.muikku.plugins.workspace.model.WorkspaceMaterial) Stateful(javax.ejb.Stateful) RestCatchSchoolDataExceptions(fi.otavanopisto.muikku.schooldata.RestCatchSchoolDataExceptions) WorkspaceUserEntityController(fi.otavanopisto.muikku.users.WorkspaceUserEntityController) SearchProvider(fi.otavanopisto.muikku.search.SearchProvider) WorkspaceMaterialFieldController(fi.otavanopisto.muikku.plugins.workspace.WorkspaceMaterialFieldController) WorkspaceNodeType(fi.otavanopisto.muikku.plugins.workspace.model.WorkspaceNodeType) MaterialController(fi.otavanopisto.muikku.plugins.material.MaterialController) WorkspaceMaterialController(fi.otavanopisto.muikku.plugins.workspace.WorkspaceMaterialController) WorkspaceMaterialReplyState(fi.otavanopisto.muikku.plugins.workspace.model.WorkspaceMaterialReplyState) Date(java.util.Date) Path(javax.ws.rs.Path) BooleanPredicate(fi.otavanopisto.muikku.model.base.BooleanPredicate) QueryParam(javax.ws.rs.QueryParam) ByteArrayInputStream(java.io.ByteArrayInputStream) DefaultValue(javax.ws.rs.DefaultValue) Any(javax.enterprise.inject.Any) Workspace(fi.otavanopisto.muikku.schooldata.entity.Workspace) ZipEntry(java.util.zip.ZipEntry) Sort(fi.otavanopisto.muikku.search.SearchProvider.Sort) DELETE(javax.ws.rs.DELETE) Context(javax.ws.rs.core.Context) WorkspaceJournalEntry(fi.otavanopisto.muikku.plugins.workspace.model.WorkspaceJournalEntry) WorkspaceMaterialAssignmentType(fi.otavanopisto.muikku.plugins.workspace.model.WorkspaceMaterialAssignmentType) Collection(java.util.Collection) WorkspaceEntityFile(fi.otavanopisto.muikku.plugins.workspace.model.WorkspaceEntityFile) WorkspaceMaterialContainsAnswersExeption(fi.otavanopisto.muikku.plugins.workspace.WorkspaceMaterialContainsAnswersExeption) StreamingOutput(javax.ws.rs.core.StreamingOutput) Logger(java.util.logging.Logger) GradingController(fi.otavanopisto.muikku.schooldata.GradingController) Objects(java.util.Objects) EducationType(fi.otavanopisto.muikku.schooldata.entity.EducationType) List(java.util.List) OffsetDateTime(java.time.OffsetDateTime) UserEntityController(fi.otavanopisto.muikku.users.UserEntityController) Response(javax.ws.rs.core.Response) UserController(fi.otavanopisto.muikku.users.UserController) WorkspaceNode(fi.otavanopisto.muikku.plugins.workspace.model.WorkspaceNode) WorkspaceMaterialReply(fi.otavanopisto.muikku.plugins.workspace.rest.model.WorkspaceMaterialReply) WorkspaceRoleArchetype(fi.otavanopisto.muikku.model.workspace.WorkspaceRoleArchetype) Request(javax.ws.rs.core.Request) CacheControl(javax.ws.rs.core.CacheControl) WorkspaceStudent(fi.otavanopisto.muikku.plugins.workspace.rest.model.WorkspaceStudent) UserEntity(fi.otavanopisto.muikku.model.users.UserEntity) UserIndexer(fi.otavanopisto.muikku.plugins.search.UserIndexer) WorkspaceController(fi.otavanopisto.muikku.schooldata.WorkspaceController) PathParam(javax.ws.rs.PathParam) WorkspaceRootFolder(fi.otavanopisto.muikku.plugins.workspace.model.WorkspaceRootFolder) FlagController(fi.otavanopisto.muikku.users.FlagController) WorkspaceUser(fi.otavanopisto.muikku.schooldata.entity.WorkspaceUser) HashMap(java.util.HashMap) WorkspaceMaterialDeleteError(fi.otavanopisto.muikku.plugins.workspace.WorkspaceMaterialDeleteError) Level(java.util.logging.Level) MessagingWidget(fi.otavanopisto.muikku.controller.messaging.MessagingWidget) HashSet(java.util.HashSet) Inject(javax.inject.Inject) FileController(fi.otavanopisto.muikku.plugins.data.FileController) CollectionUtils(org.apache.commons.collections.CollectionUtils) Status(javax.ws.rs.core.Response.Status) OutputStream(java.io.OutputStream) POST(javax.ws.rs.POST) Iterator(java.util.Iterator) WorkspaceUserEntity(fi.otavanopisto.muikku.model.workspace.WorkspaceUserEntity) WorkspaceStaffMember(fi.otavanopisto.muikku.plugins.workspace.rest.model.WorkspaceStaffMember) SearchResult(fi.otavanopisto.muikku.search.SearchResult) EntityTag(javax.ws.rs.core.EntityTag) WorkspaceJournalController(fi.otavanopisto.muikku.plugins.workspace.WorkspaceJournalController) PluginRESTService(fi.otavanopisto.muikku.plugin.PluginRESTService) RequestScoped(javax.enterprise.context.RequestScoped) UserSchoolDataIdentifier(fi.otavanopisto.muikku.model.users.UserSchoolDataIdentifier) QueryFieldController(fi.otavanopisto.muikku.plugins.material.QueryFieldController) WorkspaceMaterialFieldAnswerController(fi.otavanopisto.muikku.plugins.workspace.WorkspaceMaterialFieldAnswerController) SchoolDataBridgeSessionController(fi.otavanopisto.muikku.schooldata.SchoolDataBridgeSessionController) PUT(javax.ws.rs.PUT) Comparator(java.util.Comparator) DigestUtils(org.apache.commons.codec.digest.DigestUtils) Collections(java.util.Collections) InputStream(java.io.InputStream) WorkspaceEntityFile(fi.otavanopisto.muikku.plugins.workspace.model.WorkspaceEntityFile) WorkspaceEntity(fi.otavanopisto.muikku.model.workspace.WorkspaceEntity) StreamingOutput(javax.ws.rs.core.StreamingOutput) EntityTag(javax.ws.rs.core.EntityTag) CacheControl(javax.ws.rs.core.CacheControl) ResponseBuilder(javax.ws.rs.core.Response.ResponseBuilder) Path(javax.ws.rs.Path) RESTPermit(fi.otavanopisto.security.rest.RESTPermit) GET(javax.ws.rs.GET)

Example 68 with Context

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();
}
Also used : Produces(javax.ws.rs.Produces) AuthorizerMapper(org.apache.druid.server.security.AuthorizerMapper) TaskLogStreamer(org.apache.druid.tasklogs.TaskLogStreamer) Inject(com.google.inject.Inject) Path(javax.ws.rs.Path) ResourceFilters(com.sun.jersey.spi.container.ResourceFilters) JacksonConfigManager(org.apache.druid.common.config.JacksonConfigManager) SettableFuture(com.google.common.util.concurrent.SettableFuture) TaskStorageQueryAdapter(org.apache.druid.indexing.overlord.TaskStorageQueryAdapter) HttpMediaType(org.apache.druid.server.http.HttpMediaType) MediaType(javax.ws.rs.core.MediaType) QueryParam(javax.ws.rs.QueryParam) TaskActionClient(org.apache.druid.indexing.common.actions.TaskActionClient) Consumes(javax.ws.rs.Consumes) TaskQueue(org.apache.druid.indexing.overlord.TaskQueue) Optional(com.google.common.base.Optional) Task(org.apache.druid.indexing.common.task.Task) TaskRunner(org.apache.druid.indexing.overlord.TaskRunner) Map(java.util.Map) DefaultValue(javax.ws.rs.DefaultValue) HeaderParam(javax.ws.rs.HeaderParam) ForbiddenException(org.apache.druid.server.security.ForbiddenException) TaskResourceFilter(org.apache.druid.indexing.overlord.http.security.TaskResourceFilter) DELETE(javax.ws.rs.DELETE) WorkerBehaviorConfig(org.apache.druid.indexing.overlord.setup.WorkerBehaviorConfig) DateTimes(org.apache.druid.java.util.common.DateTimes) Function(com.google.common.base.Function) Context(javax.ws.rs.core.Context) ImmutableMap(com.google.common.collect.ImmutableMap) Collection(java.util.Collection) StringUtils(org.apache.druid.java.util.common.StringUtils) Set(java.util.Set) Action(org.apache.druid.server.security.Action) IndexerMetadataStorageAdapter(org.apache.druid.indexing.overlord.IndexerMetadataStorageAdapter) Collectors(java.util.stream.Collectors) AuditManager(org.apache.druid.audit.AuditManager) TaskStatusPlus(org.apache.druid.indexer.TaskStatusPlus) DatasourceResourceFilter(org.apache.druid.server.http.security.DatasourceResourceFilter) TaskState(org.apache.druid.indexer.TaskState) List(java.util.List) Response(javax.ws.rs.core.Response) ClientTaskQuery(org.apache.druid.client.indexing.ClientTaskQuery) AuditEntry(org.apache.druid.audit.AuditEntry) DataSegment(org.apache.druid.timeline.DataSegment) WebApplicationException(javax.ws.rs.WebApplicationException) TaskMaster(org.apache.druid.indexing.overlord.TaskMaster) Logger(org.apache.druid.java.util.common.logger.Logger) SetResult(org.apache.druid.common.config.ConfigManager.SetResult) TaskActionHolder(org.apache.druid.indexing.common.actions.TaskActionHolder) AuditInfo(org.apache.druid.audit.AuditInfo) PathParam(javax.ws.rs.PathParam) ListenableFuture(com.google.common.util.concurrent.ListenableFuture) Intervals(org.apache.druid.java.util.common.Intervals) GET(javax.ws.rs.GET) Duration(org.joda.time.Duration) HashMap(java.util.HashMap) AtomicReference(java.util.concurrent.atomic.AtomicReference) TaskStatus(org.apache.druid.indexer.TaskStatus) WorkerTaskRunnerQueryAdapter(org.apache.druid.indexing.overlord.WorkerTaskRunnerQueryAdapter) ScalingStats(org.apache.druid.indexing.overlord.autoscaling.ScalingStats) ArrayList(java.util.ArrayList) EntryExistsException(org.apache.druid.metadata.EntryExistsException) Interval(org.joda.time.Interval) HttpServletRequest(javax.servlet.http.HttpServletRequest) Lists(com.google.common.collect.Lists) ImmutableList(com.google.common.collect.ImmutableList) DefaultWorkerBehaviorConfig(org.apache.druid.indexing.overlord.setup.DefaultWorkerBehaviorConfig) ByteSource(com.google.common.io.ByteSource) Status(javax.ws.rs.core.Response.Status) StateResourceFilter(org.apache.druid.server.http.security.StateResourceFilter) Nullable(javax.annotation.Nullable) ImmutableWorkerInfo(org.apache.druid.indexing.overlord.ImmutableWorkerInfo) Access(org.apache.druid.server.security.Access) POST(javax.ws.rs.POST) TaskInfo(org.apache.druid.indexer.TaskInfo) ResourceType(org.apache.druid.server.security.ResourceType) DateTime(org.joda.time.DateTime) TaskLocation(org.apache.druid.indexer.TaskLocation) WorkerTaskRunner(org.apache.druid.indexing.overlord.WorkerTaskRunner) ConfigResourceFilter(org.apache.druid.server.http.security.ConfigResourceFilter) AuthorizationUtils(org.apache.druid.server.security.AuthorizationUtils) Maps(com.google.common.collect.Maps) RunnerTaskState(org.apache.druid.indexer.RunnerTaskState) ProvisioningStrategy(org.apache.druid.indexing.overlord.autoscaling.ProvisioningStrategy) Resource(org.apache.druid.server.security.Resource) ResourceAction(org.apache.druid.server.security.ResourceAction) TaskRunnerWorkItem(org.apache.druid.indexing.overlord.TaskRunnerWorkItem) Collections(java.util.Collections) Task(org.apache.druid.indexing.common.task.Task) WebApplicationException(javax.ws.rs.WebApplicationException) Resource(org.apache.druid.server.security.Resource) Access(org.apache.druid.server.security.Access) ArrayList(java.util.ArrayList) Duration(org.joda.time.Duration) TaskStatus(org.apache.druid.indexer.TaskStatus) TaskInfo(org.apache.druid.indexer.TaskInfo) TaskStatusPlus(org.apache.druid.indexer.TaskStatusPlus) ResourceAction(org.apache.druid.server.security.ResourceAction) Interval(org.joda.time.Interval) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET)

Example 69 with Context

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();
    }
}
Also used : Logger(org.apache.druid.java.util.common.logger.Logger) SqlLifecycle(org.apache.druid.sql.SqlLifecycle) PathParam(javax.ws.rs.PathParam) Produces(javax.ws.rs.Produces) AuthorizerMapper(org.apache.druid.server.security.AuthorizerMapper) Inject(com.google.inject.Inject) CountingOutputStream(com.google.common.io.CountingOutputStream) BadQueryException(org.apache.druid.query.BadQueryException) Path(javax.ws.rs.Path) Yielders(org.apache.druid.java.util.common.guava.Yielders) QueryCapacityExceededException(org.apache.druid.query.QueryCapacityExceededException) HttpServletRequest(javax.servlet.http.HttpServletRequest) MediaType(javax.ws.rs.core.MediaType) Consumes(javax.ws.rs.Consumes) SqlPlanningException(org.apache.druid.sql.SqlPlanningException) ForbiddenException(org.apache.druid.server.security.ForbiddenException) Yielder(org.apache.druid.java.util.common.guava.Yielder) Status(javax.ws.rs.core.Response.Status) Nullable(javax.annotation.Nullable) DELETE(javax.ws.rs.DELETE) SanitizableException(org.apache.druid.common.exception.SanitizableException) Sequence(org.apache.druid.java.util.common.guava.Sequence) Access(org.apache.druid.server.security.Access) POST(javax.ws.rs.POST) Context(javax.ws.rs.core.Context) ServerConfig(org.apache.druid.server.initialization.ServerConfig) QueryInterruptedException(org.apache.druid.query.QueryInterruptedException) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) SqlLifecycleFactory(org.apache.druid.sql.SqlLifecycleFactory) StringUtils(org.apache.druid.java.util.common.StringUtils) Set(java.util.Set) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) SqlRowTransformer(org.apache.druid.sql.SqlRowTransformer) StreamingOutput(javax.ws.rs.core.StreamingOutput) IOException(java.io.IOException) Json(org.apache.druid.guice.annotations.Json) AuthorizationUtils(org.apache.druid.server.security.AuthorizationUtils) SqlLifecycleManager(org.apache.druid.sql.SqlLifecycleManager) Collectors(java.util.stream.Collectors) List(java.util.List) QueryTimeoutException(org.apache.druid.query.QueryTimeoutException) Response(javax.ws.rs.core.Response) ResourceAction(org.apache.druid.server.security.ResourceAction) ResourceLimitExceededException(org.apache.druid.query.ResourceLimitExceededException) Preconditions(com.google.common.base.Preconditions) RelOptPlanner(org.apache.calcite.plan.RelOptPlanner) QueryUnsupportedException(org.apache.druid.query.QueryUnsupportedException) SqlLifecycle(org.apache.druid.sql.SqlLifecycle) Access(org.apache.druid.server.security.Access) ResourceAction(org.apache.druid.server.security.ResourceAction) Path(javax.ws.rs.Path) DELETE(javax.ws.rs.DELETE) Produces(javax.ws.rs.Produces)

Example 70 with Context

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();
        }
    });
}
Also used : PrimitiveWrapper(org.talend.sdk.component.server.front.model.execution.PrimitiveWrapper) Produces(javax.ws.rs.Produces) Path(javax.ws.rs.Path) BAD_FORMAT(org.talend.sdk.component.server.front.model.ErrorDictionary.BAD_FORMAT) PreDestroy(javax.annotation.PreDestroy) MediaType(javax.ws.rs.core.MediaType) JsonNumber(javax.json.JsonNumber) QueryParam(javax.ws.rs.QueryParam) Collectors.toMap(java.util.stream.Collectors.toMap) Consumes(javax.ws.rs.Consumes) Map(java.util.Map) DefaultValue(javax.ws.rs.DefaultValue) BAD_REQUEST(javax.ws.rs.core.Response.Status.BAD_REQUEST) JsonObject(javax.json.JsonObject) JsonbBuilder(javax.json.bind.JsonbBuilder) Context(javax.ws.rs.core.Context) Providers(javax.ws.rs.ext.Providers) AsyncResponse(javax.ws.rs.container.AsyncResponse) StreamingOutput(javax.ws.rs.core.StreamingOutput) Processor(org.talend.sdk.component.runtime.output.Processor) Suspended(javax.ws.rs.container.Suspended) StandardCharsets(java.nio.charset.StandardCharsets) ErrorPayload(org.talend.sdk.component.server.front.model.error.ErrorPayload) OutputEmitter(org.talend.sdk.component.api.processor.OutputEmitter) Branches(org.talend.sdk.component.runtime.output.Branches) Slf4j(lombok.extern.slf4j.Slf4j) Response(javax.ws.rs.core.Response) PostConstruct(javax.annotation.PostConstruct) Optional(java.util.Optional) WebApplicationException(javax.ws.rs.WebApplicationException) ApplicationScoped(javax.enterprise.context.ApplicationScoped) ACTION_ERROR(org.talend.sdk.component.server.front.model.ErrorDictionary.ACTION_ERROR) WriteStatistics(org.talend.sdk.component.server.front.model.execution.WriteStatistics) PathParam(javax.ws.rs.PathParam) OutputFactory(org.talend.sdk.component.runtime.output.OutputFactory) Inject(javax.inject.Inject) ComponentServerConfiguration(org.talend.sdk.component.server.configuration.ComponentServerConfiguration) Input(org.talend.sdk.component.runtime.input.Input) ExecutorService(java.util.concurrent.ExecutorService) POST(javax.ws.rs.POST) Optional.ofNullable(java.util.Optional.ofNullable) COMPONENT_MISSING(org.talend.sdk.component.server.front.model.ErrorDictionary.COMPONENT_MISSING) InputStreamReader(java.io.InputStreamReader) JsonString(javax.json.JsonString) Mapper(org.talend.sdk.component.runtime.input.Mapper) Jsonb(javax.json.bind.Jsonb) BufferedReader(java.io.BufferedReader) ComponentManager(org.talend.sdk.component.runtime.manager.ComponentManager) SECONDS(java.util.concurrent.TimeUnit.SECONDS) InputStream(java.io.InputStream) Mapper(org.talend.sdk.component.runtime.input.Mapper) PrimitiveWrapper(org.talend.sdk.component.server.front.model.execution.PrimitiveWrapper) ErrorPayload(org.talend.sdk.component.server.front.model.error.ErrorPayload) Input(org.talend.sdk.component.runtime.input.Input) WebApplicationException(javax.ws.rs.WebApplicationException) JsonNumber(javax.json.JsonNumber) JsonObject(javax.json.JsonObject) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Produces(javax.ws.rs.Produces)

Aggregations

Context (javax.ws.rs.core.Context)73 Response (javax.ws.rs.core.Response)54 Path (javax.ws.rs.Path)49 PathParam (javax.ws.rs.PathParam)42 GET (javax.ws.rs.GET)40 List (java.util.List)39 MediaType (javax.ws.rs.core.MediaType)36 POST (javax.ws.rs.POST)35 Produces (javax.ws.rs.Produces)32 UriInfo (javax.ws.rs.core.UriInfo)32 Inject (javax.inject.Inject)29 PUT (javax.ws.rs.PUT)29 HttpServletRequest (javax.servlet.http.HttpServletRequest)27 QueryParam (javax.ws.rs.QueryParam)27 Collectors (java.util.stream.Collectors)26 Map (java.util.Map)25 Api (io.swagger.annotations.Api)24 ApiOperation (io.swagger.annotations.ApiOperation)24 IOException (java.io.IOException)24 URI (java.net.URI)24