javax.ws.rs.core.Context Java Examples

The following examples show how to use javax.ws.rs.core.Context. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: FunctionsResource.java    From cantor with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@DELETE
@Path("/run/{namespace}/{function}")
@Produces(MediaType.APPLICATION_JSON)
@Operation(summary = "Execute delete method on function query")
@ApiResponses(value = {
        @ApiResponse(responseCode = "200",
                description = "Process and execute the function",
                content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))),
        @ApiResponse(responseCode = "500", description = serverErrorMessage)
})
public Response deleteExecuteFunction(@PathParam("namespace") final String namespace,
                                      @PathParam("function") final String function,
                                      @Context final HttpServletRequest request,
                                      @Context final HttpServletResponse response) {
    logger.info("executing '{}/{}' with delete method", namespace, function);
    return doExecute(namespace, function, request, response);
}
 
Example #2
Source File: CellerySTSEndpoint.java    From cellery-security with Apache License 2.0 6 votes vote down vote up
@POST
@Path("/token")
@Consumes("application/x-www-form-urlencoded")
@Produces("application/json")
public Response getStsToken(@Context HttpServletRequest request, MultivaluedMap<String, String> form) {

    CellerySTSResponse stsResponse;
    try {
        io.cellery.security.sts.endpoint.core.CellerySTSRequest cellerySTSRequest = buildStsRequest(request, form);
        stsResponse = tokenService.issueJWT(cellerySTSRequest);
    } catch (CellerySTSException e) {
        log.error("Error while issuing STS Token.", e);
        return Response.serverError().build();
    }

    // Build response.
    return Response.ok().entity(stsResponse.toJson()).build();
}
 
Example #3
Source File: RestResourceTemplate.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@POST()
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)    
public $Type$Output createResource_$name$(@Context HttpHeaders httpHeaders, @QueryParam("businessKey") String businessKey, $Type$Input resource) {
    if (resource == null) {
        resource = new $Type$Input();
    }
    final $Type$Input value = resource;

    return org.kie.kogito.services.uow.UnitOfWorkExecutor.executeInUnitOfWork(application.unitOfWorkManager(), () -> {
        ProcessInstance<$Type$> pi = process.createInstance(businessKey, mapInput(value, new $Type$()));
        String startFromNode = httpHeaders.getHeaderString("X-KOGITO-StartFromNode");
        
        if (startFromNode != null) {
            pi.startFrom(startFromNode);
        } else {
        
            pi.start();
        }
        return getModel(pi);
    });
}
 
Example #4
Source File: RuleQueryController.java    From Qualitis with Apache License 2.0 6 votes vote down vote up
@POST
@Path("query")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public GeneralResponse<?> query(RuleQueryRequest param, @Context HttpServletRequest request) {
  if (param == null) {
    param = new RuleQueryRequest();
  }
  // Get login user
  param.setUser(HttpUtils.getUserName(request));
  try {
    List<RuleQueryProject> results = ruleQueryService.query(param);
    LOG.info("[My DataSource] Query successfully. The number of results:{}", results == null ? 0 : results.size());
    return new GeneralResponse<>("200", "{&QUERY_SUCCESSFULLY}", results);
  } catch (Exception e) {
    LOG.error("[My DataSource] Query failed, internal error.", e);
    return new GeneralResponse<>("500", e.getMessage(), null);
  }
}
 
Example #5
Source File: RuleQueryController.java    From Qualitis with Apache License 2.0 6 votes vote down vote up
@GET
@Path("init")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public GeneralResponse<?> init(@Context HttpServletRequest request) {
  // Get login user
  String user = HttpUtils.getUserName(request);
  try {
    List<RuleQueryProject> results = ruleQueryService.init(user);
    LOG.info("[My DataSource] Succeed to query initial results. The number of results:{}", results == null ? 0 : results.size());
    return new GeneralResponse<>("200", "{&QUERY_SUCCESSFULLY}", results);
  } catch (Exception e) {
    LOG.error("[My DataSource] Failed to query initial results, internal error", e);
    return new GeneralResponse<>("500", e.getMessage(), null);
  }
}
 
Example #6
Source File: RuleQueryController.java    From Qualitis with Apache License 2.0 6 votes vote down vote up
@GET
@Path("conditions")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public GeneralResponse<?> conditions(@Context HttpServletRequest request) {
  // Get login user
  String user = HttpUtils.getUserName(request);
  try {
    Map<String, Object> results = ruleQueryService.conditions(user);
    LOG.info("[My DataSource] Succeed to the query initial conditions, the result:{}", results);
    return new GeneralResponse<>("200", "{&QUERY_SUCCESSFULLY}", results);
  } catch (Exception e) {
    LOG.error("[My DataSource] Failed to the query initial conditions, internal error", e);
    return new GeneralResponse<>("500", e.getMessage(), null);
  }
}
 
Example #7
Source File: TestingHttpBackupResource.java    From presto with Apache License 2.0 6 votes vote down vote up
@PUT
@Path("{uuid}")
public synchronized Response putRequest(
        @HeaderParam(PRESTO_ENVIRONMENT) String environment,
        @HeaderParam(CONTENT_XXH64) String hexHash,
        @Context HttpServletRequest request,
        @PathParam("uuid") UUID uuid,
        byte[] bytes)
{
    checkEnvironment(environment);
    if ((request.getContentLength() < 0) || (bytes.length != request.getContentLength())) {
        return Response.status(BAD_REQUEST).build();
    }
    if (parseUnsignedLong(hexHash, 16) != XxHash64.hash(Slices.wrappedBuffer(bytes))) {
        return Response.status(BAD_REQUEST).build();
    }
    if (shards.containsKey(uuid)) {
        byte[] existing = shards.get(uuid);
        if ((existing == null) || !Arrays.equals(bytes, existing)) {
            return Response.status(FORBIDDEN).build();
        }
    }
    shards.put(uuid, bytes);
    return Response.noContent().build();
}
 
Example #8
Source File: IndexController.java    From Qualitis with Apache License 2.0 6 votes vote down vote up
/**
 * Paging get applications information that was submitted today.
 * Including details of applications
 * @return
 */
@POST
@Path("application/today")
@Produces(MediaType.APPLICATION_JSON)
public GeneralResponse<?> getTodaySubmitApplications(
    @Context HttpServletRequest httpServletRequest, PageRequest pageRequest)
    throws UnExpectedRequestException {
  PageRequest.checkRequest(pageRequest);
  String user = HttpUtils.getUserName(httpServletRequest);
  try {
    IndexApplicationTodayResponse response = indexService.getTodaySubmitApplications(user, pageRequest);
    return new GeneralResponse<>("200", "{&QUERY_SUCCESSFULLY}", response);
  } catch (Exception e) {
    LOG.error("[Home overview]Failed to query API: application/today, internal error", e);
    return new GeneralResponse<>("500", e.getMessage(), -1);
  }
}
 
Example #9
Source File: IndexController.java    From Qualitis with Apache License 2.0 6 votes vote down vote up
/**
 * Return applications status in given time.
 * Including num of successful task, failed task and not pass task
 *
 * @param request
 * @return
 * @throws UnExpectedRequestException
 */
@POST
@Path("application/chart")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public GeneralResponse<?> getApplicationChart(IndexRequest request,
    @Context HttpServletRequest httpServletRequest) throws UnExpectedRequestException {
  IndexRequest.checkRequest(request);
  String user = HttpUtils.getUserName(httpServletRequest);
  request.setUser(user);
  try {
    List<IndexApplicationChartResponse> response = indexService.getApplicationChart(request);
    return new GeneralResponse<>("200", "{&QUERY_SUCCESSFULLY}", response);
  } catch (Exception e) {
    LOG.error("[Home overview]Failed to query API: application/chart, internal error", e);
    return new GeneralResponse<>("500", e.getMessage(), -1);
  }
}
 
Example #10
Source File: FlowRestfulApi.java    From DataSphereStudio with Apache License 2.0 6 votes vote down vote up
@POST
@Path("/updateFlowBaseInfo")
public Response updateFlowBaseInfo(@Context HttpServletRequest req, JsonNode json) throws DSSErrorException {
    Long flowID = json.get("id").getLongValue();
    String name = json.get("name")==null?null:json.get("name").getTextValue();
    String description = json.get("description") == null?null:json.get("description").getTextValue();
    Long taxonomyID = json.get("taxonomyID") == null?null:json.get("taxonomyID").getLongValue();
    Long projectVersionID = json.get("projectVersionID").getLongValue();
    String uses = json.get("uses") == null?null:json.get("uses").getTextValue();
    publishManager.checkeIsPublishing(projectVersionID);
    // TODO: 2019/6/13  projectVersionID的更新校验
    //这里可以不做事务
    DWSFlow dwsFlow = new DWSFlow();
    dwsFlow.setId(flowID);
    dwsFlow.setName(name);
    dwsFlow.setDescription(description);
    dwsFlow.setUses(uses);
    flowService.updateFlowBaseInfo(dwsFlow,projectVersionID,taxonomyID);
    return Message.messageToResponse(Message.ok());
}
 
Example #11
Source File: FlowTaxonomyRestfulApi.java    From DataSphereStudio with Apache License 2.0 6 votes vote down vote up
@POST
@Path("/updateFlowTaxonomy")
public Response updateFlowTaxonomy(@Context HttpServletRequest req, JsonNode json) throws DSSErrorException {
    String name = json.get("name")==null?null:json.get("name").getTextValue();
    String description = json.get("description") == null?null:json.get("description").getTextValue();
    Long id = json.get("id").getLongValue();
    Long projectVersionID = json.get("projectVersionID").getLongValue();
    publishManager.checkeIsPublishing(projectVersionID);
    // TODO: 2019/6/13  projectVersionID的更新校验
    // TODO: 2019/5/16 空值校验,重复名校验
    DWSFlowTaxonomy dwsFlowTaxonomy = new DWSFlowTaxonomy();
    dwsFlowTaxonomy.setId(id);
    dwsFlowTaxonomy.setName(name);
    dwsFlowTaxonomy.setDescription(description);
    dwsFlowTaxonomy.setUpdateTime(new Date());
    flowTaxonomyService.updateFlowTaxonomy(dwsFlowTaxonomy,projectVersionID);
    return Message.messageToResponse(Message.ok());
}
 
Example #12
Source File: ArticlesResource.java    From realworld-api-quarkus with MIT License 6 votes vote down vote up
@GET
@Produces(MediaType.APPLICATION_JSON)
@Secured(optional = true)
public Response getArticles(
    @QueryParam("offset") int offset,
    @QueryParam("limit") int limit,
    @QueryParam("tag") List<String> tags,
    @QueryParam("author") List<String> authors,
    @QueryParam("favorited") List<String> favorited,
    @Context SecurityContext securityContext)
    throws JsonProcessingException {
  Long loggedUserId = getLoggedUserId(securityContext);
  ArticlesData result =
      articlesService.findArticles(offset, limit, loggedUserId, tags, authors, favorited);
  return Response.ok(objectMapper.writeValueAsString(new ArticlesResponse(result)))
      .status(Response.Status.OK)
      .build();
}
 
Example #13
Source File: ArticlesResource.java    From realworld-api-quarkus with MIT License 6 votes vote down vote up
@POST
@Secured({Role.ADMIN, Role.USER})
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response create(
    @Valid @NotNull(message = ValidationMessages.REQUEST_BODY_MUST_BE_NOT_NULL)
        NewArticleRequest newArticleRequest,
    @Context SecurityContext securityContext) {
  Long loggedUserId = getLoggedUserId(securityContext);
  ArticleData newArticleData =
      articlesService.create(
          newArticleRequest.getTitle(),
          newArticleRequest.getDescription(),
          newArticleRequest.getBody(),
          newArticleRequest.getTagList(),
          loggedUserId);
  return Response.ok(new ArticleResponse(newArticleData)).status(Response.Status.CREATED).build();
}
 
Example #14
Source File: ArticlesResource.java    From realworld-api-quarkus with MIT License 6 votes vote down vote up
@PUT
@Path("/{slug}")
@Secured({Role.ADMIN, Role.USER})
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response update(
    @PathParam("slug") @NotBlank String slug,
    @Valid @NotNull UpdateArticleRequest updateArticleRequest,
    @Context SecurityContext securityContext) {
  Long loggedUserId = getLoggedUserId(securityContext);
  ArticleData updatedArticleData =
      articlesService.update(
          slug,
          updateArticleRequest.getTitle(),
          updateArticleRequest.getDescription(),
          updateArticleRequest.getBody(),
          loggedUserId);
  return Response.ok(new ArticleResponse(updatedArticleData)).status(Response.Status.OK).build();
}
 
Example #15
Source File: ProxyResource.java    From presto with Apache License 2.0 6 votes vote down vote up
@DELETE
@Path("/v1/proxy")
@Produces(APPLICATION_JSON)
public void cancelQuery(
        @QueryParam("uri") String uri,
        @QueryParam("hmac") String hash,
        @Context HttpServletRequest servletRequest,
        @Suspended AsyncResponse asyncResponse)
{
    if (!hmac.hashString(uri, UTF_8).equals(HashCode.fromString(hash))) {
        throw badRequest(FORBIDDEN, "Failed to validate HMAC of URI");
    }

    Request.Builder request = prepareDelete().setUri(URI.create(uri));

    performRequest(servletRequest, asyncResponse, request, response -> responseWithHeaders(noContent(), response));
}
 
Example #16
Source File: FunctionsResource.java    From cantor with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@GET
@Path("/run/{namespace}/{function}")
@Produces(MediaType.APPLICATION_JSON)
@Operation(summary = "Execute 'get' method on a function")
@ApiResponses(value = {
        @ApiResponse(responseCode = "200",
                description = "Process and execute the function",
                content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))),
        @ApiResponse(responseCode = "500", description = serverErrorMessage)
})
public Response getExecuteFunction(@PathParam("namespace") final String namespace,
                                   @PathParam("function") final String function,
                                   @Context final HttpServletRequest request,
                                   @Context final HttpServletResponse response) {
    logger.info("executing '{}/{}' with get method", namespace, function);
    return doExecute(namespace, function, request, response);
}
 
Example #17
Source File: QueuedStatementResource.java    From presto with Apache License 2.0 6 votes vote down vote up
@ResourceSecurity(AUTHENTICATED_USER)
@POST
@Produces(APPLICATION_JSON)
public Response postStatement(
        String statement,
        @Context HttpServletRequest servletRequest,
        @Context HttpHeaders httpHeaders,
        @Context UriInfo uriInfo)
{
    if (isNullOrEmpty(statement)) {
        throw badRequest(BAD_REQUEST, "SQL statement is empty");
    }

    String remoteAddress = servletRequest.getRemoteAddr();
    Optional<Identity> identity = Optional.ofNullable((Identity) servletRequest.getAttribute(AUTHENTICATED_IDENTITY));
    MultivaluedMap<String, String> headers = httpHeaders.getRequestHeaders();

    SessionContext sessionContext = new HttpRequestSessionContext(headers, remoteAddress, identity, groupProvider);
    Query query = new Query(statement, sessionContext, dispatchManager);
    queries.put(query.getQueryId(), query);

    // let authentication filter know that identity lifecycle has been handed off
    servletRequest.setAttribute(AUTHENTICATED_IDENTITY, null);

    return Response.ok(query.getQueryResults(query.getLastToken(), uriInfo)).build();
}
 
Example #18
Source File: AppJointEntranceRestfulApi.java    From DataSphereStudio with Apache License 2.0 6 votes vote down vote up
/**
 * callback接口是为了接收外部系统进行回馈各种信息的接口,外部系统调用此接口必须提供的参数有entranceEngine的唯一标识,
 * 因为只有entranceEngine的唯一标识,才能进行定位到相应的job
 * jsonNode 是外部系统传递的参数,这些参数可以包含有日志,进度 和 状态等等
 */
@POST
@Path("/callback")
public Response callback(@Context HttpServletRequest request,
                         @Context HttpServletResponse response,
                         Map<String, Object> params) {
    Object appJointName = params.get(APPJOINT_NAME_STR);
    if(appJointName == null || StringUtils.isBlank(appJointName.toString())) {
        return error(APPJOINT_NAME_STR + "为空!");
    }
    AppJoint appJoint = AppJointManager.getAppJoint(appJointName.toString());
    if(appJoint == null) {
        return error("找不到AppJoint: " + appJointName);
    }
    NodeExecution nodeExecution = appJoint.getNodeExecution();
    if(!(nodeExecution instanceof CallbackLongTermNodeExecution)) {
        return error("找不到CallbackLongTermNodeExecution来处理该请求,实际NodeExecution为 " + nodeExecution.getClass().getSimpleName());
    }
    ((CallbackLongTermNodeExecution) nodeExecution).acceptCallback(params);
    Message message = Message.ok("处理成功!");
    message.setMethod(CALL_BACK_URL);
    return Message.messageToResponse(message);
}
 
Example #19
Source File: ProjectTaxonomyRestfulApi.java    From DataSphereStudio with Apache License 2.0 6 votes vote down vote up
@POST
@Path("/addProjectTaxonomy")
public Response addProjectTaxonomy(@Context HttpServletRequest req, JsonNode json) throws DSSErrorException {
    String userName = SecurityFilter.getLoginUsername(req);
    String name = json.get("name").getTextValue();
    String description = json.get("description").getTextValue();
    // TODO: 2019/5/16 空值校验,重复名校验
    DWSProjectTaxonomy dwsProjectTaxonomy = new DWSProjectTaxonomy();
    Date date = new Date();
    dwsProjectTaxonomy.setName(name);
    dwsProjectTaxonomy.setDescription(description);
    dwsProjectTaxonomy.setCreatorID(dwsUserService.getUserID(userName));
    dwsProjectTaxonomy.setCreateTime(date);
    dwsProjectTaxonomy.setUpdateTime(date);
    projectTaxonomyService.addProjectTaxonomy(dwsProjectTaxonomy);
    return Message.messageToResponse(Message.ok());
}
 
Example #20
Source File: ApplicationRestfulApi.java    From DataSphereStudio with Apache License 2.0 6 votes vote down vote up
@GET
@Path("getBaseInfo")
public Response getBaseInfo(@Context HttpServletRequest req){
    String username = SecurityFilter.getLoginUsername(req);
    applicationHandlerChain.handle(username);
    List<Application> applicationList = applicationService.listApplications();
    for (Application application : applicationList) {
        String redirectUrl = application.getRedirectUrl();
        if(redirectUrl != null) {
            application.setHomepageUrl(ApplicationUtils.redirectUrlFormat(redirectUrl,application.getHomepageUrl()));
            application.setProjectUrl(ApplicationUtils.redirectUrlFormat(redirectUrl,application.getProjectUrl()));
        }
    }
    DSSUser dssUser = dataworkisUserService.getUserByName(username);
    DSSUserVO dataworkisUserVO = new DSSUserVO();
    dataworkisUserVO.setBasic(dssUser);
    return Message.messageToResponse(Message.ok().data("applications",applicationList).data("userInfo",dataworkisUserVO));
}
 
Example #21
Source File: ExecutingStatementResource.java    From presto with Apache License 2.0 6 votes vote down vote up
@ResourceSecurity(PUBLIC)
@GET
@Path("{queryId}/{slug}/{token}")
@Produces(MediaType.APPLICATION_JSON)
public void getQueryResults(
        @PathParam("queryId") QueryId queryId,
        @PathParam("slug") String slug,
        @PathParam("token") long token,
        @QueryParam("maxWait") Duration maxWait,
        @QueryParam("targetResultSize") DataSize targetResultSize,
        @Context UriInfo uriInfo,
        @Suspended AsyncResponse asyncResponse)
{
    Query query = getQuery(queryId, slug, token);
    asyncQueryResults(query, token, maxWait, targetResultSize, uriInfo, asyncResponse);
}
 
Example #22
Source File: UiQueryResource.java    From presto with Apache License 2.0 6 votes vote down vote up
@ResourceSecurity(WEB_UI)
@GET
public List<BasicQueryInfo> getAllQueryInfo(@QueryParam("state") String stateFilter, @Context HttpServletRequest servletRequest, @Context HttpHeaders httpHeaders)
{
    QueryState expectedState = stateFilter == null ? null : QueryState.valueOf(stateFilter.toUpperCase(Locale.ENGLISH));

    List<BasicQueryInfo> queries = dispatchManager.getQueries();
    queries = filterQueries(extractAuthorizedIdentity(servletRequest, httpHeaders, accessControl, groupProvider), queries, accessControl);

    ImmutableList.Builder<BasicQueryInfo> builder = new ImmutableList.Builder<>();
    for (BasicQueryInfo queryInfo : queries) {
        if (stateFilter == null || queryInfo.getState() == expectedState) {
            builder.add(queryInfo);
        }
    }
    return builder.build();
}
 
Example #23
Source File: UiQueryResource.java    From presto with Apache License 2.0 6 votes vote down vote up
@ResourceSecurity(WEB_UI)
@GET
@Path("{queryId}")
public Response getQueryInfo(@PathParam("queryId") QueryId queryId, @Context HttpServletRequest servletRequest, @Context HttpHeaders httpHeaders)
{
    requireNonNull(queryId, "queryId is null");

    Optional<QueryInfo> queryInfo = dispatchManager.getFullQueryInfo(queryId);
    if (queryInfo.isPresent()) {
        try {
            checkCanViewQueryOwnedBy(extractAuthorizedIdentity(servletRequest, httpHeaders, accessControl, groupProvider), queryInfo.get().getSession().getUser(), accessControl);
            return Response.ok(queryInfo.get()).build();
        }
        catch (AccessDeniedException e) {
            throw new ForbiddenException();
        }
    }
    return Response.status(Status.GONE).build();
}
 
Example #24
Source File: LoginResource.java    From presto with Apache License 2.0 6 votes vote down vote up
@ResourceSecurity(WEB_UI)
@GET
@Path(UI_LOGOUT)
public Response logout(@Context HttpHeaders httpHeaders, @Context UriInfo uriInfo, @Context SecurityContext securityContext)
{
    URI redirectLocation;
    if (formWebUiAuthenticationManager.isAuthenticationEnabled(securityContext.isSecure())) {
        redirectLocation = LOGIN_FORM_URI;
    }
    else {
        redirectLocation = DISABLED_LOCATION_URI;
    }
    return Response.seeOther(redirectLocation)
            .cookie(getDeleteCookie(securityContext.isSecure()))
            .build();
}
 
Example #25
Source File: WorkerResource.java    From presto with Apache License 2.0 6 votes vote down vote up
@ResourceSecurity(WEB_UI)
@GET
@Path("{nodeId}/task/{taskId}")
public Response getThreads(
        @PathParam("taskId") final TaskId task,
        @PathParam("nodeId") String nodeId,
        @Context HttpServletRequest servletRequest,
        @Context HttpHeaders httpHeaders)
{
    QueryId queryId = task.getQueryId();
    Optional<QueryInfo> queryInfo = dispatchManager.getFullQueryInfo(queryId);
    if (queryInfo.isPresent()) {
        try {
            checkCanViewQueryOwnedBy(extractAuthorizedIdentity(servletRequest, httpHeaders, accessControl, groupProvider), queryInfo.get().getSession().getUser(), accessControl);
            return proxyJsonResponse(nodeId, "v1/task/" + task);
        }
        catch (AccessDeniedException e) {
            throw new ForbiddenException();
        }
    }
    return Response.status(Status.GONE).build();
}
 
Example #26
Source File: WebUiStaticResource.java    From presto with Apache License 2.0 6 votes vote down vote up
@ResourceSecurity(WEB_UI)
@GET
@Path("/ui/{path: .*}")
public Response getFile(@PathParam("path") String path, @Context ServletContext servletContext)
        throws IOException
{
    if (path.isEmpty()) {
        path = "index.html";
    }

    String fullPath = "/webapp/" + path;
    if (!isCanonical(fullPath)) {
        // consider redirecting to the absolute path
        return Response.status(NOT_FOUND).build();
    }

    URL resource = getClass().getResource(fullPath);
    if (resource == null) {
        return Response.status(NOT_FOUND).build();
    }

    return Response.ok(resource.openStream(), servletContext.getMimeType(resource.toString())).build();
}
 
Example #27
Source File: QueryResource.java    From presto with Apache License 2.0 6 votes vote down vote up
@ResourceSecurity(AUTHENTICATED_USER)
@GET
public List<BasicQueryInfo> getAllQueryInfo(@QueryParam("state") String stateFilter, @Context HttpServletRequest servletRequest, @Context HttpHeaders httpHeaders)
{
    QueryState expectedState = stateFilter == null ? null : QueryState.valueOf(stateFilter.toUpperCase(Locale.ENGLISH));

    List<BasicQueryInfo> queries = dispatchManager.getQueries();
    queries = filterQueries(extractAuthorizedIdentity(servletRequest, httpHeaders, accessControl, groupProvider), queries, accessControl);

    ImmutableList.Builder<BasicQueryInfo> builder = new ImmutableList.Builder<>();
    for (BasicQueryInfo queryInfo : queries) {
        if (stateFilter == null || queryInfo.getState() == expectedState) {
            builder.add(queryInfo);
        }
    }
    return builder.build();
}
 
Example #28
Source File: QueryResource.java    From presto with Apache License 2.0 6 votes vote down vote up
@ResourceSecurity(AUTHENTICATED_USER)
@DELETE
@Path("{queryId}")
public void cancelQuery(@PathParam("queryId") QueryId queryId, @Context HttpServletRequest servletRequest, @Context HttpHeaders httpHeaders)
{
    requireNonNull(queryId, "queryId is null");

    try {
        BasicQueryInfo queryInfo = dispatchManager.getQueryInfo(queryId);
        checkCanKillQueryOwnedBy(extractAuthorizedIdentity(servletRequest, httpHeaders, accessControl, groupProvider), queryInfo.getSession().getUser(), accessControl);
        dispatchManager.cancelQuery(queryId);
    }
    catch (AccessDeniedException e) {
        throw new ForbiddenException();
    }
    catch (NoSuchElementException ignored) {
    }
}
 
Example #29
Source File: FunctionsResource.java    From cantor with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@POST
@Path("/run/{namespace}/{function}")
@Produces(MediaType.APPLICATION_JSON)
@Operation(summary = "Execute post method on function query")
@ApiResponses(value = {
        @ApiResponse(responseCode = "200",
                description = "Process and execute the function",
                content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))),
        @ApiResponse(responseCode = "500", description = serverErrorMessage)
})
public Response postExecuteFunction(@PathParam("namespace") final String namespace,
                                    @PathParam("function") final String function,
                                    @Context final HttpServletRequest request,
                                    @Context final HttpServletResponse response) {
    logger.info("executing '{}/{}' with post method", namespace, function);
    return doExecute(namespace, function, request, response);
}
 
Example #30
Source File: FlowRestfulApi.java    From DataSphereStudio with Apache License 2.0 5 votes vote down vote up
@POST
@Path("/addFlow")
public Response addFlow(@Context HttpServletRequest req, JsonNode json) throws DSSErrorException {
    //如果是子工作流,那么分类应该是和父类一起的?
    String userName = SecurityFilter.getLoginUsername(req);
    // TODO: 2019/5/23 flowName工程名下唯一校验
    String name = json.get("name").getTextValue();
    String description = json.get("description") == null?null:json.get("description").getTextValue();
    Long parentFlowID = json.get("parentFlowID") ==null?null:json.get("parentFlowID").getLongValue();
    Long taxonomyID = json.get("taxonomyID") == null? null:json.get("taxonomyID").getLongValue();
    Long projectVersionID = json.get("projectVersionID").getLongValue();
    String uses = json.get("uses") == null?null:json.get("uses").getTextValue();
    if(taxonomyID == null && parentFlowID == null) throw new DSSErrorException(90009,"请求选择工作流分类");
    publishManager.checkeIsPublishing(projectVersionID);
    DWSFlow dwsFlow = new DWSFlow();
    dwsFlow.setProjectID(projectService.getProjectByProjectVersionID(projectVersionID).getId());
    dwsFlow.setName(name);
    dwsFlow.setDescription(description);
    dwsFlow.setCreatorID(dwsUserService.getUserID(userName));
    dwsFlow.setCreateTime(new Date());
    dwsFlow.setState(false);
    dwsFlow.setSource("create by user");
    dwsFlow.setUses(uses);
    if(parentFlowID == null){
        dwsFlow.setRootFlow(true);
        dwsFlow.setRank(0);
        dwsFlow.setHasSaved(true);
        dwsFlow = flowService.addRootFlow(dwsFlow,taxonomyID,projectVersionID);
    }else {
        dwsFlow.setRootFlow(false);
        Integer rank = flowService.getParentRank(parentFlowID);
        // TODO: 2019/6/3 并发问题考虑for update
        dwsFlow.setRank(rank+1);
        dwsFlow.setHasSaved(false);
        dwsFlow = flowService.addSubFlow(dwsFlow,parentFlowID,projectVersionID);
    }
    // TODO: 2019/5/16 空值校验,重复名校验
    return Message.messageToResponse(Message.ok().data("flow",dwsFlow));
}