Apioperation example

Apioperation example DEFAULT

Spring Boot + Swagger2- Understanding various Swagger annotations-

In previous post we configured a spring boot application to integrate swagger2.Various Swagger annotations are available to help document the REST APIs. Lets take a look at these. We will add these annotations to the sayHello() method we defined in the previous post.
  • @ApiOperation-

    This annotation is used to describe the exposed REST API. It describes an operation or typically a HTTP method against a specific path. It takes the following parameters-
    Annotation Parameter Description
    value The value of the annotation is a short description on the API. Since this is displayed in the list of operations in Swagger-UI and the location is limited in size, this should be kept short (preferably shorter than 120 characters)
    notes The notes allows you to give significantly more details about the operations (e.g. you can include request samples and responses here)
    nickname The nickname for this API.

    Spring Boot Swagger- Table of Contents

    Spring Boot + Swagger Example Hello World ExampleSpring Boot + Swagger- Understanding the various Swagger AnnotationsSpring Boot + Swagger + Profile - Implementing Spring Boot Profile for a Swagger applicationSpring Boot + Swagger 3 (OpenAPI 3) Hello World ExampleSpring Boot + Swagger 3 (OpenAPI 3) + Security Example The code will be as follows for the hello method- @ApiOperation(value = "getGreeting", notes="get greeting",nickname = "getGreeting") @RequestMapping(method = RequestMethod.GET, value = "/api/javainuse") public <Hello> sayHello() { ArrayList<Hello> arrayList= new ArrayList<>(); arrayList.add(new Hello()); return arrayList; }
  • @ApiResponses-

    This annotation is used to describe the expected responses for the REST API. The @ApiResponse describes a concrete possible response. It cannot be used directly on the method and needs to be included in the array value of @ApiResponses (whether there's one response or more). It takes the following parameters-
    Annotation Parameter Description
    ApiResponse The @ApiResponse describes a concrete possible response
    The code will be as follows for the hello method-
    @ApiOperation(value = "getGreeting", nickname = "getGreeting") @ApiResponses(value = { @ApiResponse(code = 500, message = "Server error"), @ApiResponse(code = 404, message = "Service not found"), @ApiResponse(code = 200, message = "Successful retrieval", response = Hello.class, responseContainer = "List") }) @RequestMapping(method = RequestMethod.GET, value = "/api/javainuse") public <Hello> sayHello() { ArrayList<Hello> arrayList= new ArrayList<>(); arrayList.add(new Hello()); return arrayList; } If the user has default response messages which are to be applied to all the REST APIs then these can be specified when defining the Docket bean. Hence these will not need to be applied at the method level. For example if the response for code 404 and 500 is going to be same through out all services
    @Bean public Docket postsApi() { Docket docket=new Docket(DocumentationType.SWAGGER_2); docket.groupName("public-api") .apiInfo(apiInfo()).select().paths(postPaths()).build(); docket.globalResponseMessage(RequestMethod.GET, ImmutableList.of(new ResponseMessageBuilder() .code(400) .message("Bad Request") .responseModel(new ModelRef("Error")).build(),new ResponseMessageBuilder() .code(500) .message("Internal Server Error") .responseModel(new ModelRef("Error")).build())); return docket;
  • @ApiParam-

    This annotation is used to describe the exposed REST API. It takes the following parameters-
    Annotation Parameter Description
    value The value is a short description of the parameter
    required If the parameter is optional or required.
    defaultValue Specify defaultValue of the parameter.
    The code will be as follows for the hello method- @ApiOperation(value = "getGreeting", nickname = "getGreeting") @ApiResponses(value = { @ApiResponse(code = 500, message = "Server error"), @ApiResponse(code = 200, message = "Successful retrieval", response = Hello.class, responseContainer = "List") }) @RequestMapping(method = RequestMethod.GET, value = "/api/javainuse") public List<Hello> sayHello(@ApiParam(value = "testId", required = true, defaultValue = "111") @PathVariable(ID) final int institutuionId) { return new Hello(); }
We get the Swagger UI as-

boot8_1

Understanding the Annotations for the model class-

The sayHello() method above is returning a list of Hello class. We can use annotations to define a default response that we expect-
  • @ApiModel-

    The @ApiModel allows you to manipulate the meta data of a model from a simple description or name change to a definition of polymorphism. We have used it to create a response class Hello with default values. It takes the following parameters-
    Annotation Parameter Description
    value The name displayed for the Model class
    description The description of the model class
  • @ApiModelProperty-

    The @ApiModelProperty allows controlling Swagger-specific definitions such as allowed values, and additional notes. It also offers additional filtering properties in case you want to hide the property in certain scenarios. We use this parameter for specifying default values to the Response model class Hello. It takes the following parameters-
    Annotation Parameter Description
    position The position of the field in the reponse class during display using swagger.
    value The value of the field when using Swagger. For example the default value of the path varaible will be 111 for class Hello.
    required If the field is optional or required.
package com.javainuse.swaggertest; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @ApiModel public class Hello { private int helloId; private String test; @ApiModelProperty(position = 1, required = true, value = "1") public int getHelloId() { return helloId; } public void setHelloId(int helloId) { this.helloId = helloId; } @ApiModelProperty(position = 2, required = true, value = "helloTest") public String getTest() { return test; } public void setTest(String test) { this.test = test; } }

Download Source Code

Download it -
Spring Boot + Swagger Annotations example

See Also

Spring Boot Hello World Application- Create simple controller and jsp view using MavenSpring Boot Hello World Application- Create simple controller and jsp view using GradleSpring Boot Tutorial-Spring Data JPASpring Boot + Simple Security ConfigurationPagination using Spring Boot Simple ExampleSpring Boot + ActiveMQ Hello world ExampleSpring Boot + Swagger Example Hello World ExampleSpring Boot Main MenuSpring Boot Interview Questions
Sours: https://www.javainuse.com

Java Code Examples for io.swagger.annotations.ApiOperation

The following examples show how to use io.swagger.annotations.ApiOperation. These examples are extracted from open source projects. 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

/** * @since 3.9.0 */ @GET @Path("oidc") @Produces(MediaType.APPLICATION_JSON) @ApiOperation( value = "Returns a list of all OIDC users", response = OidcUser.class, responseContainer = "List", responseHeaders = @ResponseHeader(name = TOTAL_COUNT_HEADER, response = Long.class, description = "The total number of OIDC users") ) @ApiResponses(value = { @ApiResponse(code = 401, message = "Unauthorized") }) @PermissionRequired(Permissions.Constants.ACCESS_MANAGEMENT) public Response getOidcUsers() { try (QueryManager qm = new QueryManager(getAlpineRequest())) { final long totalCount = qm.getCount(OidcUser.class); final List<OidcUser> users = qm.getOidcUsers(); return Response.ok(users).header(TOTAL_COUNT_HEADER, totalCount).build(); } }

Example 2

/** * Retrieve a stock for a given symbol. * http://localhost:9090/stockquote/IBM * * @param symbol Stock symbol will be taken from the path parameter. * @return Response */ @GET @Path("/{symbol}") @Produces({"application/json", "text/xml"}) @ApiOperation( value = "Return stock quote corresponding to the symbol", notes = "Returns HTTP 404 if the symbol is not found") @ApiResponses(value = { @ApiResponse(code = 200, message = "Valid stock item found"), @ApiResponse(code = 404, message = "Stock item not found")}) public Response getQuote(@ApiParam(value = "Symbol", required = true) @PathParam("symbol") String symbol) throws SymbolNotFoundException { Stock stock = stockQuotes.get(symbol); if (stock == null) { throw new SymbolNotFoundException("Symbol " + symbol + " not found"); } return Response.ok().entity(stock).cookie(new NewCookie("symbol", symbol)).build(); }

Example 3

@ApiOperation(value = "Delete a deployment", tags = { "Deployment" }) @ApiResponses(value = { @ApiResponse(code = 204, message = "Indicates the deployment was found and has been deleted. Response-body is intentionally empty."), @ApiResponse(code = 404, message = "Indicates the requested deployment was not found.") }) @DeleteMapping(value = "/repository/deployments/{deploymentId}", produces = "application/json") public void deleteDeployment(@ApiParam(name = "deploymentId") @PathVariable String deploymentId, @RequestParam(value = "cascade", required = false, defaultValue = "false") Boolean cascade, HttpServletResponse response) { Deployment deployment = repositoryService.createDeploymentQuery().deploymentId(deploymentId).singleResult(); if (deployment == null) { throw new FlowableObjectNotFoundException("Could not find a deployment with id '" + deploymentId + "'.", Deployment.class); } if (restApiInterceptor != null) { restApiInterceptor.deleteDeployment(deployment); } if (cascade) { repositoryService.deleteDeployment(deploymentId, true); } else { repositoryService.deleteDeployment(deploymentId); } response.setStatus(HttpStatus.NO_CONTENT.value()); }

Example 4

/** * 上传文件. * * @param request the request * @param optUploadFileReqDto the opt upload file req dto * * @return the wrapper */ @PostMapping(consumes = "multipart/form-data", value = "/uploadFile") @ApiOperation(httpMethod = "POST", value = "上传文件") public Wrapper<String> uploadFile(HttpServletRequest request, OptUploadFileReqDto optUploadFileReqDto) { StringBuilder temp = new StringBuilder(); logger.info("uploadFile - 上传文件. optUploadFileReqDto={}", optUploadFileReqDto); Preconditions.checkArgument(StringUtils.isNotEmpty(optUploadFileReqDto.getFileType()), "文件类型为空"); Preconditions.checkArgument(StringUtils.isNotEmpty(optUploadFileReqDto.getBucketName()), "存储地址为空"); MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; List<OptUploadFileRespDto> optUploadFileRespDtos = optAttachmentService.uploadFile(multipartRequest, optUploadFileReqDto, getLoginAuthDto(), true); for (final OptUploadFileRespDto fileRespDto : optUploadFileRespDtos) { temp.append(fileRespDto.getAttachmentId()).append(","); } String attachmentIds = temp.toString(); if (StringUtils.isNotEmpty(attachmentIds)) { attachmentIds = StringUtils.substringBeforeLast(attachmentIds, GlobalConstant.Symbol.COMMA); } return WrapMapper.ok(attachmentIds); }

Example 5

@PUT @Path("/{id}/files/{referenceUid}/formdata") @Consumes({ MediaType.APPLICATION_FORM_URLENCODED }) @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) @ApiOperation(value = "update DossierFile") @ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Returns"), @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized", response = ExceptionModel.class), @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found", response = ExceptionModel.class), @ApiResponse(code = HttpURLConnection.HTTP_FORBIDDEN, message = "Access denied", response = ExceptionModel.class) }) public Response updateDossierFileFormData( @Context HttpServletRequest request, @Context HttpHeaders header, @Context Company company, @Context Locale locale, @Context User user, @Context ServiceContext serviceContext, @ApiParam(value = "id of dossier", required = true) @PathParam("id") long id, @ApiParam(value = "referenceUid of dossierfile", required = true) @PathParam("referenceUid") String referenceUid, @ApiParam(value = "formdata of dossierfile", required = true) @FormParam("formdata") String formdata);

Example 6

@GET @Path("/shop/{id}/item") @Permission({"vshop", "item", "list"}) @ApiOperation( value = "List Shop Items", notes = "Return a list of all shops items") public Collection<CachedStockItem> listShopItems(@PathParam("id") UUID id) { return WebAPI.runOnMain(() -> { Optional<NPCguard> npc = VillagerShops.getNPCfromShopUUID(id); if (!npc.isPresent()) { throw new NotFoundException("Shop with id " + id + " not found"); } InvPrep inv = npc.get().getPreparator(); int s = inv.size(); List<CachedStockItem> csi = new ArrayList<>(s); for (int i = 0; i < s; i++) csi.add(new CachedStockItem(inv.getItem(i), i, npc.get().getIdentifier())); return csi; }); }

Example 7

/** * 检测权限编码是否已存在 * * @param uacActionCheckCodeDto the uac action check code dto * * @return the wrapper */ @PostMapping(value = "/checkActionCode") @ApiOperation(httpMethod = "POST", value = "检测权限编码是否已存在") public Wrapper<Boolean> checkActionCode(@ApiParam(name = "uacActionCheckCodeDto", value = "id与url") @RequestBody UacActionCheckCodeDto uacActionCheckCodeDto) { logger.info("校验权限编码唯一性 uacActionCheckCodeDto={}", uacActionCheckCodeDto); Long id = uacActionCheckCodeDto.getActionId(); String actionCode = uacActionCheckCodeDto.getActionCode(); Example example = new Example(UacAction.class); Example.Criteria criteria = example.createCriteria(); if (id != null) { criteria.andNotEqualTo("id", id); } criteria.andEqualTo("actionCode", actionCode); int result = uacActionService.selectCountByExample(example); return WrapMapper.ok(result < 1); }

Example 8

@ApiOperation( value = "Get applications", notes = "Gets the list of applications using the file", response = Application.class, responseContainer = "List" ) @GET @Path("/apps/{url}") @Produces(MediaType.APPLICATION_JSON) public Response getApplicationsForFile(@PathParam("url") @ApiParam("An URL referencing the file") String url) { try { String decodedUrl = URLDecoder.decode(url, "UTF-8"); return Response.OK(this.applicationDAO.getAllApplicationsByUrl(decodedUrl)); } catch (Exception e) { logger.error("Unexpected error when getting the list of applications by URL", e); return Response.INTERNAL_ERROR(); } }

Example 9

@ApiOperation( value = "Create or update plugin settings rule", notes = "Creates a new plugin settings rule record (if id is not provided) or updates existing one otherwise", authorizations = {@Authorization("Bearer Token")} ) @PUT @Path("/private/rule") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response saveSettingsRule(String ruleJSON) { try { ObjectMapper mapper = new ObjectMapper(); DeviceLogRule rule = mapper.readValue(ruleJSON, this.settingsDAO.getSettingsRuleClass()); this.settingsDAO.savePluginSettingsRule(rule); notifyRuleDevices(rule); return Response.OK(); } catch (Exception e) { log.error("Failed to create or update device log plugin settings rule", e); return Response.INTERNAL_ERROR(); } }

Example 10

@ApiOperation( value = "Create a classification with the current user", response = ClassificationDto.class, httpMethod = "POST", notes = "Returns an instance of created classification Template." ) @POST public Response createClassification(ClassificationDto c) { if (c == null) { return Response.status(400).type("text/plain").entity("A required query parameter was not specified for this request.").build(); } Classification element = classificationLogic.createClassification(mapper.map(c, Classification.class)); boolean succeed = (element != null); if (succeed) { return Response.ok().entity(mapper.map(element, ClassificationDto.class)).build(); } else { return Response.status(500).type("text/plain").entity("Classification creation failed.").build(); } }

Example 11

@ApiOperation(value = "修改密码") @PutMapping("/change_password") public ResponseEntity<?> changePassword( @ApiParam("旧密码") @RequestParam("oldPassword") String oldPassword, @ApiParam("新密码") @RequestParam("newPassword") String newPassword ) { OAuth2Authentication auth = (OAuth2Authentication) SecurityContextHolder.getContext().getAuthentication(); Optional<User> user = userService.selectByID(((SecurityUser) auth.getPrincipal()).getId()); BCryptPasswordEncoder encoder = new BCryptPasswordEncoder(); if (user.isPresent() && encoder.matches(oldPassword, user.get().getPassword())) { User instance = user.get(); instance.setPassword(newPassword); userService.modifyById(instance); return ResponseEntity.status(HttpStatus.OK).build(); } else { return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build(); } }

Example 12

@PUT @RolesAllowed({ Role.USER, Role.ADMIN }) @Path("/{thingUID}/enable") @ApiOperation(value = "Sets the thing enabled status.") @ApiResponses(value = { @ApiResponse(code = 200, message = "OK", response = String.class), @ApiResponse(code = 404, message = "Thing not found.") }) public Response setEnabled(@HeaderParam(HttpHeaders.ACCEPT_LANGUAGE) String language, @PathParam("thingUID") @ApiParam(value = "thing") String thingUID, @ApiParam(value = "enabled") String enabled) throws IOException { final Locale locale = localeService.getLocale(language); ThingUID thingUIDObject = new ThingUID(thingUID); // Check if the Thing exists, 404 if not Thing thing = thingRegistry.get(thingUIDObject); if (null == thing) { logger.info("Received HTTP PUT request for set enabled at '{}' for the unknown thing '{}'.", uriInfo.getPath(), thingUID); return getThingNotFoundResponse(thingUID); } thingManager.setEnabled(thingUIDObject, Boolean.valueOf(enabled)); // everything went well return getThingResponse(Status.OK, thing, locale, null); }

Example 13

@DELETE @ApiOperation(value = "Delete a scope", notes = "User must have the DOMAIN_SCOPE[DELETE] permission on the specified domain " + "or DOMAIN_SCOPE[DELETE] permission on the specified environment " + "or DOMAIN_SCOPE[DELETE] permission on the specified organization") @ApiResponses({ @ApiResponse(code = 204, message = "Scope successfully deleted"), @ApiResponse(code = 500, message = "Internal server error")}) public void delete( @PathParam("organizationId") String organizationId, @PathParam("environmentId") String environmentId, @PathParam("domain") String domain, @PathParam("scope") String scope, @Suspended final AsyncResponse response) { final User authenticatedUser = getAuthenticatedUser(); checkAnyPermission(organizationId, environmentId, domain, Permission.DOMAIN_SCOPE, Acl.DELETE) .andThen(scopeService.delete(scope, false, authenticatedUser)) .subscribe(() -> response.resume(Response.noContent().build()), response::resume); }

Example 14

@ApiOperation( value = "Copy configuration", notes = "Creates a new copy of configuration referenced by the id and names it with provided name." ) @PUT @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Path("/copy") public Response copyConfiguration(Configuration configuration) { Configuration dbConfiguration = this.configurationDAO.getConfigurationByName(configuration.getName()); if (dbConfiguration != null) { return Response.DUPLICATE_ENTITY("error.duplicate.configuration"); } else { dbConfiguration = this.getConfiguration(configuration.getId()); List<Application> configurationApplications = this.configurationDAO.getPlainConfigurationApplications(configuration.getId()); Configuration copy = dbConfiguration.newCopy(); copy.setName(configuration.getName()); copy.setApplications(configurationApplications); copy.setBaseUrl(this.configurationDAO.getBaseUrl()); this.configurationDAO.insertConfiguration(copy); return Response.OK(); } }

Example 15

@POST @Path("/{property}/{cluster}/{namespace}/clearBacklog") @ApiOperation(hidden = true, value = "Clear backlog for all topics on a namespace.") @ApiResponses(value = { @ApiResponse(code = 403, message = "Don't have admin permission"), @ApiResponse(code = 404, message = "Namespace does not exist") }) public void clearNamespaceBacklog(@Suspended final AsyncResponse asyncResponse, @PathParam("property") String property, @PathParam("cluster") String cluster, @PathParam("namespace") String namespace, @QueryParam("authoritative") @DefaultValue("false") boolean authoritative) { try { validateNamespaceName(property, cluster, namespace); internalClearNamespaceBacklog(asyncResponse, authoritative); } catch (WebApplicationException wae) { asyncResponse.resume(wae); } catch (Exception e) { asyncResponse.resume(new RestException(e)); } }

Example 16

@PUT @ApiOperation("Update attributes of a task") @Path("/tasks/{taskId}/attributes") public Response updateTaskAttributes(@PathParam("taskId") String taskId, TaskAttributesUpdate request) { TaskAttributesUpdate sanitizedRequest; if (request.getTaskId().isEmpty()) { sanitizedRequest = request.toBuilder().setTaskId(taskId).build(); } else { if (!taskId.equals(request.getTaskId())) { return Response.status(Response.Status.BAD_REQUEST).build(); } sanitizedRequest = request; } return Responses.fromCompletable(jobServiceGateway.updateTaskAttributes(sanitizedRequest, resolveCallMetadata())); }

Example 17

@POST @Path("/{name}") @Timed @RequiresAuthentication @RequiresPermissions(ReportScheduleRestPermissions.AGGREGATE_REPORT_SCHEDULES_UPDATE) @AuditEvent(type = AuditEventTypes.AGGREGATES_REPORT_SCHEDULE_UPDATE) @ApiOperation(value = "Update a report schedule") @ApiResponses(value = { @ApiResponse(code = 400, message = "The supplied request is not valid.") }) public Response update(@ApiParam(name = "name", required = true) @PathParam("name") String name, @ApiParam(name = "JSON body", required = true) @Valid @NotNull UpdateReportScheduleRequest request ) throws UnsupportedEncodingException { final ReportSchedule reportSchedule = reportScheduleService.fromRequest(request); reportScheduleService.update(java.net.URLDecoder.decode(name, "UTF-8"), reportSchedule); return Response.accepted().build(); }

Example 18

@PutMapping(path = "/{deviceGuid}/application") @ApiOperation(value = "Move device to another application") @PreAuthorize("hasAuthority('EDIT_DEVICE')") public DeviceVO move( @PathVariable("application") String applicationId, @PathVariable("deviceGuid") String deviceGuid, @ApiParam(name = "body", required = true) @RequestBody ApplicationDestinationVO applicationDestinationVO) throws BadServiceResponseException, NotFoundResponseException { Tenant tenant = user.getTenant(); Application application = getApplication(applicationId); Application destApplication = getApplication(applicationDestinationVO.getDestinationApplicationName()); ServiceResponse<Device> deviceResponse = deviceRegisterService.move(tenant, application, deviceGuid, destApplication); if (!deviceResponse.isOk()) { throw new BadServiceResponseException( deviceResponse, validationsCode); } return new DeviceVO().apply(deviceResponse.getResult()); }

Example 19

@Path("/pipeline/{pipelineId}/metadata") @POST @ApiOperation(value ="", hidden = true) @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @RolesAllowed({ AuthzRole.CREATOR, AuthzRole.ADMIN, AuthzRole.CREATOR_REMOTE, AuthzRole.ADMIN_REMOTE }) @SuppressWarnings("unchecked") public Response saveMetadata( @PathParam("pipelineId") String name, @QueryParam("rev") @DefaultValue("0") String rev, Map<String, Object> metadata ) throws PipelineException { PipelineInfo pipelineInfo = store.getInfo(name); RestAPIUtils.injectPipelineInMDC(pipelineInfo.getTitle(), pipelineInfo.getPipelineId()); store.saveMetadata(user, name, rev, metadata); return Response.ok().build(); }

Example 20

/** * 恢复定时任务信息 */ @ApiOperation(value = "恢复定时任务信息", notes = "恢复定时任务信息") @ApiImplicitParam(paramType = "query", name = "jobIds", value = "主键ID数组", dataType = "Integer", required = true, allowMultiple = true) @PostMapping("/resume") @RequiresPermissions("sys/schedule/resume") public CommonResult resume(@RequestBody Long[] jobIds) { scheduleJobService.resume(jobIds); return CommonResult.success(""); }

Example 21

@ApiOperation(value = "统计各科室每日接待患者人数(近7日)") @RequestMapping(value = "/deptPatients", method = RequestMethod.GET) @ResponseBody public CommonResult<SmsPatientsStatisticsResult> deptPatients(Long deptId) { SmsPatientsStatisticsResult smsPatientsStatisticsResult = smsEchartsService.deptPatients(deptId); return CommonResult.success(smsPatientsStatisticsResult); }

Example 22

@POST @Path("/{property}/{cluster}/{namespace}/maxProducersPerTopic") @ApiOperation(value = " Set maxProducersPerTopic configuration on a namespace.") @ApiResponses(value = { @ApiResponse(code = 403, message = "Don't have admin permission"), @ApiResponse(code = 404, message = "Namespace does not exist"), @ApiResponse(code = 409, message = "Concurrent modification"), @ApiResponse(code = 412, message = "maxProducersPerTopic value is not valid") }) public void setMaxProducersPerTopic(@PathParam("property") String property, @PathParam("cluster") String cluster, @PathParam("namespace") String namespace, int maxProducersPerTopic) { validateNamespaceName(property, cluster, namespace); internalSetMaxProducersPerTopic(maxProducersPerTopic); }

Example 23

@ApiOperation(value="删除文件", notes="删除文件") @RequestMapping(value = "/file", method = RequestMethod.POST) public boolean removeFile( @ApiParam(value = "文件服务器存放路径") @RequestParam("filePath") String filePath, @ApiParam(value = "删除标示,0:本文件,1:整个文件目录") @RequestParam("flag") int flag ) throws ServiceException { return removeService.removeFile(filePath,flag); }

Example 24

/** * 批量推送配置 * * @param body * @return */ @RequestMapping(value = "/batchPush", method = RequestMethod.POST) @ApiOperation("批量推送") public Response<PushServiceConfigResponseBody> batchPush(@RequestBody BatchPushServiceConfigRequestBody body) { List<String> configIds = body.getIds(); if (null == configIds || configIds.isEmpty()) { return new Response<>(SystemErrCode.ERRCODE_INVALID_PARAMETER, SystemErrCode.ERRMSG_SERVICE_CONFIG_IDS_NOT_NULL); } List<String> ids = body.getRegionIds(); if (null == ids || ids.isEmpty()) { return new Response<>(SystemErrCode.ERRCODE_INVALID_PARAMETER, SystemErrCode.ERRMSG_REGION_IDS_NOT_NULL); } return this.serviceConfigImpl.batchPush(body); }

Example 25

/** * 资源下载 * * @param response {@link HttpServletResponse} */ @ApiOperation(value = "通过访问路径获取文件资源") @AuthInterceptor(InterceptorLevel.NONE) @RequestMapping(value = "/**", method = RequestMethod.GET) public void getResource(HttpServletResponse response) throws IOException { ControllerUtils.loadResource(response, fileService.getResource(request.getServletPath(), request), ValueConsts.FALSE); }

Example 26

@ApiOperation("添加权限") @RequestMapping(value = "/create", method = RequestMethod.POST) @ResponseBody public CommonResult create(@RequestBody UmsPermission permission) { int count = permissionService.create(permission); if(count>0){ return CommonResult.success(count); } return CommonResult.failed(); }

Example 27

/** * 批量删除数据 * * @return */ @ApiOperation(value = "批量删除数据", notes = "批量删除数据") @ApiImplicitParams({ @ApiImplicitParam(name = "id", required = true, value = "id", paramType = "form") }) @PostMapping("/batch/remove") public ResultBody batchRemove( @RequestParam(value = "ids") String ids ) { targetService.removeByIds(Arrays.asList(ids.split(","))); return ResultBody.ok(); }

Example 28

@ApiOperation("获取指定订单设置") @RequestMapping(value = "/{id}", method = RequestMethod.GET) @ResponseBody public CommonResult<OmsOrderSetting> getItem(@PathVariable Long id) { OmsOrderSetting orderSetting = orderSettingService.getItem(id); return CommonResult.success(orderSetting); }

Example 29

@ApiOperation("批量删除订单") @RequestMapping(value = "/delete", method = RequestMethod.POST) @ResponseBody public CommonResult delete(@RequestParam("ids") List<Long> ids) { int count = orderService.delete(ids); if (count > 0) { return CommonResult.success(count); } return CommonResult.failed(); }

Example 30

/** * API to get all user roles mappings details * * @author Nidhish * @param page - zero-based page index. * @param size - the size of the page to be returned. * @param searchTerm - searchTerm to be searched. * @return All UserRolesMapping Details */ @ApiOperation(httpMethod = "GET", value = "API to get all user roles mappings details", response = Response.class, produces = MediaType.APPLICATION_JSON_VALUE) @RequestMapping(path = "/list", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<Object> getAllUserRolesMapping( @ApiParam(value = "provide valid page number", required = true) @RequestParam("page") Integer page, @ApiParam(value = "provide valid page size", required = true) @RequestParam("size") Integer size, @ApiParam(value = "provide valid search term", required = false) @RequestParam(defaultValue="", name = "searchTerm", required = false) String searchTerm) { try { return ResponseUtils.buildSucessResponse(userRolesMappingService.getAllUserRolesMapping(searchTerm.trim(), page, size)); } catch (Exception exception) { log.error(UNEXPECTED_ERROR_OCCURRED, exception); return ResponseUtils.buildFailureResponse(new Exception(UNEXPECTED_ERROR_OCCURRED), exception.getMessage()); } }
Sours: https://www.programcreek.com/java-api-examples/?api=io.swagger.annotations.ApiOperation
  1. React js rest client
  2. Golden doodles oklahoma
  3. Reddit trees
  4. Left airpod replacement
  5. From time piano tutorial

Java Code Examples for com.wordnik.swagger.annotations.ApiOperation

The following examples show how to use com.wordnik.swagger.annotations.ApiOperation. These examples are extracted from open source projects. 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

/** * Retrieves the access configuration for this NiFi. * * @param httpServletRequest the servlet request * @return A accessConfigurationEntity */ @GET @Consumes(MediaType.WILDCARD) @Produces(MediaType.APPLICATION_JSON) @Path("config") @ApiOperation( value = "Retrieves the access configuration for this NiFi", response = AccessConfigurationEntity.class ) public Response getLoginConfig(@Context HttpServletRequest httpServletRequest) { final AccessConfigurationDTO accessConfiguration = new AccessConfigurationDTO(); // specify whether login should be supported and only support for secure requests accessConfiguration.setSupportsLogin(loginIdentityProvider != null && httpServletRequest.isSecure()); // create the response entity final AccessConfigurationEntity entity = new AccessConfigurationEntity(); entity.setConfig(accessConfiguration); // generate the response return clusterContext(generateOkResponse(entity)).build(); }

Example 2

@GET @Consumes(MediaType.WILDCARD) @Produces(MediaType.TEXT_PLAIN) @Path("client-id") @ApiOperation( value = "Generates a client id.", response = String.class, authorizations = { @Authorization(value = "Read - /flow", type = "") } ) @ApiResponses( value = { @ApiResponse(code = 400, message = "NiFi was unable to complete the request because it was invalid. The request should not be retried without modification."), @ApiResponse(code = 401, message = "Client could not be authenticated."), @ApiResponse(code = 403, message = "Client is not authorized to make this request."), @ApiResponse(code = 409, message = "The request was valid but NiFi was not in the appropriate state to process it. Retrying the same request later may be successful.") } ) public Response generateClientId() { authorizeFlow(); return clusterContext(generateOkResponse(generateUuid())).build(); }

Example 3

/** * Retrieves the specified remote process groups status history. * * @param groupId The group id * @return A processorEntity. * @throws InterruptedException if interrupted */ @GET @Consumes(MediaType.WILDCARD) @Produces(MediaType.APPLICATION_JSON) @Path("process-groups/{id}/status/history") @ApiOperation( value = "Gets status history for a remote process group", response = StatusHistoryEntity.class, authorizations = { @Authorization(value = "Read - /flow", type = "") } ) @ApiResponses( value = { @ApiResponse(code = 400, message = "NiFi was unable to complete the request because it was invalid. The request should not be retried without modification."), @ApiResponse(code = 401, message = "Client could not be authenticated."), @ApiResponse(code = 403, message = "Client is not authorized to make this request."), @ApiResponse(code = 404, message = "The specified resource could not be found."), @ApiResponse(code = 409, message = "The request was valid but NiFi was not in the appropriate state to process it. Retrying the same request later may be successful.") } ) public Response getProcessGroupStatusHistory( @ApiParam( value = "The process group id.", required = true ) @PathParam("id") String groupId) throws InterruptedException { authorizeFlow(); // replicate if cluster manager if (isReplicateRequest()) { return replicate(HttpMethod.GET); } // get the specified processor status history final StatusHistoryEntity entity = serviceFacade.getProcessGroupStatusHistory(groupId); return clusterContext(generateOkResponse(entity)).build(); }

Example 4

/** * Retrieves the specified processor status history. * * @param id The id of the processor history to retrieve. * @return A statusHistoryEntity. * @throws InterruptedException if interrupted */ @GET @Consumes(MediaType.WILDCARD) @Produces(MediaType.APPLICATION_JSON) @Path("processors/{id}/status/history") @ApiOperation( value = "Gets status history for a processor", response = StatusHistoryEntity.class, authorizations = { @Authorization(value = "Read - /flow", type = "") } ) @ApiResponses( value = { @ApiResponse(code = 400, message = "NiFi was unable to complete the request because it was invalid. The request should not be retried without modification."), @ApiResponse(code = 401, message = "Client could not be authenticated."), @ApiResponse(code = 403, message = "Client is not authorized to make this request."), @ApiResponse(code = 404, message = "The specified resource could not be found."), @ApiResponse(code = 409, message = "The request was valid but NiFi was not in the appropriate state to process it. Retrying the same request later may be successful.") } ) public Response getProcessorStatusHistory( @ApiParam( value = "The processor id.", required = true ) @PathParam("id") String id) throws InterruptedException { authorizeFlow(); // replicate if cluster manager if (isReplicateRequest()) { return replicate(HttpMethod.GET); } // get the specified processor status history final StatusHistoryEntity entity = serviceFacade.getProcessorStatusHistory(id); return clusterContext(generateOkResponse(entity)).build(); }

Example 5

/** * Retrieves the configuration for this NiFi. * * @return A controllerConfigurationEntity. */ @GET @Consumes(MediaType.WILDCARD) @Produces(MediaType.APPLICATION_JSON) @Path("config") @ApiOperation( value = "Retrieves the configuration for this NiFi Controller", response = ControllerConfigurationEntity.class, authorizations = { @Authorization(value = "Read - /controller", type = "") } ) @ApiResponses( value = { @ApiResponse(code = 400, message = "NiFi was unable to complete the request because it was invalid. The request should not be retried without modification."), @ApiResponse(code = 401, message = "Client could not be authenticated."), @ApiResponse(code = 403, message = "Client is not authorized to make this request."), @ApiResponse(code = 409, message = "The request was valid but NiFi was not in the appropriate state to process it. Retrying the same request later may be successful.") } ) public Response getControllerConfig() { authorizeController(RequestAction.READ); if (isReplicateRequest()) { return replicate(HttpMethod.GET); } final ControllerConfigurationEntity entity = serviceFacade.getControllerConfiguration(); return clusterContext(generateOkResponse(entity)).build(); }

Example 6

/** * Creates a single use access token for downloading FlowFile content. * * @param httpServletRequest the servlet request * @return A token (string) */ @POST @Consumes(MediaType.APPLICATION_FORM_URLENCODED) @Produces(MediaType.TEXT_PLAIN) @Path("/download-token") @ApiOperation( value = "Creates a single use access token for downloading FlowFile content.", notes = "The token returned is a base64 encoded string. It is valid for a single request up to five minutes from being issued. " + "It is used as a query parameter name 'access_token'.", response = String.class ) @ApiResponses( value = { @ApiResponse(code = 403, message = "Client is not authorized to make this request."), @ApiResponse(code = 409, message = "Unable to create the download token because NiFi is not in the appropriate state. " + "(i.e. may not have any tokens to grant or be configured to support username/password login)"), @ApiResponse(code = 500, message = "Unable to create download token because an unexpected error occurred.") } ) public Response createDownloadToken(@Context HttpServletRequest httpServletRequest) { // only support access tokens when communicating over HTTPS if (!httpServletRequest.isSecure()) { throw new IllegalStateException("Download tokens are only issued over HTTPS."); } final NiFiUser user = NiFiUserUtils.getNiFiUser(); if (user == null) { throw new AccessDeniedException("No user authenticated in the request."); } final OtpAuthenticationToken authenticationToken = new OtpAuthenticationToken(user.getIdentity()); // generate otp for response final String token = otpService.generateDownloadToken(authenticationToken); // build the response final URI uri = URI.create(generateResourceUri("access", "download-token")); return generateCreatedResponse(uri, token).build(); }

Example 7

/** * Creates a single use access token for accessing a NiFi UI extension. * * @param httpServletRequest the servlet request * @return A token (string) */ @POST @Consumes(MediaType.APPLICATION_FORM_URLENCODED) @Produces(MediaType.TEXT_PLAIN) @Path("/ui-extension-token") @ApiOperation( value = "Creates a single use access token for accessing a NiFi UI extension.", notes = "The token returned is a base64 encoded string. It is valid for a single request up to five minutes from being issued. " + "It is used as a query parameter name 'access_token'.", response = String.class ) @ApiResponses( value = { @ApiResponse(code = 403, message = "Client is not authorized to make this request."), @ApiResponse(code = 409, message = "Unable to create the download token because NiFi is not in the appropriate state. " + "(i.e. may not have any tokens to grant or be configured to support username/password login)"), @ApiResponse(code = 500, message = "Unable to create download token because an unexpected error occurred.") } ) public Response createUiExtensionToken(@Context HttpServletRequest httpServletRequest) { // only support access tokens when communicating over HTTPS if (!httpServletRequest.isSecure()) { throw new IllegalStateException("UI extension access tokens are only issued over HTTPS."); } final NiFiUser user = NiFiUserUtils.getNiFiUser(); if (user == null) { throw new AccessDeniedException("No user authenticated in the request."); } final OtpAuthenticationToken authenticationToken = new OtpAuthenticationToken(user.getIdentity()); // generate otp for response final String token = otpService.generateUiExtensionToken(authenticationToken); // build the response final URI uri = URI.create(generateResourceUri("access", "ui-extension-token")); return generateCreatedResponse(uri, token).build(); }

Example 8

/** * Gets the available resources that support access/authorization policies. * * @return A resourcesEntity. */ @GET @Consumes(MediaType.WILDCARD) @Produces(MediaType.APPLICATION_JSON) @ApiOperation( value = "Gets the available resources that support access/authorization policies", response = ResourcesEntity.class, authorizations = { @Authorization(value = "Read - /resources", type = "") } ) @ApiResponses( value = { @ApiResponse(code = 401, message = "Client could not be authenticated."), @ApiResponse(code = 403, message = "Client is not authorized to make this request."),} ) public Response getResources() { authorizeResource(); if (isReplicateRequest()) { return replicate(HttpMethod.GET); } final List<ResourceDTO> resources = serviceFacade.getResources(); // create the response final ResourcesEntity entity = new ResourcesEntity(); entity.setResources(resources); // generate the response return clusterContext(generateOkResponse(entity)).build(); }

Example 9

/** * Retrieves the specified connection status history. * * @param id The id of the connection to retrieve. * @return A statusHistoryEntity. * @throws InterruptedException if interrupted */ @GET @Consumes(MediaType.WILDCARD) @Produces(MediaType.APPLICATION_JSON) @Path("connections/{id}/status/history") @ApiOperation( value = "Gets the status history for a connection", response = StatusHistoryEntity.class, authorizations = { @Authorization(value = "Read - /flow", type = "") } ) @ApiResponses( value = { @ApiResponse(code = 400, message = "NiFi was unable to complete the request because it was invalid. The request should not be retried without modification."), @ApiResponse(code = 401, message = "Client could not be authenticated."), @ApiResponse(code = 403, message = "Client is not authorized to make this request."), @ApiResponse(code = 404, message = "The specified resource could not be found."), @ApiResponse(code = 409, message = "The request was valid but NiFi was not in the appropriate state to process it. Retrying the same request later may be successful.") } ) public Response getConnectionStatusHistory( @ApiParam( value = "The connection id.", required = true ) @PathParam("id") String id) throws InterruptedException { authorizeFlow(); // replicate if cluster manager if (isReplicateRequest()) { return replicate(HttpMethod.GET); } // get the specified processor status history final StatusHistoryEntity entity = serviceFacade.getConnectionStatusHistory(id); return clusterContext(generateOkResponse(entity)).build(); }

Example 10

/** * Retrieves the contents of the specified group. * * @param groupId The id of the process group. * @return A processGroupEntity. * @throws InterruptedException if interrupted */ @GET @Consumes(MediaType.WILDCARD) @Produces(MediaType.APPLICATION_JSON) @Path("process-groups/{id}") @ApiOperation( value = "Gets a process group", response = ProcessGroupFlowEntity.class, authorizations = { @Authorization(value = "Read - /flow", type = "") } ) @ApiResponses( value = { @ApiResponse(code = 400, message = "NiFi was unable to complete the request because it was invalid. The request should not be retried without modification."), @ApiResponse(code = 401, message = "Client could not be authenticated."), @ApiResponse(code = 403, message = "Client is not authorized to make this request."), @ApiResponse(code = 404, message = "The specified resource could not be found."), @ApiResponse(code = 409, message = "The request was valid but NiFi was not in the appropriate state to process it. Retrying the same request later may be successful.") } ) public Response getFlow( @ApiParam( value = "The process group id.", required = false ) @PathParam("id") String groupId) throws InterruptedException { authorizeFlow(); if (isReplicateRequest()) { return replicate(HttpMethod.GET); } // get this process group flow final ProcessGroupFlowEntity entity = serviceFacade.getProcessGroupFlow(groupId); populateRemainingFlowContent(entity.getProcessGroupFlow()); return clusterContext(generateOkResponse(entity)).build(); }

Example 11

/** * Retrieves all the of controller services in this NiFi. * * @return A controllerServicesEntity. */ @GET @Consumes(MediaType.WILDCARD) @Produces(MediaType.APPLICATION_JSON) @Path("controller/controller-services") @ApiOperation( value = "Gets all controller services", response = ControllerServicesEntity.class, authorizations = { @Authorization(value = "Read - /flow", type = "") } ) @ApiResponses( value = { @ApiResponse(code = 400, message = "NiFi was unable to complete the request because it was invalid. The request should not be retried without modification."), @ApiResponse(code = 401, message = "Client could not be authenticated."), @ApiResponse(code = 403, message = "Client is not authorized to make this request."), @ApiResponse(code = 409, message = "The request was valid but NiFi was not in the appropriate state to process it. Retrying the same request later may be successful.") } ) public Response getControllerServicesFromController() { authorizeFlow(); if (isReplicateRequest()) { return replicate(HttpMethod.GET); } // get all the controller services final Set<ControllerServiceEntity> controllerServices = serviceFacade.getControllerServices(null); controllerServiceResource.populateRemainingControllerServiceEntitiesContent(controllerServices); // create the response entity final ControllerServicesEntity entity = new ControllerServicesEntity(); entity.setCurrentTime(new Date()); entity.setControllerServices(controllerServices); // generate the response return clusterContext(generateOkResponse(entity)).build(); }

Example 12

/** * Retrieves the status for this NiFi. * * @return A controllerStatusEntity. * @throws InterruptedException if interrupted */ @GET @Consumes(MediaType.WILDCARD) @Produces(MediaType.APPLICATION_JSON) @Path("status") @ApiOperation( value = "Gets the current status of this NiFi", response = ControllerStatusEntity.class, authorizations = { @Authorization(value = "Read - /flow", type = "") } ) @ApiResponses( value = { @ApiResponse(code = 400, message = "NiFi was unable to complete the request because it was invalid. The request should not be retried without modification."), @ApiResponse(code = 401, message = "Client could not be authenticated."), @ApiResponse(code = 403, message = "Client is not authorized to make this request."), @ApiResponse(code = 409, message = "The request was valid but NiFi was not in the appropriate state to process it. Retrying the same request later may be successful.") } ) public Response getControllerStatus() throws InterruptedException { authorizeFlow(); if (isReplicateRequest()) { return replicate(HttpMethod.GET); } final ControllerStatusDTO controllerStatus = serviceFacade.getControllerStatus(); // create the response entity final ControllerStatusEntity entity = new ControllerStatusEntity(); entity.setControllerStatus(controllerStatus); // generate the response return clusterContext(generateOkResponse(entity)).build(); }

Example 13

/** * Retrieves the controller level bulletins. * * @return A controllerBulletinsEntity. */ @GET @Consumes(MediaType.WILDCARD) @Produces(MediaType.APPLICATION_JSON) @Path("controller/bulletins") @ApiOperation( value = "Retrieves Controller level bulletins", response = ControllerBulletinsEntity.class, authorizations = { @Authorization(value = "Read - /flow", type = ""), @Authorization(value = "Read - /controller - For controller bulletins", type = ""), @Authorization(value = "Read - /controller-services/{uuid} - For controller service bulletins", type = ""), @Authorization(value = "Read - /reporting-tasks/{uuid} - For reporting task bulletins", type = "") } ) @ApiResponses( value = { @ApiResponse(code = 400, message = "NiFi was unable to complete the request because it was invalid. The request should not be retried without modification."), @ApiResponse(code = 401, message = "Client could not be authenticated."), @ApiResponse(code = 403, message = "Client is not authorized to make this request."), @ApiResponse(code = 404, message = "The specified resource could not be found."), @ApiResponse(code = 409, message = "The request was valid but NiFi was not in the appropriate state to process it. Retrying the same request later may be successful.") } ) public Response getBulletins() { authorizeFlow(); if (isReplicateRequest()) { return replicate(HttpMethod.GET); } final ControllerBulletinsEntity entity = serviceFacade.getControllerBulletins(); return clusterContext(generateOkResponse(entity)).build(); }

Example 14

/** * Retrieves the banners for this NiFi. * * @return A bannerEntity. */ @GET @Consumes(MediaType.WILDCARD) @Produces(MediaType.APPLICATION_JSON) @Path("banners") @ApiOperation( value = "Retrieves the banners for this NiFi", response = BannerEntity.class, authorizations = { @Authorization(value = "Read - /flow", type = "") } ) @ApiResponses( value = { @ApiResponse(code = 400, message = "NiFi was unable to complete the request because it was invalid. The request should not be retried without modification."), @ApiResponse(code = 401, message = "Client could not be authenticated."), @ApiResponse(code = 403, message = "Client is not authorized to make this request."), @ApiResponse(code = 409, message = "The request was valid but NiFi was not in the appropriate state to process it. Retrying the same request later may be successful.") } ) public Response getBanners() { authorizeFlow(); // get the banner from the properties - will come from the NCM when clustered final String bannerText = getProperties().getBannerText(); // create the DTO final BannerDTO bannerDTO = new BannerDTO(); bannerDTO.setHeaderText(bannerText); bannerDTO.setFooterText(bannerText); // create the response entity final BannerEntity entity = new BannerEntity(); entity.setBanners(bannerDTO); // generate the response return clusterContext(generateOkResponse(entity)).build(); }

Example 15

/** * Retrieves the types of processors that this NiFi supports. * * @return A processorTypesEntity. * @throws InterruptedException if interrupted */ @GET @Consumes(MediaType.WILDCARD) @Produces(MediaType.APPLICATION_JSON) @Path("processor-types") @ApiOperation( value = "Retrieves the types of processors that this NiFi supports", notes = NON_GUARANTEED_ENDPOINT, response = ProcessorTypesEntity.class, authorizations = { @Authorization(value = "Read - /flow", type = "") } ) @ApiResponses( value = { @ApiResponse(code = 400, message = "NiFi was unable to complete the request because it was invalid. The request should not be retried without modification."), @ApiResponse(code = 401, message = "Client could not be authenticated."), @ApiResponse(code = 403, message = "Client is not authorized to make this request."), @ApiResponse(code = 409, message = "The request was valid but NiFi was not in the appropriate state to process it. Retrying the same request later may be successful.") } ) public Response getProcessorTypes() throws InterruptedException { authorizeFlow(); // create response entity final ProcessorTypesEntity entity = new ProcessorTypesEntity(); entity.setProcessorTypes(serviceFacade.getProcessorTypes()); // generate the response return clusterContext(generateOkResponse(entity)).build(); }

Example 16

/** * Retrieves the types of controller services that this NiFi supports. * * @param serviceType Returns only services that implement this type * @return A controllerServicesTypesEntity. * @throws InterruptedException if interrupted */ @GET @Consumes(MediaType.WILDCARD) @Produces(MediaType.APPLICATION_JSON) @Path("controller-service-types") @ApiOperation( value = "Retrieves the types of controller services that this NiFi supports", notes = NON_GUARANTEED_ENDPOINT, response = ControllerServiceTypesEntity.class, authorizations = { @Authorization(value = "Read - /flow", type = "") } ) @ApiResponses( value = { @ApiResponse(code = 400, message = "NiFi was unable to complete the request because it was invalid. The request should not be retried without modification."), @ApiResponse(code = 401, message = "Client could not be authenticated."), @ApiResponse(code = 403, message = "Client is not authorized to make this request."), @ApiResponse(code = 409, message = "The request was valid but NiFi was not in the appropriate state to process it. Retrying the same request later may be successful.") } ) public Response getControllerServiceTypes( @ApiParam( value = "If specified, will only return controller services of this type.", required = false ) @QueryParam("serviceType") String serviceType) throws InterruptedException { authorizeFlow(); // create response entity final ControllerServiceTypesEntity entity = new ControllerServiceTypesEntity(); entity.setControllerServiceTypes(serviceFacade.getControllerServiceTypes(serviceType)); // generate the response return clusterContext(generateOkResponse(entity)).build(); }

Example 17

/** * Gets the content for the input of the specified event. * * @param clusterNodeId The id of the node within the cluster this content is on. Required if clustered. * @param id The id of the provenance event associated with this content. * @return The content stream */ @GET @Consumes(MediaType.WILDCARD) @Produces(MediaType.WILDCARD) @Path("{id}/content/input") @ApiOperation( value = "Gets the input content for a provenance event", authorizations = { @Authorization(value = "Read Component Data - /data/{component-type}/{uuid}", type = "") } ) @ApiResponses( value = { @ApiResponse(code = 400, message = "NiFi was unable to complete the request because it was invalid. The request should not be retried without modification."), @ApiResponse(code = 401, message = "Client could not be authenticated."), @ApiResponse(code = 403, message = "Client is not authorized to make this request."), @ApiResponse(code = 404, message = "The specified resource could not be found."), @ApiResponse(code = 409, message = "The request was valid but NiFi was not in the appropriate state to process it. Retrying the same request later may be successful.") } ) public Response getInputContent( @ApiParam( value = "The id of the node where the content exists if clustered.", required = false ) @QueryParam("clusterNodeId") final String clusterNodeId, @ApiParam( value = "The provenance event id.", required = true ) @PathParam("id") final LongParameter id) { // ensure proper input if (id == null) { throw new IllegalArgumentException("The event id must be specified."); } // replicate if cluster manager if (isReplicateRequest()) { // determine where this request should be sent if (clusterNodeId == null) { throw new IllegalArgumentException("The id of the node in the cluster is required."); } else { return replicate(HttpMethod.GET, clusterNodeId); } } // get the uri of the request final String uri = generateResourceUri("provenance", "events", String.valueOf(id.getLong()), "content", "input"); // get an input stream to the content final DownloadableContent content = serviceFacade.getContent(id.getLong(), uri, ContentDirection.INPUT); // generate a streaming response final StreamingOutput response = new StreamingOutput() { @Override public void write(OutputStream output) throws IOException, WebApplicationException { try (InputStream is = content.getContent()) { // stream the content to the response StreamUtils.copy(is, output); // flush the response output.flush(); } } }; // use the appropriate content type String contentType = content.getType(); if (contentType == null) { contentType = MediaType.APPLICATION_OCTET_STREAM; } return generateOkResponse(response).type(contentType).header("Content-Disposition", String.format("attachment; filename=\"%s\"", content.getFilename())).build(); }

Example 18

/** * Retrieves the specified processor. * * @param id The id of the processor to retrieve. * @return A processorEntity. * @throws InterruptedException if interrupted */ @GET @Consumes(MediaType.WILDCARD) @Produces(MediaType.APPLICATION_JSON) @Path("/{id}") @ApiOperation( value = "Gets a processor", response = ProcessorEntity.class, authorizations = { @Authorization(value = "Read - /processors/{uuid}", type = "") } ) @ApiResponses( value = { @ApiResponse(code = 400, message = "NiFi was unable to complete the request because it was invalid. The request should not be retried without modification."), @ApiResponse(code = 401, message = "Client could not be authenticated."), @ApiResponse(code = 403, message = "Client is not authorized to make this request."), @ApiResponse(code = 404, message = "The specified resource could not be found."), @ApiResponse(code = 409, message = "The request was valid but NiFi was not in the appropriate state to process it. Retrying the same request later may be successful.") } ) public Response getProcessor( @ApiParam( value = "The processor id.", required = true ) @PathParam("id") final String id) throws InterruptedException { if (isReplicateRequest()) { return replicate(HttpMethod.GET); } // authorize access serviceFacade.authorizeAccess(lookup -> { final Authorizable processor = lookup.getProcessor(id).getAuthorizable(); processor.authorize(authorizer, RequestAction.READ, NiFiUserUtils.getNiFiUser()); }); // get the specified processor final ProcessorEntity entity = serviceFacade.getProcessor(id); populateRemainingProcessorEntityContent(entity); // generate the response return clusterContext(generateOkResponse(entity)).build(); }

Example 19

/** * Update the specified counter. This will reset the counter value to 0. * * @param httpServletRequest request * @param id The id of the counter. * @return A counterEntity. */ @PUT @Consumes(MediaType.WILDCARD) @Produces(MediaType.APPLICATION_JSON) @Path("{id}") @ApiOperation( value = "Updates the specified counter. This will reset the counter value to 0", notes = NON_GUARANTEED_ENDPOINT, response = CounterEntity.class, authorizations = { @Authorization(value = "Write - /counters", type = "") } ) @ApiResponses( value = { @ApiResponse(code = 400, message = "NiFi was unable to complete the request because it was invalid. The request should not be retried without modification."), @ApiResponse(code = 401, message = "Client could not be authenticated."), @ApiResponse(code = 403, message = "Client is not authorized to make this request."), @ApiResponse(code = 404, message = "The specified resource could not be found."), @ApiResponse(code = 409, message = "The request was valid but NiFi was not in the appropriate state to process it. Retrying the same request later may be successful.") } ) public Response updateCounter( @Context final HttpServletRequest httpServletRequest, @ApiParam( value = "The id of the counter." ) @PathParam("id") final String id) { if (isReplicateRequest()) { return replicate(HttpMethod.PUT); } final ComponentEntity requestComponentEntity = new ComponentEntity(); requestComponentEntity.setId(id); return withWriteLock( serviceFacade, requestComponentEntity, lookup -> { authorizeCounters(RequestAction.WRITE); }, null, (componentEntity) -> { // reset the specified counter final CounterDTO counter = serviceFacade.updateCounter(componentEntity.getId()); // create the response entity final CounterEntity entity = new CounterEntity(); entity.setCounter(counter); // generate the response return clusterContext(generateOkResponse(entity)).build(); } ); }

Example 20

/** * Creates a new replay request for the content associated with the specified provenance event id. * * @param httpServletRequest request * @param replayRequestEntity The replay request * @return A provenanceEventEntity */ @POST @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Path("replays") @ApiOperation( value = "Replays content from a provenance event", response = ProvenanceEventEntity.class, authorizations = { @Authorization(value = "Read Component Data - /data/{component-type}/{uuid}", type = ""), @Authorization(value = "Write Component Data - /data/{component-type}/{uuid}", type = "") } ) @ApiResponses( value = { @ApiResponse(code = 400, message = "NiFi was unable to complete the request because it was invalid. The request should not be retried without modification."), @ApiResponse(code = 401, message = "Client could not be authenticated."), @ApiResponse(code = 403, message = "Client is not authorized to make this request."), @ApiResponse(code = 404, message = "The specified resource could not be found."), @ApiResponse(code = 409, message = "The request was valid but NiFi was not in the appropriate state to process it. Retrying the same request later may be successful.") } ) public Response submitReplay( @Context final HttpServletRequest httpServletRequest, @ApiParam( value = "The replay request.", required = true ) final SubmitReplayRequestEntity replayRequestEntity) { // ensure the event id is specified if (replayRequestEntity == null || replayRequestEntity.getEventId() == null) { throw new IllegalArgumentException("The id of the event must be specified."); } // replicate if cluster manager if (isReplicateRequest()) { // determine where this request should be sent if (replayRequestEntity.getClusterNodeId() == null) { throw new IllegalArgumentException("The id of the node in the cluster is required."); } else { return replicate(HttpMethod.POST, replayRequestEntity, replayRequestEntity.getClusterNodeId()); } } // handle expects request (usually from the cluster manager) final String expects = httpServletRequest.getHeader(RequestReplicator.REQUEST_VALIDATION_HTTP_HEADER); if (expects != null) { return generateContinueResponse().build(); } // submit the provenance replay request final ProvenanceEventDTO event = serviceFacade.submitReplay(replayRequestEntity.getEventId()); // create a response entity final ProvenanceEventEntity entity = new ProvenanceEventEntity(); entity.setProvenanceEvent(event); // generate the response URI uri = URI.create(generateResourceUri("provenance-events", event.getId())); return clusterContext(generateCreatedResponse(uri, entity)).build(); }

Example 21

/** * Creates a new Funnel. * * @param httpServletRequest request * @param groupId The group id * @param requestFunnelEntity A funnelEntity. * @return A funnelEntity. */ @POST @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Path("{id}/funnels") @ApiOperation( value = "Creates a funnel", response = FunnelEntity.class, authorizations = { @Authorization(value = "Write - /process-groups/{uuid}", type = "") } ) @ApiResponses( value = { @ApiResponse(code = 400, message = "NiFi was unable to complete the request because it was invalid. The request should not be retried without modification."), @ApiResponse(code = 401, message = "Client could not be authenticated."), @ApiResponse(code = 403, message = "Client is not authorized to make this request."), @ApiResponse(code = 404, message = "The specified resource could not be found."), @ApiResponse(code = 409, message = "The request was valid but NiFi was not in the appropriate state to process it. Retrying the same request later may be successful.") } ) public Response createFunnel( @Context final HttpServletRequest httpServletRequest, @ApiParam( value = "The process group id.", required = true ) @PathParam("id") final String groupId, @ApiParam( value = "The funnel configuration details.", required = true ) final FunnelEntity requestFunnelEntity) { if (requestFunnelEntity == null || requestFunnelEntity.getComponent() == null) { throw new IllegalArgumentException("Funnel details must be specified."); } if (requestFunnelEntity.getRevision() == null || (requestFunnelEntity.getRevision().getVersion() == null || requestFunnelEntity.getRevision().getVersion() != 0)) { throw new IllegalArgumentException("A revision of 0 must be specified when creating a new Funnel."); } if (requestFunnelEntity.getComponent().getId() != null) { throw new IllegalArgumentException("Funnel ID cannot be specified."); } final PositionDTO proposedPosition = requestFunnelEntity.getComponent().getPosition(); if (proposedPosition != null) { if (proposedPosition.getX() == null || proposedPosition.getY() == null) { throw new IllegalArgumentException("The x and y coordinate of the proposed position must be specified."); } } if (requestFunnelEntity.getComponent().getParentGroupId() != null && !groupId.equals(requestFunnelEntity.getComponent().getParentGroupId())) { throw new IllegalArgumentException(String.format("If specified, the parent process group id %s must be the same as specified in the URI %s", requestFunnelEntity.getComponent().getParentGroupId(), groupId)); } requestFunnelEntity.getComponent().setParentGroupId(groupId); if (isReplicateRequest()) { return replicate(HttpMethod.POST, requestFunnelEntity); } return withWriteLock( serviceFacade, requestFunnelEntity, lookup -> { final Authorizable processGroup = lookup.getProcessGroup(groupId).getAuthorizable(); processGroup.authorize(authorizer, RequestAction.WRITE, NiFiUserUtils.getNiFiUser()); }, null, funnelEntity -> { // set the processor id as appropriate funnelEntity.getComponent().setId(generateUuid()); // create the funnel and generate the json final Revision revision = getRevision(funnelEntity, funnelEntity.getComponent().getId()); final FunnelEntity entity = serviceFacade.createFunnel(revision, groupId, funnelEntity.getComponent()); funnelResource.populateRemainingFunnelEntityContent(entity); // build the response return clusterContext(generateCreatedResponse(URI.create(entity.getUri()), entity)).build(); } ); }

Example 22

/** * Clears the state for a controller service. * * @param httpServletRequest servlet request * @param id The id of the controller service * @return a componentStateEntity */ @POST @Consumes(MediaType.WILDCARD) @Produces(MediaType.APPLICATION_JSON) @Path("{id}/state/clear-requests") @ApiOperation( value = "Clears the state for a controller service", response = ComponentStateDTO.class, authorizations = { @Authorization(value = "Write - /controller-services/{uuid}", type = "") } ) @ApiResponses( value = { @ApiResponse(code = 400, message = "NiFi was unable to complete the request because it was invalid. The request should not be retried without modification."), @ApiResponse(code = 401, message = "Client could not be authenticated."), @ApiResponse(code = 403, message = "Client is not authorized to make this request."), @ApiResponse(code = 404, message = "The specified resource could not be found."), @ApiResponse(code = 409, message = "The request was valid but NiFi was not in the appropriate state to process it. Retrying the same request later may be successful.") } ) public Response clearState( @Context HttpServletRequest httpServletRequest, @ApiParam( value = "The controller service id.", required = true ) @PathParam("id") final String id) { if (isReplicateRequest()) { return replicate(HttpMethod.POST); } final ControllerServiceEntity requestControllerServiceEntity = new ControllerServiceEntity(); requestControllerServiceEntity.setId(id); return withWriteLock( serviceFacade, requestControllerServiceEntity, lookup -> { final Authorizable controllerService = lookup.getControllerService(id).getAuthorizable(); controllerService.authorize(authorizer, RequestAction.WRITE, NiFiUserUtils.getNiFiUser()); }, () -> serviceFacade.verifyCanClearControllerServiceState(id), (controllerServiceEntity) -> { // get the component state serviceFacade.clearControllerServiceState(controllerServiceEntity.getId()); // generate the response entity final ComponentStateEntity entity = new ComponentStateEntity(); // generate the response return clusterContext(generateOkResponse(entity)).build(); } ); }

Example 23

/** * Retrieves the specified label. * * @param id The id of the label to retrieve * @return A labelEntity. */ @GET @Consumes(MediaType.WILDCARD) @Produces(MediaType.APPLICATION_JSON) @Path("{id}") @ApiOperation( value = "Gets a label", response = LabelEntity.class, authorizations = { @Authorization(value = "Read - /labels/{uuid}", type = "") } ) @ApiResponses( value = { @ApiResponse(code = 400, message = "NiFi was unable to complete the request because it was invalid. The request should not be retried without modification."), @ApiResponse(code = 401, message = "Client could not be authenticated."), @ApiResponse(code = 403, message = "Client is not authorized to make this request."), @ApiResponse(code = 404, message = "The specified resource could not be found."), @ApiResponse(code = 409, message = "The request was valid but NiFi was not in the appropriate state to process it. Retrying the same request later may be successful.") } ) public Response getLabel( @ApiParam( value = "The label id.", required = true ) @PathParam("id") final String id) { if (isReplicateRequest()) { return replicate(HttpMethod.GET); } // authorize access serviceFacade.authorizeAccess(lookup -> { final Authorizable label = lookup.getLabel(id); label.authorize(authorizer, RequestAction.READ, NiFiUserUtils.getNiFiUser()); }); // get the label final LabelEntity entity = serviceFacade.getLabel(id); populateRemainingLabelEntityContent(entity); return clusterContext(generateOkResponse(entity)).build(); }

Example 24

/** * Updates the specified label. * * @param httpServletRequest request * @param id The id of the label to update. * @param requestLabelEntity A labelEntity. * @return A labelEntity. */ @PUT @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Path("{id}") @ApiOperation( value = "Updates a label", response = LabelEntity.class, authorizations = { @Authorization(value = "Write - /labels/{uuid}", type = "") } ) @ApiResponses( value = { @ApiResponse(code = 400, message = "NiFi was unable to complete the request because it was invalid. The request should not be retried without modification."), @ApiResponse(code = 401, message = "Client could not be authenticated."), @ApiResponse(code = 403, message = "Client is not authorized to make this request."), @ApiResponse(code = 404, message = "The specified resource could not be found."), @ApiResponse(code = 409, message = "The request was valid but NiFi was not in the appropriate state to process it. Retrying the same request later may be successful.") } ) public Response updateLabel( @Context final HttpServletRequest httpServletRequest, @ApiParam( value = "The label id.", required = true ) @PathParam("id") final String id, @ApiParam( value = "The label configuration details.", required = true ) final LabelEntity requestLabelEntity) { if (requestLabelEntity == null || requestLabelEntity.getComponent() == null) { throw new IllegalArgumentException("Label details must be specified."); } if (requestLabelEntity.getRevision() == null) { throw new IllegalArgumentException("Revision must be specified."); } // ensure the ids are the same final LabelDTO requestLabelDTO = requestLabelEntity.getComponent(); if (!id.equals(requestLabelDTO.getId())) { throw new IllegalArgumentException(String.format("The label id (%s) in the request body does not equal the " + "label id of the requested resource (%s).", requestLabelDTO.getId(), id)); } final PositionDTO proposedPosition = requestLabelDTO.getPosition(); if (proposedPosition != null) { if (proposedPosition.getX() == null || proposedPosition.getY() == null) { throw new IllegalArgumentException("The x and y coordinate of the proposed position must be specified."); } } if (isReplicateRequest()) { return replicate(HttpMethod.PUT, requestLabelEntity); } // handle expects request (usually from the cluster manager) final Revision requestRevision = getRevision(requestLabelEntity, id); return withWriteLock( serviceFacade, requestLabelEntity, requestRevision, lookup -> { Authorizable authorizable = lookup.getLabel(id); authorizable.authorize(authorizer, RequestAction.WRITE, NiFiUserUtils.getNiFiUser()); }, null, (revision, labelEntity) -> { final LabelDTO labelDTO = labelEntity.getComponent(); // update the label final LabelEntity entity = serviceFacade.updateLabel(revision, labelDTO); populateRemainingLabelEntityContent(entity); return clusterContext(generateOkResponse(entity)).build(); } ); }

Example 25

/** * Removes the specified label. * * @param httpServletRequest request * @param version The revision is used to verify the client is working with the latest version of the flow. * @param clientId Optional client id. If the client id is not specified, a new one will be generated. This value (whether specified or generated) is included in the response. * @param id The id of the label to remove. * @return A entity containing the client id and an updated revision. */ @DELETE @Consumes(MediaType.WILDCARD) @Produces(MediaType.APPLICATION_JSON) @Path("{id}") @ApiOperation( value = "Deletes a label", response = LabelEntity.class, authorizations = { @Authorization(value = "Write - /labels/{uuid}", type = ""), @Authorization(value = "Write - Parent Process Group - /process-groups/{uuid}", type = "") } ) @ApiResponses( value = { @ApiResponse(code = 400, message = "NiFi was unable to complete the request because it was invalid. The request should not be retried without modification."), @ApiResponse(code = 401, message = "Client could not be authenticated."), @ApiResponse(code = 403, message = "Client is not authorized to make this request."), @ApiResponse(code = 404, message = "The specified resource could not be found."), @ApiResponse(code = 409, message = "The request was valid but NiFi was not in the appropriate state to process it. Retrying the same request later may be successful.") } ) public Response removeLabel( @Context final HttpServletRequest httpServletRequest, @ApiParam( value = "The revision is used to verify the client is working with the latest version of the flow.", required = false ) @QueryParam(VERSION) final LongParameter version, @ApiParam( value = "If the client id is not specified, new one will be generated. This value (whether specified or generated) is included in the response.", required = false ) @QueryParam(CLIENT_ID) @DefaultValue(StringUtils.EMPTY) final ClientIdParameter clientId, @ApiParam( value = "The label id.", required = true ) @PathParam("id") final String id) { if (isReplicateRequest()) { return replicate(HttpMethod.DELETE); } final LabelEntity requestLabelEntity = new LabelEntity(); requestLabelEntity.setId(id); // handle expects request (usually from the cluster manager) final Revision requestRevision = new Revision(version == null ? null : version.getLong(), clientId.getClientId(), id); return withWriteLock( serviceFacade, requestLabelEntity, requestRevision, lookup -> { final Authorizable label = lookup.getLabel(id); // ensure write permission to the label label.authorize(authorizer, RequestAction.WRITE, NiFiUserUtils.getNiFiUser()); // ensure write permission to the parent process group label.getParentAuthorizable().authorize(authorizer, RequestAction.WRITE, NiFiUserUtils.getNiFiUser()); }, null, (revision, labelEntity) -> { // delete the specified label final LabelEntity entity = serviceFacade.deleteLabel(revision, labelEntity.getId()); return clusterContext(generateOkResponse(entity)).build(); } ); }

Example 26

/** * Retrieves the specified input port. * * @param id The id of the input port to retrieve * @return A inputPortEntity. */ @GET @Consumes(MediaType.WILDCARD) @Produces(MediaType.APPLICATION_JSON) @Path("{id}") @ApiOperation( value = "Gets an input port", response = PortEntity.class, authorizations = { @Authorization(value = "Read - /input-ports/{uuid}", type = "") } ) @ApiResponses( value = { @ApiResponse(code = 400, message = "NiFi was unable to complete the request because it was invalid. The request should not be retried without modification."), @ApiResponse(code = 401, message = "Client could not be authenticated."), @ApiResponse(code = 403, message = "Client is not authorized to make this request."), @ApiResponse(code = 404, message = "The specified resource could not be found."), @ApiResponse(code = 409, message = "The request was valid but NiFi was not in the appropriate state to process it. Retrying the same request later may be successful.") } ) public Response getInputPort( @ApiParam( value = "The input port id.", required = true ) @PathParam("id") final String id) { if (isReplicateRequest()) { return replicate(HttpMethod.GET); } // authorize access serviceFacade.authorizeAccess(lookup -> { final Authorizable inputPort = lookup.getInputPort(id); inputPort.authorize(authorizer, RequestAction.READ, NiFiUserUtils.getNiFiUser()); }); // get the port final PortEntity entity = serviceFacade.getInputPort(id); populateRemainingInputPortEntityContent(entity); return clusterContext(generateOkResponse(entity)).build(); }

Example 27

/** * Updates the specified input port. * * @param httpServletRequest request * @param id The id of the input port to update. * @param requestPortEntity A inputPortEntity. * @return A inputPortEntity. */ @PUT @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Path("{id}") @ApiOperation( value = "Updates an input port", response = PortEntity.class, authorizations = { @Authorization(value = "Write - /input-ports/{uuid}", type = "") } ) @ApiResponses( value = { @ApiResponse(code = 400, message = "NiFi was unable to complete the request because it was invalid. The request should not be retried without modification."), @ApiResponse(code = 401, message = "Client could not be authenticated."), @ApiResponse(code = 403, message = "Client is not authorized to make this request."), @ApiResponse(code = 404, message = "The specified resource could not be found."), @ApiResponse(code = 409, message = "The request was valid but NiFi was not in the appropriate state to process it. Retrying the same request later may be successful.") } ) public Response updateInputPort( @Context HttpServletRequest httpServletRequest, @ApiParam( value = "The input port id.", required = true ) @PathParam("id") final String id, @ApiParam( value = "The input port configuration details.", required = true ) final PortEntity requestPortEntity) { if (requestPortEntity == null || requestPortEntity.getComponent() == null) { throw new IllegalArgumentException("Input port details must be specified."); } if (requestPortEntity.getRevision() == null) { throw new IllegalArgumentException("Revision must be specified."); } // ensure the ids are the same final PortDTO requestPortDTO = requestPortEntity.getComponent(); if (!id.equals(requestPortDTO.getId())) { throw new IllegalArgumentException(String.format("The input port id (%s) in the request body does not equal the " + "input port id of the requested resource (%s).", requestPortDTO.getId(), id)); } final PositionDTO proposedPosition = requestPortDTO.getPosition(); if (proposedPosition != null) { if (proposedPosition.getX() == null || proposedPosition.getY() == null) { throw new IllegalArgumentException("The x and y coordinate of the proposed position must be specified."); } } if (isReplicateRequest()) { return replicate(HttpMethod.PUT, requestPortEntity); } // handle expects request (usually from the cluster manager) final Revision requestRevision = getRevision(requestPortEntity, id); return withWriteLock( serviceFacade, requestPortEntity, requestRevision, lookup -> { Authorizable authorizable = lookup.getInputPort(id); authorizable.authorize(authorizer, RequestAction.WRITE, NiFiUserUtils.getNiFiUser()); }, () -> serviceFacade.verifyUpdateInputPort(requestPortDTO), (revision, portEntity) -> { final PortDTO portDTO = portEntity.getComponent(); // update the input port final PortEntity entity = serviceFacade.updateInputPort(revision, portDTO); populateRemainingInputPortEntityContent(entity); return clusterContext(generateOkResponse(entity)).build(); } ); }

Example 28

/** * Updates the specified process group. * * @param httpServletRequest request * @param id The id of the process group. * @param requestProcessGroupEntity A processGroupEntity. * @return A processGroupEntity. */ @PUT @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Path("{id}") @ApiOperation( value = "Updates a process group", response = ProcessGroupEntity.class, authorizations = { @Authorization(value = "Write - /process-groups/{uuid}", type = "") } ) @ApiResponses( value = { @ApiResponse(code = 400, message = "NiFi was unable to complete the request because it was invalid. The request should not be retried without modification."), @ApiResponse(code = 401, message = "Client could not be authenticated."), @ApiResponse(code = 403, message = "Client is not authorized to make this request."), @ApiResponse(code = 404, message = "The specified resource could not be found."), @ApiResponse(code = 409, message = "The request was valid but NiFi was not in the appropriate state to process it. Retrying the same request later may be successful.") } ) public Response updateProcessGroup( @Context final HttpServletRequest httpServletRequest, @ApiParam( value = "The process group id.", required = true ) @PathParam("id") final String id, @ApiParam( value = "The process group configuration details.", required = true ) final ProcessGroupEntity requestProcessGroupEntity) { if (requestProcessGroupEntity == null || requestProcessGroupEntity.getComponent() == null) { throw new IllegalArgumentException("Process group details must be specified."); } if (requestProcessGroupEntity.getRevision() == null) { throw new IllegalArgumentException("Revision must be specified."); } // ensure the same id is being used final ProcessGroupDTO requestProcessGroupDTO = requestProcessGroupEntity.getComponent(); if (!id.equals(requestProcessGroupDTO.getId())) { throw new IllegalArgumentException(String.format("The process group id (%s) in the request body does " + "not equal the process group id of the requested resource (%s).", requestProcessGroupDTO.getId(), id)); } final PositionDTO proposedPosition = requestProcessGroupDTO.getPosition(); if (proposedPosition != null) { if (proposedPosition.getX() == null || proposedPosition.getY() == null) { throw new IllegalArgumentException("The x and y coordinate of the proposed position must be specified."); } } if (isReplicateRequest()) { return replicate(HttpMethod.PUT, requestProcessGroupEntity); } // handle expects request (usually from the cluster manager) final Revision requestRevision = getRevision(requestProcessGroupEntity, id); return withWriteLock( serviceFacade, requestProcessGroupEntity, requestRevision, lookup -> { Authorizable authorizable = lookup.getProcessGroup(id).getAuthorizable(); authorizable.authorize(authorizer, RequestAction.WRITE, NiFiUserUtils.getNiFiUser()); }, null, (revision, processGroupEntity) -> { // update the process group final ProcessGroupEntity entity = serviceFacade.updateProcessGroup(revision, processGroupEntity.getComponent()); populateRemainingProcessGroupEntityContent(entity); return clusterContext(generateOkResponse(entity)).build(); } ); }

Example 29

/** * Gets the state for a processor. * * @param id The id of the processor * @return a componentStateEntity * @throws InterruptedException if interrupted */ @GET @Consumes(MediaType.WILDCARD) @Produces(MediaType.APPLICATION_JSON) @Path("/{id}/state") @ApiOperation( value = "Gets the state for a processor", response = ComponentStateDTO.class, authorizations = { @Authorization(value = "Write - /processors/{uuid}", type = "") } ) @ApiResponses( value = { @ApiResponse(code = 400, message = "NiFi was unable to complete the request because it was invalid. The request should not be retried without modification."), @ApiResponse(code = 401, message = "Client could not be authenticated."), @ApiResponse(code = 403, message = "Client is not authorized to make this request."), @ApiResponse(code = 404, message = "The specified resource could not be found."), @ApiResponse(code = 409, message = "The request was valid but NiFi was not in the appropriate state to process it. Retrying the same request later may be successful.") } ) public Response getState( @ApiParam( value = "The processor id.", required = true ) @PathParam("id") final String id) throws InterruptedException { if (isReplicateRequest()) { return replicate(HttpMethod.GET); } // authorize access serviceFacade.authorizeAccess(lookup -> { final Authorizable processor = lookup.getProcessor(id).getAuthorizable(); processor.authorize(authorizer, RequestAction.WRITE, NiFiUserUtils.getNiFiUser()); }); // get the component state final ComponentStateDTO state = serviceFacade.getProcessorState(id); // generate the response entity final ComponentStateEntity entity = new ComponentStateEntity(); entity.setComponentState(state); // generate the response return clusterContext(generateOkResponse(entity)).build(); }

Example 30

/** * Move's the components in this Snippet into a new Process Group. * * @param httpServletRequest request * @param snippetId The id of the snippet. * @param requestSnippetEntity A snippetEntity * @return A snippetEntity */ @PUT @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Path("{id}") @ApiOperation( value = "Move's the components in this Snippet into a new Process Group and discards the snippet", response = SnippetEntity.class, authorizations = { @Authorization(value = "Write Process Group - /process-groups/{uuid}", type = ""), @Authorization(value = "Write - /{component-type}/{uuid} - For each component in the Snippet and their descendant components", type = "") } ) @ApiResponses( value = { @ApiResponse(code = 400, message = "NiFi was unable to complete the request because it was invalid. The request should not be retried without modification."), @ApiResponse(code = 401, message = "Client could not be authenticated."), @ApiResponse(code = 403, message = "Client is not authorized to make this request."), @ApiResponse(code = 404, message = "The specified resource could not be found."), @ApiResponse(code = 409, message = "The request was valid but NiFi was not in the appropriate state to process it. Retrying the same request later may be successful.") } ) public Response updateSnippet( @Context HttpServletRequest httpServletRequest, @ApiParam( value = "The snippet id.", required = true ) @PathParam("id") String snippetId, @ApiParam( value = "The snippet configuration details.", required = true ) final SnippetEntity requestSnippetEntity) { if (requestSnippetEntity == null || requestSnippetEntity.getSnippet() == null) { throw new IllegalArgumentException("Snippet details must be specified."); } // ensure the ids are the same final SnippetDTO requestSnippetDTO = requestSnippetEntity.getSnippet(); if (!snippetId.equals(requestSnippetDTO.getId())) { throw new IllegalArgumentException(String.format("The snippet id (%s) in the request body does not equal the " + "snippet id of the requested resource (%s).", requestSnippetDTO.getId(), snippetId)); } if (isReplicateRequest()) { return replicate(HttpMethod.PUT, requestSnippetEntity); } // get the revision from this snippet final Set<Revision> requestRevisions = serviceFacade.getRevisionsFromSnippet(snippetId); return withWriteLock( serviceFacade, requestSnippetEntity, requestRevisions, lookup -> { // ensure write access to the target process group if (requestSnippetDTO.getParentGroupId() != null) { lookup.getProcessGroup(requestSnippetDTO.getParentGroupId()).getAuthorizable().authorize(authorizer, RequestAction.WRITE, NiFiUserUtils.getNiFiUser()); } // ensure write permission to every component in the snippet excluding referenced services final SnippetAuthorizable snippet = lookup.getSnippet(snippetId); authorizeSnippet(snippet, authorizer, lookup, RequestAction.WRITE, false, false); }, () -> serviceFacade.verifyUpdateSnippet(requestSnippetDTO, requestRevisions.stream().map(rev -> rev.getComponentId()).collect(Collectors.toSet())), (revisions, snippetEntity) -> { // update the snippet final SnippetEntity entity = serviceFacade.updateSnippet(revisions, snippetEntity.getSnippet()); populateRemainingSnippetEntityContent(entity); return clusterContext(generateOkResponse(entity)).build(); } ); }
Sours: https://www.programcreek.com/java-api-examples/?api=com.wordnik.swagger.annotations.ApiOperation
What is Swagger API Documentation -- Swagger API Documentation tutorial for beginners -- Spring Boot

Now a days REST and Microservices have got a lot of momentum. At the same time, actual REST specification does not suggest any standard way to document the REST APIs that we are going to expose [like WSDL for SOAP]. As a result, everybody is documenting their APIs in their own way, resulting a gap in common structure which all can easily follow, understand and use. We need to have a common pattern and tool.

Swagger (backed by companies like Google, IBM, Microsoft) does this same job of filling the gap of common documentation style. In this tutorial, we will learn to use Swagger to generate REST API docs using swagger 2 annotations.

Table of Contents What is SwaggerProject Structure and Technology StackCreate REST APIsSwagger2 ConfigurationSwagger2 AnnotationsDemo

What is Swagger

Swagger (now the “Open API Initiative”) is a specification and framework for describing REST APIs using a common language that everyone can understand. There are other available frameworks that have gained some popularity, such as RAML, Summation etc. but Swagger is most popular at this point of time considering its features and acceptance among the developer community.

It offers both human readable and machine readable format of documentation. It provides both JSON and UI support. JSON can be used as machine readable format and is for visual display which is easy for humans to understand by just browsing the api documentation.

Project Structure and Technology Stack

The folder structure of project is :

Swagger2 Project Structure

We will use the below technologies for this demo.

  1. Eclipse as IDE
  2. Maven as build tool
  3. Spring Boot as application framework
  4. Spring Rest as REST API framework
  5. Swagger2 as REST documentation framework
  6. Java 1.8

Create REST APIs

We will first create some REST APIs which will be used for demonstration of Swagger documentation capability. We will use the Spring boot style of exposing rest API for faster development time.

  1. Create a Spring boot project from Spring Boot initializer portal with , , dependencies. Give other maven GAV coordinates and download the project. This screen will look like:

    Unzip and import the project into Eclipse as existing maven project. In this step, all necessary dependencies will be downloaded from maven repository. Perform a fresh at this step so that all spring-boot related artifacts got downloaded properly.

  2. Open and add below property. This will start the application in context path.server.contextPath=/swagger2-demo
  3. Add one REST controller which will provide basic REST based functionalities on entity.

    Swagger2DemoRestController.java

    package com.example.springbootswagger2.controller; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.example.springbootswagger2.model.Student; @RestController public class Swagger2DemoRestController { List<Student> students = new ArrayList<Student>(); { students.add(new Student("Sajal", "IV", "India")); students.add(new Student("Lokesh", "V", "India")); students.add(new Student("Kajal", "III", "USA")); students.add(new Student("Sukesh", "VI", "USA")); } @RequestMapping(value = "/getStudents") public List<Student> getStudents() { return students; } @RequestMapping(value = "/getStudent/{name}") public Student getStudent(@PathVariable(value = "name") String name) { return students.stream().filter(x -> x.getName().equalsIgnoreCase(name)).collect(Collectors.toList()).get(0); } @RequestMapping(value = "/getStudentByCountry/{country}") public List<Student> getStudentByCountry(@PathVariable(value = "country") String country) { System.out.println("Searching Student in country : " + country); List<Student> studentsByCountry = students.stream().filter(x -> x.getCountry().equalsIgnoreCase(country)) .collect(Collectors.toList()); System.out.println(studentsByCountry); return studentsByCountry; } @RequestMapping(value = "/getStudentByClass/{cls}") public List<Student> getStudentByClass(@PathVariable(value = "cls") String cls) { return students.stream().filter(x -> x.getCls().equalsIgnoreCase(cls)).collect(Collectors.toList()); } }

    Student.java

    package com.example.springbootswagger2.model; public class Student { private String name; private String cls; private String country; public Student(String name, String cls, String country) { super(); this.name = name; this.cls = cls; this.country = country; } public String getName() { return name; } public String getCls() { return cls; } public String getCountry() { return country; } @Override public String toString() { return "Student [name=" + name + ", cls=" + cls + ", country=" + country + "]"; } }
  4. Start the application as Spring boot application. Test couple of REST Endpoints to check if they are working fine:
    • http://localhost:8080/swagger2-demo/getStudents
    • http://localhost:8080/swagger2-demo/getStudent/sajal
    • http://localhost:8080/swagger2-demo/getStudentByCountry/india
    • http://localhost:8080/swagger2-demo/getStudentByClass/v

Swagger2 Configuration

Our REST APIs are ready. Now add swagger 2 support to the project.ff

Add Swagger2 Maven Dependencies

Open pom.xml file of the project and add below two swagger related dependencies i.e. and .

<dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.6.1</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.6.1</version> </dependency>

Actually API has couple of varieties and maintained in different artifacts. Today we will use the because this version adapts well with any spring based configurations. We can try other configurations also easily and that should give same functionality – with no/little change in configuration.

Add Swagger2 Configuration

Add the below configuration in the code base. To help you understand the configuration, I have added inline comments.

package com.example.springbootswagger2.configuration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import com.google.common.base.Predicates; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2; @Configuration @EnableSwagger2 public class Swagger2UiConfiguration extends WebMvcConfigurerAdapter { @Bean public Docket api() { // @formatter:off //Register the controllers to swagger //Also it is configuring the Swagger Docket return new Docket(DocumentationType.SWAGGER_2).select() // .apis(RequestHandlerSelectors.any()) .apis(Predicates.not(RequestHandlerSelectors.basePackage("org.springframework.boot"))) // .paths(PathSelectors.any()) // .paths(PathSelectors.ant("/swagger2-demo")) .build(); // @formatter:on } @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { //enabling swagger-ui part for visual documentation registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/"); registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/"); } }

Verify Swagger2 JSON Format Docs

Do maven build and Start the server. Open the link http://localhost:8080/swagger2-demo/v2/api-docs and it should give the entire documentation in format. This is not that much easy to read and understand, actually Swagger has provided this to be used in other systems like API management tools now a days popular, which provides the functionality like API gateways, API caching, API documentation etc.

Verify Swagger2 UI Docs

Open http://localhost:8080/swagger2-demo/swagger-ui.html to see the Swagger UI documentation in the browser.

Swagger2 UI Docs without Annotations

Swagger2 Annotations

The default generated API docs are good but they lack detailed API level information. Swagger has provided few annotations to add this detailed information to the APIs. e.g.

  1. – We can add this Annotation to the controller to add basic information regarding the [email protected](value = "Swagger2DemoRestController", description = "REST APIs related to Student Entity!!!!") @RestController public class Swagger2DemoRestController { ... }
  2. – We can add these annotations to any rest method in the controller to add basic information related to that method. e.g. @ApiOperation(value = "Get list of Students in the System ", response = Iterable.class, tags = "getStudents") @ApiResponses(value = { @ApiResponse(code = 200, message = "Success|OK"), @ApiResponse(code = 401, message = "not authorized!"), @ApiResponse(code = 403, message = "forbidden!!!"), @ApiResponse(code = 404, message = "not found!!!") }) @RequestMapping(value = "/getStudents") public List<Student> getStudents() { return students; }

    Here we can add to methods to add some grouping in the .

  3. – This annotation is used in the Model property to add some description to the Swagger output for that model attribute. [email protected](notes = "Name of the Student",name="name",required=true,value="test name") private String name;

Controller and Model class code after adding swagger2 annotations.

Swagger2DemoRestController.java

package com.example.springbootswagger2.controller; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.example.springbootswagger2.model.Student; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponses; @Api(value = "Swagger2DemoRestController", description = "REST Apis related to Student Entity!!!!") @RestController public class Swagger2DemoRestController { List<Student> students = new ArrayList<Student>(); { students.add(new Student("Sajal", "IV", "India")); students.add(new Student("Lokesh", "V", "India")); students.add(new Student("Kajal", "III", "USA")); students.add(new Student("Sukesh", "VI", "USA")); } @ApiOperation(value = "Get list of Students in the System ", response = Iterable.class, tags = "getStudents") @ApiResponses(value = { @ApiResponse(code = 200, message = "Suceess|OK"), @ApiResponse(code = 401, message = "not authorized!"), @ApiResponse(code = 403, message = "forbidden!!!"), @ApiResponse(code = 404, message = "not found!!!") }) @RequestMapping(value = "/getStudents") public List<Student> getStudents() { return students; } @ApiOperation(value = "Get specific Student in the System ", response = Student.class, tags = "getStudent") @RequestMapping(value = "/getStudent/{name}") public Student getStudent(@PathVariable(value = "name") String name) { return students.stream().filter(x -> x.getName().equalsIgnoreCase(name)).collect(Collectors.toList()).get(0); } @ApiOperation(value = "Get specific Student By Country in the System ", response = Student.class, tags = "getStudentByCountry") @RequestMapping(value = "/getStudentByCountry/{country}") public List<Student> getStudentByCountry(@PathVariable(value = "country") String country) { System.out.println("Searching Student in country : " + country); List<Student> studentsByCountry = students.stream().filter(x -> x.getCountry().equalsIgnoreCase(country)) .collect(Collectors.toList()); System.out.println(studentsByCountry); return studentsByCountry; } // @ApiOperation(value = "Get specific Student By Class in the System ",response = Student.class,tags="getStudentByClass") @RequestMapping(value = "/getStudentByClass/{cls}") public List<Student> getStudentByClass(@PathVariable(value = "cls") String cls) { return students.stream().filter(x -> x.getCls().equalsIgnoreCase(cls)).collect(Collectors.toList()); } }

Student.java

package com.example.springbootswagger2.model; import io.swagger.annotations.ApiModelProperty; public class Student { @ApiModelProperty(notes = "Name of the Student",name="name",required=true,value="test name") private String name; @ApiModelProperty(notes = "Class of the Student",name="cls",required=true,value="test class") private String cls; @ApiModelProperty(notes = "Country of the Student",name="country",required=true,value="test country") private String country; public Student(String name, String cls, String country) { super(); this.name = name; this.cls = cls; this.country = country; } public String getName() { return name; } public String getCls() { return cls; } public String getCountry() { return country; } @Override public String toString() { return "Student [name=" + name + ", cls=" + cls + ", country=" + country + "]"; } }

Demo

Now when our REST APIs are properly annotated, let’s see the final output. Open http://localhost:8080/swagger2-demo/swagger-ui.html to see the Swagger ui documentation in the browser.

Final Swagger2 REST API Output

That’s all about to create REST API documentation using swagger2 using a spring boot application. Drop me your questions in comments section.

Download Source code

Happy Learning !!

Let us know if you liked the post. That’s the only way we can improve.

Sours: https://howtodoinjava.com/swagger2/swagger-spring-mvc-rest-example/

Example apioperation

ApiOperation

(Quick Reference)

Purpose

Documents an operation

Usage

@ApiOperation(value="", notes="", response=Foo, responseContainer="", tags="", httpMethod="", position=0, nickName="", produces="", consumes="", protocols="", authorizations=@Authorization(""), hidden=false)

Parameters

ParameterSupportedUsage
YesProvides a brief description of this operation. Should be 120 characters or less for proper visibility in Swagger-UI.
YesA verbose description of the operation.
YesThe response type of the operation.
YesNotes whether the response type is a list of values. Use or for containers.
NoCurrently not implemented in readers, reserved for future use.
NoCorresponds to the `method` field as the HTTP method used. Acceptable values are "GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS" and "PATCH".
NoOptional explicit ordering of this API resource in the Resource Listing.
NoThe nickname field is used by third-party tools to uniquely identify this operation. Autogenerated.
YesTakes in comma-separated values of content types. For example, "application/json, application/xml" would suggest this API Resource generates JSON and XML output.
YesTakes in comma-separated values of content types. For example, "application/json, application/xml" would suggest this API Resource accepts JSON and XML input.
NoDescribes url schemes supported by controller.
NoTakes in a list of the required authorizations for this API Resource. This may be overridden by specific operations.
NoHides the api
Sours: https://rahulsom.github.io/swaggydoc/ref/Swagger%20Annotations/ApiOperation.html
OAuth 2.0: An Overview

Java Examples for io.swagger.annotations.ApiOperation

Example 4

@GET @Produces(MediaType.APPLICATION_JSON) @ApiOperation(value = "getDocuments: return Document uris corresponding to the specified query") public Response getDocuments(@QueryParam("query") String query, @DefaultValue("1") @QueryParam("page") int page, @DefaultValue("100") @QueryParam("size") int size) { // add paginaton, pattern logger.trace("getDocuments.enter; query: {}, page: {}, size: {}", query, page, size); DocumentManagement docMgr = getDocManager(); try { Collection<String> uris = docMgr.getDocumentUris(query, null); uris = new ArrayList<>(uris); Collections.sort((List) uris); DocumentBean[] docs = new DocumentBean[size]; long now = new java.util.Date().getTime(); int start = page == 0 ? 0 : (page - 1) * size; if (start >= uris.size()) { start = uris.size() - size; } for (int i = 0; i < size && start + i < uris.size(); i++) { String uri = ((List<String>) uris).get(i); docs[i] = new DocumentBean(uri, now, "owner", "utf-8", 1000); } return Response.ok(docs).build(); } catch (Exception ex) { logger.error("getDocuments.error", ex); throw new WebApplicationException(ex, Status.INTERNAL_SERVER_ERROR); } }

Example 5

@ApiOperation(notes = "Retrieves a list of the Consumers", value = "list", response = Consumer.class, responseContainer = "list") @ApiResponses({ @ApiResponse(code = 400, message = ""), @ApiResponse(code = 404, message = "") }) @GET @Produces(MediaType.APPLICATION_JSON) @Wrapped(element = "consumers") @Paginate @SuppressWarnings("checkstyle:indentation") public CandlepinQuery<Consumer> list(@QueryParam("username") String userName, @QueryParam("type") Set<String> typeLabels, @QueryParam("owner") String ownerKey, @QueryParam("uuid") List<String> uuids, @QueryParam("hypervisor_id") List<String> hypervisorIds, @QueryParam("fact") @CandlepinParam(type = KeyValueParameter.class) List<KeyValueParameter> attrFilters, @Context PageRequest pageRequest) { if (userName == null && (typeLabels == null || typeLabels.isEmpty()) && ownerKey == null && (uuids == null || uuids.isEmpty()) && (hypervisorIds == null || hypervisorIds.isEmpty()) && (attrFilters == null || attrFilters.isEmpty())) { throw new BadRequestException(i18n.tr("Must specify at least one search criteria.")); } Owner owner = null; if (ownerKey != null) { owner = ownerCurator.lookupByKey(ownerKey); if (owner == null) { throw new NotFoundException(i18n.tr("owner with key: {0} was not found.", ownerKey)); } } List<ConsumerType> types = consumerTypeValidator.findAndValidateTypeLabels(typeLabels); return this.consumerCurator.searchOwnerConsumers(owner, userName, types, uuids, hypervisorIds, attrFilters, Collections.<String>emptyList(), Collections.<String>emptyList(), Collections.<String>emptyList()); }

Example 6

@POST @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @ApiOperation(value = "Creates new project", response = ProjectConfigDto.class) @ApiResponses({ @ApiResponse(code = 200, message = "OK"), @ApiResponse(code = 403, message = "Operation is forbidden"), @ApiResponse(code = 409, message = "Project with specified name already exist in workspace"), @ApiResponse(code = 500, message = "Server error") }) @GenerateLink(rel = LINK_REL_CREATE_PROJECT) public /** * NOTE: parentPath is added to make a module */ ProjectConfigDto createProject(@ApiParam(value = "Add to this project as module", required = false) @Context UriInfo uriInfo, @Description("descriptor of project") ProjectConfigDto projectConfig) throws ConflictException, ForbiddenException, ServerException, NotFoundException { Map<String, String> options = new HashMap<>(); MultivaluedMap<String, String> map = uriInfo.getQueryParameters(); for (String key : map.keySet()) { options.put(key, map.get(key).get(0)); } String pathToProject = projectConfig.getPath(); String pathToParent = pathToProject.substring(0, pathToProject.lastIndexOf("/")); if (!pathToParent.equals("/")) { VirtualFileEntry parentFileEntry = projectManager.getProjectsRoot().getChild(pathToParent); if (parentFileEntry == null) { throw new NotFoundException("The parent folder with path " + pathToParent + " does not exist."); } } final RegisteredProject project = projectManager.createProject(projectConfig, options); final ProjectConfigDto configDto = asDto(project); eventService.publish(new ProjectCreatedEvent(workspace, project.getPath())); return injectProjectLinks(configDto); }

Example 7

@Path("/entries") @GET @UnitOfWork @ApiOperation(value = "Get feed entries", notes = "Get a list of feed entries", response = Entries.checkNotNull(id); Preconditions.checkNotNull(readType); keywords = StringUtils.trimToNull(keywords); Preconditions.checkArgument(keywords == null || StringUtils.length(keywords) >= 3); List<FeedEntryKeyword> entryKeywords = FeedEntryKeyword.fromQueryString(keywords); limit = Math.min(limit, 1000); limit = Math.max(0, limit); Entries entries = new Entries(); entries.setOffset(offset); entries.setLimit(limit); boolean unreadOnly = readType == ReadingMode.unread; Date newerThanDate = newerThan == null ? null : new Date(newerThan); FeedSubscription subscription = feedSubscriptionDAO.findById(user, Long.valueOf(id)); if (subscription != null) { entries.setName(subscription.getTitle()); entries.setMessage(subscription.getFeed().getMessage()); entries.setErrorCount(subscription.getFeed().getErrorCount()); entries.setFeedLink(subscription.getFeed().getLink()); List<FeedEntryStatus> list = feedEntryStatusDAO.findBySubscriptions(user, Arrays.asList(subscription), unreadOnly, entryKeywords, newerThanDate, offset, limit + 1, order, true, onlyIds, null); for (FeedEntryStatus status : list) { entries.getEntries().add(Entry.build(status, config.getApplicationSettings().getPublicUrl(), config.getApplicationSettings().getImageProxyEnabled())); } boolean hasMore = entries.getEntries().size() > limit; if (hasMore) { entries.setHasMore(true); entries.getEntries().remove(entries.getEntries().size() - 1); } } else { return Response.status(Status.NOT_FOUND).entity("<message>feed not found</message>").build(); } entries.setTimestamp(System.currentTimeMillis()); entries.setIgnoredReadStatus(keywords != null); FeedUtils.removeUnwantedFromSearch(entries.getEntries(), entryKeywords); return Response.ok(entries).build(); }

Example 8

@POST @UnitOfWork @ApiOperation(value = "Add a new registration") @ApiResponses({ @ApiResponse(code = HttpStatus.CREATED_201, message = ApiResponseConstants.Created.MESSAGE, responseHeaders = { @ResponseHeader(name = ApiResponseConstants.Created.Headers.NAME, description = ApiResponseConstants.Created.Headers.DESCRIPTION, response = String.class) }), @ApiResponse(code = HttpStatus.NOT_FOUND_404, response = ErrorMessage.class, message = "No event with given ID"), @ApiResponse(code = HttpStatus.UNPROCESSABLE_ENTITY_422, response = ValidationErrorMessage.class, message = "Failed validation") }) public Response addRegistration(@PathParam("eventId") @ApiParam(value = "Event ID", required = true) String eventId, @Valid @ApiParam(value = "Registration", required = true) AddRegistrationRequest request) throws AddEntityException, EntityNotFoundException { RegistrationAddPayload addPayload = registrationMapper.toDomainAddPayload(request, eventId); Registration domainEntity = eventRegistrationService.add(addPayload); RegistrationApiEntity registration = registrationMapper.toApiEntity(domainEntity); return Response.created(UriBuilder.fromPath("/events/{eventId}/registrations/{registrationId}").build(eventId, registration.getId())).build(); }

Example 9

@POST @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @ApiOperation(value = "Creates new project", response = ProjectConfigDto.class) @ApiResponses({ @ApiResponse(code = 200, message = "OK"), @ApiResponse(code = 403, message = "Operation is forbidden"), @ApiResponse(code = 409, message = "Project with specified name already exist in workspace"), @ApiResponse(code = 500, message = "Server error") }) @GenerateLink(rel = LINK_REL_CREATE_PROJECT) public /** * NOTE: parentPath is added to make a module */ ProjectConfigDto createProject(@ApiParam(value = "Add to this project as module", required = false) @Context UriInfo uriInfo, @Description("descriptor of project") ProjectConfigDto projectConfig) throws ConflictException, ForbiddenException, ServerException, NotFoundException { Map<String, String> options = new HashMap<>(); MultivaluedMap<String, String> map = uriInfo.getQueryParameters(); for (String key : map.keySet()) { options.put(key, map.get(key).get(0)); } String pathToProject = projectConfig.getPath(); String pathToParent = pathToProject.substring(0, pathToProject.lastIndexOf("/")); if (!pathToParent.equals("/")) { VirtualFileEntry parentFileEntry = projectManager.getProjectsRoot().getChild(pathToParent); if (parentFileEntry == null) { throw new NotFoundException("The parent folder with path " + pathToParent + " does not exist."); } } final RegisteredProject project = projectManager.createProject(projectConfig, options); final ProjectConfigDto configDto = asDto(project); eventService.publish(new ProjectCreatedEvent(workspace, project.getPath())); return injectProjectLinks(configDto); }

Example 10

@GET @ApiOperation(value = "Returns the status of the service", response = SystemStatus.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "OK"), @ApiResponse(code = 500, message = "Something wrong in Server") }) public SystemStatus status() { try { if (null != graphFactory.getGraph()) { return new SystemStatus("The system is working normally."); } } catch (final Exception e) { throw new GafferRuntimeException("Unable to create graph.", e, Status.INTERNAL_SERVER_ERROR); } return new SystemStatus("Unable to create graph."); }

Example 11

@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()); }

Example 12

@POST @Path("/") @ApiOperation(value = "Create gauge metric.", notes = "Clients are not required to explicitly create " + "a metric before storing data. Doing so however allows clients to prevent naming collisions and to " + "specify tags and data retention.") @ApiResponses(value = { @ApiResponse(code = 201, message = "Metric created successfully"), @ApiResponse(code = 400, message = "Missing or invalid payload", response = ApiError.class), @ApiResponse(code = 409, message = "Gauge metric with given id already exists", response = ApiError.class), @ApiResponse(code = 500, message = "Metric creation failed due to an unexpected error", response = ApiError.class) }) public void createMetric(@Suspended final AsyncResponse asyncResponse, @ApiParam(required = true) Metric<Double> metric, @ApiParam(value = "Overwrite previously created metric configuration if it exists. " + "Only data retention and tags are overwriten; existing data points are unnafected. " + "Defaults to false.") @DefaultValue("false") @QueryParam("overwrite") Boolean overwrite, @Context UriInfo uriInfo) { if (metric.getType() != null && UNDEFINED != metric.getType() && GAUGE != metric.getType()) { asyncResponse.resume(badRequest(new ApiError("Metric type does not match " + GAUGE.getText()))); } metric = new Metric<>(new MetricId<>(getTenant(), GAUGE, metric.getId()), metric.getTags(), metric.getDataRetention()); URI location = uriInfo.getBaseUriBuilder().path("/gauges/{id}").build(metric.getMetricId().getName()); metricsService.createMetric(metric, overwrite).subscribe(new MetricCreatedObserver(asyncResponse, location)); }

Example 13

@GET @Path("{id}/actions/allowed") @Produces(MediaType.APPLICATION_JSON) @ApiOperation("Gets the list of actions permitted for the given username and/or groups.") @ApiResponses({ @ApiResponse(code = 200, message = "Returns the actions.", response = ActionGroup.class), @ApiResponse(code = 404, message = "A feed with the given ID does not exist.", response = RestResponseStatus.class) }) public ActionGroup getAllowedActions(@PathParam("id") String feedIdStr, @QueryParam("user") Set<String> userNames, @QueryParam("group") Set<String> groupNames) { LOG.debug("Get allowed actions for feed: {}", feedIdStr); Set<? extends Principal> users = Arrays.stream(this.actionsTransform.asUserPrincipals(userNames)).collect(Collectors.toSet()); Set<? extends Principal> groups = Arrays.stream(this.actionsTransform.asGroupPrincipals(groupNames)).collect(Collectors.toSet()); return this.securityService.getAllowedFeedActions(feedIdStr, Stream.concat(users.stream(), groups.stream()).collect(Collectors.toSet())).orElseThrow(() -> new WebApplicationException("A feed with the given ID does not exist: " + feedIdStr, Status.NOT_FOUND)); }

Example 14

/* ================= VARIANTS ===================*/ @POST @Path("/variants/search") @Consumes(MediaType.APPLICATION_JSON) @ApiOperation(value = "Description", position = 1, notes = "Notes") public Response searchVariants(SearchVariantsRequest request) { String method = "ga4gh/variants/search"; try { if (request.getVariantSetId() == null || request.getVariantSetId().isEmpty()) { return createErrorResponse(method, "Required referenceName or referenceId"); } QueryOptions queryOptions = new QueryOptions(uriInfo.getQueryParameters(), true); queryOptions.append(STUDIES.key(), request.getVariantSetId()); // queryOptions.append(, request.getVariantName()); //TODO if (request.getCallSetIds() != null) { queryOptions.append(RETURNED_SAMPLES.key(), request.getCallSetIds()); } CharSequence chr = null; if (request.getReferenceName() != null) { chr = request.getReferenceName(); } if (chr == null) { return createErrorResponse(method, "Required referenceName or referenceId"); } if (request.getStart() == null || request.getStart() < 0) { return createErrorResponse(method, "Required start position"); } if (request.getEnd() == null || request.getEnd() < 0) { return createErrorResponse(method, "Required end position"); } long delta = request.getEnd() - request.getStart(); if (delta < 0) /* || delta > 20000*/ { return createErrorResponse(method, "End must be behind the start"); } queryOptions.append(REGION.key(), new Region(chr.toString(), request.getStart().intValue(), request.getEnd().intValue())); if (request.getPageSize() == null || request.getPageSize() <= 0 || request.getPageSize() > 4000) { this.queryOptions.add(QueryOptions.LIMIT, 1000); } else { this.queryOptions.add(QueryOptions.LIMIT, request.getPageSize()); } int page = 0; if (request.getPageToken() != null) { try { page = Integer.parseInt(request.getPageToken().toString()); this.queryOptions.put("skip", this.queryOptions.getInt("limit") * page); } catch (Exception e) { return createErrorResponse(method, "Invalid page token \"" + request.getPageToken() + "\""); } } // Get all query options SearchVariantsResponse response = new SearchVariantsResponse(); Query query = VariantStorageManager.getVariantQuery(queryOptions); List<Variant> variants = variantManager.get(query, queryOptions, sessionId, Variant.class).getResult(); response.setNextPageToken(Integer.toString(++page)); response.setVariants(variants); return buildResponse(Response.ok(response.toString(), MediaType.APPLICATION_JSON_TYPE)); } catch (Exception e) { return createErrorResponse(e); } }

Example 15

@GET @Path("/tables") @Produces(MediaType.APPLICATION_JSON) //swagger annotations @ApiOperation(value = "List tables", notes = "List all the tables on this server") @ApiResponses(value = { @ApiResponse(code = 200, message = "Success", response = TablesList.class), @ApiResponse(code = 500, message = "Server initialization error", response = ErrorInfo.class) }) public TablesList listTables() { InstanceDataManager dataManager = checkGetInstanceDataManager(); Collection<TableDataManager> tableDataManagers = dataManager.getTableDataManagers(); List<String> tables = new ArrayList<>(tableDataManagers.size()); for (TableDataManager tableDataManager : tableDataManagers) { tables.add(tableDataManager.getTableName()); } return new TablesList(tables); }

Example 16

@GET @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) @ApiOperation(value = "List Representations", notes = "Gets a list of representations.", response = Representations.class, responseContainer = "List") @ApiResponses(value = { @ApiResponse(code = 200, message = "Successful response", response = Representations.class, responseContainer = "List"), @ApiResponse(code = 404, message = "Not found", response = ApiResponseMessage.class) }) public Response listRepresentations(@ApiParam(value = "Index of the first element to return", defaultValue = "0") @QueryParam(RodaConstants.API_QUERY_KEY_START) String start, @ApiParam(value = "Maximum number of elements to return", defaultValue = RodaConstants.DEFAULT_PAGINATION_STRING_VALUE) @QueryParam(RodaConstants.API_QUERY_KEY_LIMIT) String limit, @ApiParam(value = "Choose format in which to get the representation", allowableValues = RodaConstants.API_LIST_MEDIA_TYPES, defaultValue = RodaConstants.API_QUERY_VALUE_ACCEPT_FORMAT_JSON) @QueryParam(RodaConstants.API_QUERY_KEY_ACCEPT_FORMAT) String acceptFormat) throws RODAException { String mediaType = ApiUtils.getMediaType(acceptFormat, request); // get user User user = UserUtility.getApiUser(request); // delegate action to controller boolean justActive = false; Pair<Integer, Integer> pagingParams = ApiUtils.processPagingParams(start, limit); IndexResult<IndexedRepresentation> result = Browser.find(IndexedRepresentation.class, Filter.NULL, Sorter.NONE, new Sublist(pagingParams.getFirst(), pagingParams.getSecond()), null, user, justActive, new ArrayList<>()); return Response.ok(ApiUtils.indexedResultToRODAObjectList(IndexedRepresentation.class, result), mediaType).build(); }

Example 17

@GET @Timed @Produces(MediaType.APPLICATION_JSON) @Path("agreements/{seaCloudsId}") @ApiOperation(value = "Get SLA Agreement for a particular SeaClouds Application Id") public Response getAgreement(@PathParam("seaCloudsId") String seaCloudsId) { if (seaCloudsId == null) { LOG.error("Missing input parameters"); return Response.status(Response.Status.NOT_ACCEPTABLE).build(); } else { SeaCloudsApplicationData seaCloudsApplicationData = dataStore.getSeaCloudsApplicationDataById(seaCloudsId); if (seaCloudsApplicationData == null) { return Response.status(Response.Status.BAD_REQUEST).build(); } if (seaCloudsApplicationData.getAgreementId() == null) { LOG.error("Application " + seaCloudsId + " doesn't contain any agreement"); return Response.status(Response.Status.NOT_FOUND).build(); } return Response.ok(sla.getAgreement(seaCloudsApplicationData.getAgreementId())).build(); } }

Example 18

@ApiOperation(value = "Upload a strongbox.xml and reload the server's configuration.") @ApiResponses(value = { @ApiResponse(code = 200, message = "The configuration was updated successfully."), @ApiResponse(code = 500, message = "An error occurred.") }) @PreAuthorize("hasAuthority('CONFIGURATION_UPLOAD')") @RequestMapping(value = "/xml", method = RequestMethod.PUT, produces = MediaType.TEXT_PLAIN_VALUE, consumes = MediaType.TEXT_PLAIN_VALUE) public ResponseEntity setConfigurationXML(@ApiParam(value = "The strongbox.xml configuration file", required = true) @RequestBody String serializedConfiguration) throws IOException, AuthenticationException, JAXBException { GenericParser<Configuration> parser = new GenericParser<>(Configuration.class); Configuration configuration = parser.deserialize(serializedConfiguration); try { configurationManagementService.setConfiguration(configuration); logger.info("Received new configuration over REST."); return ResponseEntity.ok("The configuration was updated successfully."); } catch (IOExceptionJAXBException | e) { logger.error(e.getMessage(), e); return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR); } }

Example 19

@GET @ApiOperation(value = "Get organizations.", response = ApiResponse.class) public ApiResponse getOrganizations() { Entity org1 = new Entity(); org1.setId(UUID.randomUUID()); org1.setName("org1"); org1.setType("organization"); Entity org2 = new Entity(); org2.setId(UUID.randomUUID()); org2.setName("org2"); org2.setType("organization"); ApiResponse response = new ApiResponse(); response.setContent("All Organizations"); response.setEntities(Lists.newArrayList(org1, org2)); return response; }

Example 20

@GET @ApiOperation(value = "Get organizations.", response = ApiResponse.class) public ApiResponse getOrganizations() { Entity org1 = new Entity(); org1.setId(UUID.randomUUID()); org1.setName("org1"); org1.setType("organization"); Entity org2 = new Entity(); org2.setId(UUID.randomUUID()); org2.setName("org2"); org2.setType("organization"); ApiResponse response = new ApiResponse(); response.setContent("All Organizations"); response.setEntities(Lists.newArrayList(org1, org2)); return response; }

Example 21

@ApiOperation(value = "生�图片验��", notes = "需�传递一个uuid作为用户本次登录的唯一表示") @ApiImplicitParam(name = "uid", value = "�个 uid 对应一次用户登录", required = true, dataType = "String") @RequestMapping(value = "/verify/image", method = RequestMethod.GET) public void verifyimage(String uid, HttpServletResponse response) { response.setHeader("Pragma", "No-cache"); response.setHeader("Cache-Control", "no-cache"); response.setDateHeader("Expires", 0); response.setContentType("image/jpeg"); //生��机字串 String verifyCode = VerifyCodeUtils.generateVerifyCode(4); //存入Redis String key = VERIFYCODE + uid; jedisClient.set(key, verifyCode); jedisClient.expire(key, EXPIRE_TIME); //生�图片 int w = 100, h = 30; try { VerifyCodeUtils.outputImage(w, h, response.getOutputStream(), verifyCode); } catch (IOException e) { logger.error("验��生�失败", e); } }

Example 22

@POST @Consumes(MediaType.APPLICATION_JSON) @ApiOperation("create new Resource") public Response createResource(@NotNull @Valid @WithoutId ResourcePrototype protoType) { // Log.trace("protoType=[{}]", protoType); protoType.setState(AlexandriaState.TENTATIVE); final ResourceCreationRequest request = requestBuilder.build(protoType); AlexandriaResource resource = request.execute(service); if (request.wasExecutedAsIs()) { return noContent(); } return created(resource); }

Example 23

@ApiOperation(value = "Creates a new Session and returns the Session's data", nickname = "postNewSession") @ApiResponses(value = { @ApiResponse(code = 201, message = HTML_STATUS_201), @ApiResponse(code = 503, message = HTML_STATUS_503) }) @RequestMapping(value = "/", method = RequestMethod.POST) @ResponseStatus(HttpStatus.CREATED) public Session postNewSession(@ApiParam(value = "current session", required = true) @RequestBody final Session session, final HttpServletResponse response) { if (session != null && session.isCourseSession()) { final List<Course> courses = new ArrayList<>(); final Course course = new Course(); course.setId(session.getCourseId()); courses.add(course); final int sessionCount = sessionService.countSessions(courses); if (sessionCount > 0) { final String appendix = " (" + (sessionCount + 1) + ")"; session.setName(session.getName() + appendix); session.setShortName(session.getShortName() + appendix); } } final Session newSession = sessionService.saveSession(session); if (newSession == null) { response.setStatus(HttpStatus.SERVICE_UNAVAILABLE.value()); return null; } return newSession; }

Example 24

@ApiOperation("Get Repo Content Result.") @ApiResponses({ @ApiResponse(code = 200, response = RepoContentResult.class, message = "Repo Content Result") }) @Path("/content") @Produces({ "application/json", "application/indy*+json" }) @POST public RepoContentResult getRepoContent(final RepositoryContentRequest request, @Context final UriInfo uriInfo) { Response response = null; try { final String baseUri = uriInfo.getAbsolutePathBuilder().path("api").build().toString(); return controller.getRepoContent(request, baseUri); } catch (final CartoRESTException e) { logger.error(e.getMessage(), e); response = formatResponse(e); } return null; }

Example 25

@ApiOperation(value = "Contributor", notes = "The Contributors endpoint returns all information like name, url, commits count, \nprojects count of all the Contributors for the selected filter. \n", response = Contributor.class, responseContainer = "List") @ApiResponses(value = { @ApiResponse(code = 200, message = "An array of Contributors of selected Github organization"), @ApiResponse(code = 0, message = "Unexpected error") }) @RequestMapping(value = "", method = RequestMethod.GET) @ResponseBody public List<Contributor> contributorsGet(// @ApiParam(value = "List of github.com organizations to scan(comma seperated)", required = true) // @RequestParam(value = Constants.API_REQUEST_PARAM_ORGANIZATIONS, required = true) String // organizations, // @ApiParam(value = "Number of items to retrieve. Default is 5.") // @RequestParam(value = Constants.API_REQUEST_PARAM_LIMIT, required = false) Integer // limit, // @ApiParam(value = "Offset the list of returned results by this amount. Default is zero.") // @RequestParam(value = Constants.API_REQUEST_PARAM_OFFSET, required = false) Integer // offset, // @ApiParam(value = "Date from which to start fetching records from database(default = current_date)") // @RequestParam(value = Constants.API_REQUEST_PARAM_STARTDATE, required = false) String // startDate, // @ApiParam(value = "Date till which records will be fetched from database(default = current_date)") // @RequestParam(value = Constants.API_REQUEST_PARAM_ENDDATE, required = false) String // endDate, @ApiParam(value = "parameter by which result should be sorted. '-' means descending order (default is count of commit)") // @RequestParam(value = Constants.API_REQUEST_PARAM_SORTBY, required = false) String // sortBy, // @ApiParam(value = "query paramater for search query (this will be contributor names prefix)") // @RequestParam(value = Constants.API_REQUEST_PARAM_Q, required = false) String // q) { validate(organizations, offset, limit, sortBy, startDate, endDate); if (startDate != null && endDate != null && repository.findPreviousSnapShotDate(iso8601(endDate)) != null && repository.findPreviousSnapShotDate(iso8601(startDate)) != null) { return contributorsGet_timeSpan(organizations, limit, offset, startDate, endDate, sortBy, q); } else if (// startDate == null && endDate == null && repository.findPreviousSnapShotDate(from(now())) != null) { return contributorsGet_noTimeSpan(organizations, limit, offset, endDate, sortBy, q); } else { throw new UnsupportedOperationException("this parameter configuration is not implemented yet" + " .. start date, end date required atm"); } }

Example 26

/** * 分页查询app下的service信�. */ @RequestMapping(value = "/projects/services", method = RequestMethod.GET) @ApiOperation(value = ApiDocs.SEARCH_APP_SERVICES_PAGE, notes = ApiDocs.SEARCH_APP_SERVICES_PAGE) public // Page<ServiceInfo> searchServices(// @RequestParam("appId") final int appId, // @RequestParam("searchText") final String searchText, @// PageableDefault(// page = DEFAULT_PAGE_NUM, // size = DEFAULT_PAGE_SIZE, sort = "id", direction = Direction.ASC) final Pageable pageable) { final Page<ServiceInfo> pageResult; if (StringUtils.isBlank(searchText)) { pageResult = serviceService.getServicesByAppId(appId, pageable); } else { pageResult = serviceService.findByAppIdAndserviceNameLike(appId, searchText, pageable); } return pageResult; }

Example 27

@Path("/pipelines/labels") @GET @ApiOperation(value = "Returns all Pipeline labels", response = List.class, responseContainer = "List", authorizations = @Authorization(value = "basic")) @Produces(MediaType.APPLICATION_JSON) @PermitAll public Response getPipelineLabels() throws PipelineStoreException { final List<PipelineInfo> pipelineInfoList = store.getPipelines(); Set<String> pipelineLabels = new HashSet<>(); for (PipelineInfo pipelineInfo : pipelineInfoList) { Map<String, Object> metadata = pipelineInfo.getMetadata(); if (metadata != null && metadata.containsKey("labels")) { List<String> labels = (List<String>) metadata.get("labels"); pipelineLabels.addAll(labels); } } return Response.ok().type(MediaType.APPLICATION_JSON).entity(pipelineLabels).build(); }

Example 28

@GET @Path("/") @Produces(APPLICATION_JSON) @ApiOperation(value = "Get triggers with optional filtering.", notes = "If not criteria defined, it fetches all triggers stored in the system.", response = Trigger.class, responseContainer = "List") @ApiResponses(value = { @ApiResponse(code = 200, message = "Successfully fetched list of triggers."), @ApiResponse(code = 400, message = "Bad request/Invalid Parameters.", response = ApiError.class), @ApiResponse(code = 500, message = "Internal server error.", response = ApiError.class) }) @QueryParamValidation(name = "findTriggers") public Response findTriggers(@ApiParam(required = false, value = "Filter out triggers for unspecified triggerIds. ", allowableValues = "Comma separated list of trigger IDs.") @QueryParam("triggerIds") final String triggerIds, @ApiParam(required = false, value = "Filter out triggers for unspecified tags.", allowableValues = "Comma separated list of tags, each tag of format 'name\\|value'. + \n" + "Specify '*' for value to match all values.") @QueryParam("tags") final String tags, @ApiParam(required = false, value = "Return only thin triggers. Currently Ignored.") @QueryParam("thin") final Boolean thin, @Context final UriInfo uri) { try { ResponseUtil.checkForUnknownQueryParams(uri, queryParamValidationMap.get("findTriggers")); Pager pager = RequestUtil.extractPaging(uri); TriggersCriteria criteria = buildCriteria(triggerIds, tags, thin); Page<Trigger> triggerPage = definitions.getTriggers(tenantId, criteria, pager); log.debugf("Triggers: %s", triggerPage); if (isEmpty(triggerPage)) { return ResponseUtil.ok(triggerPage); } return ResponseUtil.paginatedOk(triggerPage, uri); } catch (Exception e) { return ResponseUtil.onException(e, log); } }

Example 29

@POST @javax.ws.rs.Path("/{environmentId}/resources") @ApiOperation("Creates a new resource") @ApiResponses({ @ApiResponse(code = 201, message = "Resource successfully created"), @ApiResponse(code = 400, message = "Invalid input data", response = ApiError.class), @ApiResponse(code = 404, message = "Tenant or environment doesn't exist", response = ApiError.class), @ApiResponse(code = 409, message = "Resource already exists", response = ApiError.class), @ApiResponse(code = 500, message = "Server error", response = ApiError.class) }) public Response addResource(@PathParam("environmentId") String environmentId, @ApiParam(required = true) Resource.Blueprint resource, @Context UriInfo uriInfo) { String tenantId = getTenantId(); CanonicalPath env = CanonicalPath.of().tenant(tenantId).environment(environmentId).get(); if (!security.canCreate(Resource.class).under(env)) { return Response.status(FORBIDDEN).build(); } Resource entity = inventory.inspect(env, Environments.Single.class).resources().create(resource).entity(); return ResponseUtil.created(entity, uriInfo, resource.getId()).build(); }

Example 30

/** * @code code == 0 创建�功, body = �登陆账�的accountId; * @code code == 11 => 昵称��; * @code code == 12 => 邮箱��; * @code code == 13 => 手机��; * @code code == 8888 => 信�有误, extra = 错误信�; * @code code == 9999 => 系统异常; */ @ApiOperation(value = "创建账�", notes = "创建账�") @ApiResponse(code = 200, message = "�功") @RequestMapping(value = "/create_account", method = RequestMethod.POST) public ResponseEntity<TcR<String>> createAccount(@RequestBody TiAccount tiAccount, HttpServletRequest request) { Set<ConstraintViolation<TiAccount>> violations = validator.validate(tiAccount); if (!violations.isEmpty()) { List<String> errs = violations.stream().map(ConstraintViolation::getMessage).collect(Collectors.toList()); return ResponseEntity.ok(TcR.br(errs)); } tiAccount.setSigninIp(TcServletUtils.extractIp(request)).setSigninPlatform(TmPlatform.PC_PLATFORM).setCreatedPerson(tcSessionService.getAccountId()); TcR<String> tcR = tcAccountApi.createAccount(tiAccount); return ResponseEntity.ok(tcR); }

Example 31

@GET @Path("/sql") @ApiOperation(value = "Create a cohort", position = 1, notes = "", response = String.class) public Response getSqlQuery(@ApiParam(value = "table", required = true) @QueryParam("table") String table, @ApiParam(value = "id") @QueryParam("id") String id, @ApiParam(value = "ancestralAllele") @QueryParam("ancestralAllele") String ancestralAllele, @ApiParam(value = "displayConsequenceType") @QueryParam("displayConsequenceType") String displayConsequenceType, @ApiParam(value = "xrefs") @QueryParam("xrefs") String xrefs, @ApiParam(value = "hgvs") @QueryParam("hgvs") String hgvs, @ApiParam(value = "consequenceTypes") @QueryParam("consequenceTypes") String consequenceTypes, @ApiParam(value = "consequenceTypes.sequenceOntologyTerms.accession") @QueryParam("consequenceTypes.sequenceOntologyTerms.accession") String consequenceSoAccession, @ApiParam(value = "consequenceTypes.sequenceOntologyTerms.name") @QueryParam("consequenceTypes.sequenceOntologyTerms.name") String consequenceSoName, @ApiParam(value = "populationFrequencies") @QueryParam("populationFrequencies") String populationFrequencies, @ApiParam(value = "conservation") @QueryParam("conservation") String conservation, @ApiParam(value = "variantTraitAssociation") @QueryParam("variantTraitAssociation") String variantTraitAssociation) { try { Query query = new Query(); query.putIfNotEmpty("id", id); query.putIfNotEmpty("ancestralAllele", ancestralAllele); query.putIfNotEmpty("displayConsequenceType", displayConsequenceType); query.putIfNotEmpty("xrefs", xrefs); query.putIfNotEmpty("hgvs", hgvs); query.putIfNotEmpty("annotation.consequenceTypes", consequenceTypes); query.putIfNotEmpty("annotation.populationFrequencies", populationFrequencies); query.putIfNotEmpty("annotation.consequenceTypes.sequenceOntologyTerms.accession", consequenceSoAccession); query.putIfNotEmpty("annotation.consequenceTypes.sequenceOntologyTerms.name", consequenceSoName); query.putIfNotEmpty("annotation.conservation", conservation); query.putIfNotEmpty("annotation.variantTraitAssociation", variantTraitAssociation); VariantParseQuery variantParseQuery = new VariantParseQuery(); String sql = variantParseQuery.parse(query, null, table); return Response.ok(sql).build(); } catch (Exception e) { return Response.ok(e.toString()).build(); } }

Example 32

@Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { try { Object result1 = method.invoke(result0, args); Class<?> type = String.class; if (result1 instanceof Response) { Response resp = (Response) result1; if (isStatusCodeHealthy(resp.getStatus()) && method.isAnnotationPresent(ApiOperation.class)) { type = getClassFromMethodAnnotationOrDefault(method, type); } // wrap the original response so it self-closes result1 = BuiltResponsePreservingError.copyResponseAndClose(resp, type); } return result1; } catch (Throwable e) { if (e instanceof InvocationTargetException) { e = ((InvocationTargetException) e).getTargetException(); } throw Exceptions.propagate(e); } }

Example 33

@ApiOperation(value = "[vote] Vote on an article", notes = "Vote on an article. Note that kaif do not support DOWN vote on article.") @RequiredScope(VOTE) @RequestMapping(value = "/article", method = RequestMethod.POST, consumes = { MediaType.APPLICATION_JSON_VALUE }) public void article(ClientAppUserAccessToken token, @Valid @RequestBody VoteArticleEntry entry) { ignoreDuplicateVote(() -> { VoteState previousState = voteService.listArticleVoters(token, asList(entry.articleId)).stream().map(ArticleVoter::getVoteState).findAny().orElse(VoteState.EMPTY); //for api, we don't hack previousCount. this may cause user see stale total counting int previousCount = 0; voteService.voteArticle(entry.voteState, entry.articleId, token, previousState, previousCount); }); }

Example 34

@TimedResource @GET @Path("/{accountId:" + UUID_PATTERN + "}") @Produces(APPLICATION_JSON) @ApiOperation(value = "Retrieve an account by id", response = AccountJson.class) @ApiResponses(value = { @ApiResponse(code = 400, message = "Invalid account id supplied"), @ApiResponse(code = 404, message = "Account not found") }) public Response getAccount(@PathParam("accountId") final String accountId, @QueryParam(QUERY_ACCOUNT_WITH_BALANCE) @DefaultValue("false") final Boolean accountWithBalance, @QueryParam(QUERY_ACCOUNT_WITH_BALANCE_AND_CBA) @DefaultValue("false") final Boolean accountWithBalanceAndCBA, @QueryParam(QUERY_AUDIT) @DefaultValue("NONE") final AuditMode auditMode, @javax.ws.rs.core.Context final HttpServletRequest request) throws AccountApiException { final TenantContext tenantContext = context.createContext(request); final Account account = accountUserApi.getAccountById(UUID.fromString(accountId), tenantContext); final AccountAuditLogs accountAuditLogs = auditUserApi.getAccountAuditLogs(account.getId(), auditMode.getLevel(), tenantContext); final AccountJson accountJson = getAccount(account, accountWithBalance, accountWithBalanceAndCBA, accountAuditLogs, tenantContext); return Response.status(Status.OK).entity(accountJson).build(); }

Example 35

@GET @Path("/{sitemapname: [a-zA-Z_0-9]*}") @Produces(MediaType.APPLICATION_JSON) @ApiOperation(value = "Get sitemap by name.", response = SitemapDTO.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "OK") }) public Response getSitemapData(@Context HttpHeaders headers, @HeaderParam(HttpHeaders.ACCEPT_LANGUAGE) @ApiParam(value = "language") String language, @PathParam("sitemapname") @ApiParam(value = "sitemap name") String sitemapname, @QueryParam("type") String type, @QueryParam("jsoncallback") @DefaultValue("callback") String callback) { final Locale locale = LocaleUtil.getLocale(language); logger.debug("Received HTTP GET request at '{}' for media type '{}'.", new Object[] { uriInfo.getPath(), type }); Object responseObject = getSitemapBean(sitemapname, uriInfo.getBaseUriBuilder().build(), locale); return Response.ok(responseObject).build(); }

Example 36

@GET @Path("/status") @ApiOperation(value = "get customer status", notes = "get customer status as xml/json") @ApiResponses({ @ApiResponse(code = 404, message = "Customer not found") }) public CustomerStatus size() { CustomerStatus status = new CustomerStatus(); status.setSize(data.getCustomerList().size()); HeapSize jvm = new HeapSize(); jvm.setMaxMemory(Runtime.getRuntime().maxMemory()); jvm.setFreeMemory(Runtime.getRuntime().freeMemory()); jvm.setAllocatedMemory(Runtime.getRuntime().totalMemory()); status.setHeap(jvm); return status; }

Example 37

static SwaggerOperation parseSwaggerAnnotations(Method method) { final SwaggerOperation swaggerOperation = new SwaggerOperation(); // @ApiOperation { final Annotation apiOperation = Utils.getAnnotation(method, "io.swagger.annotations.ApiOperation"); if (apiOperation != null) { final Class<?> response = Utils.getAnnotationElementValue(apiOperation, "response", Class.class); final String responseContainer = Utils.getAnnotationElementValue(apiOperation, "responseContainer", String.class); if (responseContainer == null || responseContainer.isEmpty()) { swaggerOperation.responseType = response; } else { switch(responseContainer) { case "List": swaggerOperation.responseType = Utils.createParameterizedType(List.class, response); break; case "Set": swaggerOperation.responseType = Utils.createParameterizedType(Set.class, response); break; case "Map": swaggerOperation.responseType = Utils.createParameterizedType(Map.class, String.class, response); break; } } swaggerOperation.hidden = Utils.getAnnotationElementValue(apiOperation, "hidden", Boolean.class); swaggerOperation.comment = Utils.getAnnotationElementValue(apiOperation, "value", String.class); swaggerOperation.comment = swaggerOperation.comment.isEmpty() ? null : swaggerOperation.comment; } } // @ApiResponses { final Annotation[] apiResponses = Utils.getAnnotationElementValue(method, "io.swagger.annotations.ApiResponses", "value", Annotation[].class); if (apiResponses != null) { swaggerOperation.possibleResponses = new ArrayList<>(); for (Annotation apiResponse : apiResponses) { final SwaggerResponse response = new SwaggerResponse(); response.code = Utils.getAnnotationElementValue(apiResponse, "code", Integer.class); response.comment = Utils.getAnnotationElementValue(apiResponse, "message", String.class); response.responseType = Utils.getAnnotationElementValue(apiResponse, "response", Class.class); swaggerOperation.possibleResponses.add(response); } } } return swaggerOperation; }

Example 38

/** * Create the feature if not exist or update it * * @param headers * current request header * @param data * feature serialized as JSON * @return 204 or 201 */ @PUT @RolesAllowed({ ROLE_WRITE }) @ApiOperation(value = "Create of update a feature", response = Response.class) @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @ApiResponses({ @ApiResponse(code = 201, message = "Feature has been created"), @ApiResponse(code = 204, message = "No content, feature is updated") }) public Response upsertFeature(@Context HttpHeaders headers, @PathParam("uid") String id, FeatureApiBean fApiBean) { // Parameter validations if ("".equals(id) || !id.equals(fApiBean.getUid())) { String errMsg = "Invalid identifier expected " + id; return Response.status(Response.Status.BAD_REQUEST).entity(errMsg).build(); } Feature feat = new Feature(id); feat.setDescription(fApiBean.getDescription()); feat.setEnable(fApiBean.isEnable()); feat.setGroup(fApiBean.getGroup()); feat.setPermissions(new HashSet<String>(fApiBean.getPermissions())); // Flipping Strategy FlippingStrategyApiBean flipApiBean = fApiBean.getFlippingStrategy(); if (flipApiBean != null) { try { Map<String, String> initparams = flipApiBean.getInitParams(); feat.setFlippingStrategy(MappingUtil.instanceFlippingStrategy(id, flipApiBean.getType(), initparams)); } catch (Exception e) { String errMsg = "Cannot read Flipping Strategy, does not seems to have a DEFAULT constructor, " + e.getMessage(); return Response.status(Response.Status.BAD_REQUEST).entity(errMsg).build(); } } // Properties Map<String, PropertyApiBean> mapProperties = fApiBean.getCustomProperties(); if (mapProperties != null) { for (PropertyApiBean propertyBean : mapProperties.values()) { feat.addProperty(propertyBean.asProperty()); } } // Update or create ? if (!getFeatureStore().exist(feat.getUid())) { getFeatureStore().create(feat); String location = String.format("%s", uriInfo.getAbsolutePath().toString()); try { return Response.created(new URI(location)).build(); } catch (URISyntaxException e) { return Response.status(Response.Status.CREATED).header(LOCATION, location).entity(id).build(); } } // Create getFeatureStore().update(feat); return Response.noContent().build(); }

Example 39

/** * Create the feature if not exist or update it * * @param headers * current request header * @param data * feature serialized as JSON * @return 204 or 201 */ @PUT @RolesAllowed({ ROLE_WRITE }) @ApiOperation(value = "Create of update a feature", response = Response.class) @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @ApiResponses({ @ApiResponse(code = 201, message = "Feature has been created"), @ApiResponse(code = 204, message = "No content, feature is updated") }) public Response upsertFeature(@Context HttpHeaders headers, @PathParam("uid") String id, FeatureApiBean fApiBean) { // Parameter validations if ("".equals(id) || !id.equals(fApiBean.getUid())) { String errMsg = "Invalid identifier expected " + id; return Response.status(Response.Status.BAD_REQUEST).entity(errMsg).build(); } Feature feat = new Feature(id); feat.setDescription(fApiBean.getDescription()); feat.setEnable(fApiBean.isEnable()); feat.setGroup(fApiBean.getGroup()); feat.setPermissions(new HashSet<String>(fApiBean.getPermissions())); // Flipping Strategy FlippingStrategyApiBean flipApiBean = fApiBean.getFlippingStrategy(); if (flipApiBean != null) { try { Map<String, String> initparams = flipApiBean.getInitParams(); feat.setFlippingStrategy(MappingUtil.instanceFlippingStrategy(id, flipApiBean.getType(), initparams)); } catch (Exception e) { String errMsg = "Cannot read Flipping Strategy, does not seems to have a DEFAULT constructor, " + e.getMessage(); return Response.status(Response.Status.BAD_REQUEST).entity(errMsg).build(); } } // Properties Map<String, PropertyApiBean> mapProperties = fApiBean.getCustomProperties(); if (mapProperties != null) { for (PropertyApiBean propertyBean : mapProperties.values()) { feat.addProperty(propertyBean.asProperty()); } } // Update or create ? if (!getFeatureStore().exist(feat.getUid())) { getFeatureStore().create(feat); String location = String.format("%s", uriInfo.getAbsolutePath().toString()); try { return Response.created(new URI(location)).build(); } catch (URISyntaxException e) { return Response.status(Response.Status.CREATED).header(LOCATION, location).entity(id).build(); } } // Create getFeatureStore().update(feat); return Response.noContent().build(); }

Example 40

@GET @Path("/{property}/{cluster}/{namespace}") @ApiOperation(value = "Get the list of destinations under a namespace.", response = String.class, responseContainer = "List") @ApiResponses(value = { @ApiResponse(code = 403, message = "Don't have admin permission"), @ApiResponse(code = 404, message = "Namespace doesn't exist") }) public List<String> getList(@PathParam("property") String property, @PathParam("cluster") String cluster, @PathParam("namespace") String namespace) { validateAdminAccessOnProperty(property); // Validate that namespace exists, throws 404 if it doesn't exist try { policiesCache().get(path("policies", property, cluster, namespace)); } catch (KeeperException.NoNodeException e) { log.warn("[{}] Failed to get topic list {}/{}/{}: Namespace does not exist", clientAppId(), property, cluster, namespace); throw new RestException(Status.NOT_FOUND, "Namespace does not exist"); } catch (Exception e) { log.error("[{}] Failed to get topic list {}/{}/{}", clientAppId(), property, cluster, namespace, e); throw new RestException(e); } List<String> destinations = Lists.newArrayList(); try { String path = String.format("/managed-ledgers/%s/%s/%s/%s", property, cluster, namespace, domain()); for (String destination : managedLedgerListCache().get(path)) { if (domain().equals(DestinationDomain.persistent.toString())) { destinations.add(DestinationName.get(domain(), property, cluster, namespace, decode(destination)).toString()); } } } catch (KeeperException.NoNodeException e) { } catch (Exception e) { log.error("[{}] Failed to get destination list for namespace {}/{}/{}", clientAppId(), property, cluster, namespace, e); throw new RestException(e); } destinations.sort(null); return destinations; }

Example 41

/** * Registry user map. ApiOperation(value = "注册用户") public Map<String, Object> registryUser(@ApiParam(required = true, value = "版本", defaultValue = "v1") @PathVariable("version") String version, @Length(min = 6, max = 20, message = "密�长度为6到20") @ApiParam(required = true, value = "密�") @RequestParam("password") String password, @Pattern(regexp = "1(3[0-9]|4[57]|5[0-35-9]|7[01678]|8[0-9])\\d{8}", message = "手机��格�错误") @ApiParam(required = true, value = "手机�") @RequestParam("mobile") String mobile, @Pattern(regexp = "\\d{6}", message = "验��为6�数字") @ApiParam(required = true, value = "短信验��� setMobile(mobile); user.setPassword(passwordEncoder.encode(password)); // 注册 tripUserService.registryUser(mobile, passwordEncoder.encode(password)); Map<String, Object> message = new HashMap<>(); message.put(Message.RETURN_FIELD_CODE, ReturnCode.SUCCESS); return message; }

Example 42

public Swagger read(SpringResource resource) { if (swagger == null) { swagger = new Swagger(); } List<Method> methods = resource.getMethods(); Map<String, Tag> tags = new HashMap<String, Tag>(); List<SecurityRequirement> resourceSecurities = new ArrayList<SecurityRequirement>(); // Add the description from the controller api Class<?> controller = resource.getControllerClass(); RequestMapping controllerRM = AnnotatedElementUtils.findMergedAnnotation(controller, RequestMapping.class); String[] controllerProduces = new String[0]; String[] controllerConsumes = new String[0]; if (controllerRM != null) { controllerConsumes = controllerRM.consumes(); controllerProduces = controllerRM.produces(); } if (controller.isAnnotationPresent(Api.class)) { Api api = AnnotatedElementUtils.findMergedAnnotation(controller, Api.class); if (!canReadApi(false, api)) { return swagger; } tags = updateTagsForApi(null, api); resourceSecurities = getSecurityRequirements(api); } resourcePath = resource.getControllerMapping(); //collect api from method with @RequestMapping Map<String, List<Method>> apiMethodMap = collectApisByRequestMapping(methods); for (String path : apiMethodMap.keySet()) { for (Method method : apiMethodMap.get(path)) { RequestMapping requestMapping = AnnotatedElementUtils.findMergedAnnotation(method, RequestMapping.class); if (requestMapping == null) { continue; } ApiOperation apiOperation = AnnotatedElementUtils.findMergedAnnotation(method, ApiOperation.class); if (apiOperation == null || apiOperation.hidden()) { continue; } Map<String, String> regexMap = new HashMap<String, String>(); String operationPath = parseOperationPath(path, regexMap); //http method for (RequestMethod requestMethod : requestMapping.method()) { String httpMethod = requestMethod.toString().toLowerCase(); Operation operation = parseMethod(method); updateOperationParameters(new ArrayList<Parameter>(), regexMap, operation); updateOperationProtocols(apiOperation, operation); String[] apiProduces = requestMapping.produces(); String[] apiConsumes = requestMapping.consumes(); apiProduces = (apiProduces.length == 0) ? controllerProduces : apiProduces; apiConsumes = (apiConsumes.length == 0) ? controllerConsumes : apiConsumes; apiConsumes = updateOperationConsumes(new String[0], apiConsumes, operation); apiProduces = updateOperationProduces(new String[0], apiProduces, operation); updateTagsForOperation(operation, apiOperation); updateOperation(apiConsumes, apiProduces, tags, resourceSecurities, operation); updatePath(operationPath, httpMethod, operation); } } } return swagger; }

Example 43

@PutMapping(value = "/{envId}", consumes = APPLICATION_JSON_VALUE) @ApiOperation(value = "Updates Test Environment by envId.", notes = "This operation can be performed only if '" + TestEnvUtils.SESSION_COOKIE + "' cookie is " + "present and valid. To obtain this cookie POST to /envs must be performed firstly. " + "This cookie is valid only for Test Environment with " + "envId which was specified in POST request body.") @ApiResponses(value = { @ApiResponse(code = 202, message = "Update is successful."), @ApiResponse(code = 404, message = "Test Environment with provided envId or sessionId is not found."), @ApiResponse(code = 400, message = TestEnvUtils.SESSION_COOKIE + " cookie is not present.") }) public ResponseEntity<?> updateTestEnvironment(@CookieValue(TestEnvUtils.SESSION_COOKIE) String sessionId, @PathVariable String envId, @RequestBody TestEnvironmentEntity testEnv, final HttpServletResponse response) { if (!testEnvService.exists(envId)) throw ResourceNotFoundException.getTestEnvResourceNfe(); if (!testEnvService.existsWithSessionId(envId, sessionId)) throw new TestEnvironmentSessionNotFoundException(envId, sessionId); validateTestEnv(testEnv); testEnv.setEnvironmentId(envId); testEnv.setSessionId(sessionId); TestEnvironmentEntity updated = testEnvService.update(testEnv); if (updated.getStatus() == PENDING) { getTestExecutionToExecute(updated).ifPresent( execution -> response.addHeader(TestEnvUtils.EXECUTION_ID_HEADER, execution.getId().toString())); } response.addCookie(getSessionCookie(updated)); return ResponseEntity.accepted().build(); }

Example 44

@GET @Produces(MediaType.APPLICATION_JSON) @Path(OrcidApiConstants.SWAGGER_FILE) @ApiOperation(value = "The swagger definition in JSON", hidden = true) public Response getListingJson(@Context Application app, @Context HttpHeaders headers, @Context UriInfo uriInfo) { Swagger swagger = (Swagger) context.getAttribute("swagger"); if (!initialized) { swagger = scan(app); } if (swagger != null) { SwaggerSpecFilter filterImpl = FilterFactory.getFilter(); if (filterImpl != null) { SpecFilter f = new SpecFilter(); swagger = f.filter(swagger, filterImpl, getQueryParams(uriInfo.getQueryParameters()), getCookies(headers), getHeaders(headers)); } return Response.ok().entity(swagger).build(); } else { return Response.status(404).build(); } }

Example 45

@Test public void testBuildArchiveSwagger() throws Exception { VDBMetaData vdb = getTestVDBMetaData(); RestASMBasedWebArchiveBuilder builder = new RestASMBasedWebArchiveBuilder(); MetadataStore metadataStore = vdb.getAttachment(TransformationMetadata.class).getMetadataStore(); for (ModelMetaData model : vdb.getModelMetaDatas().values()) { Schema schema = metadataStore.getSchema(model.getName()); byte[] viewContents = builder.getViewClass(vdb.getName(), vdb.getVersion(), model.getName(), schema, false); if (viewContents != null) { Class<?> cls = ASMUtilities.defineClass("org.teiid.jboss.rest.View", viewContents); Set<Annotation> annotationSet = new HashSet<Annotation>(); for (Annotation annotation : cls.getAnnotations()) { annotationSet.add(annotation); } assertEquals(2, annotationSet.size()); for (Method m : cls.getMethods()) { if (m.getName().equals("g1Tableapplication_xml")) { ApiOperation annotation = m.getAnnotation(ApiOperation.class); assertEquals("g1Table", annotation.value()); } else if (m.getName().equals("sqlQueryxml")) { ApiOperation annotation = m.getAnnotation(ApiOperation.class); assertEquals("xml", annotation.value()); } else if (m.getName().equals("sqlQueryjson")) { ApiOperation annotation = m.getAnnotation(ApiOperation.class); assertEquals("json", annotation.value()); } } } } }

Example 46

@GET @Path("/{id}") @Produces({ "application/json", "application/scim+json" }) @ApiOperation(value = "Return the user with the given id", notes = "Returns HTTP 200 if the user is found.") @ApiResponses(value = { @ApiResponse(code = 200, message = "Valid user is found"), @ApiResponse(code = 404, message = "Valid user is not found") }) public Response getUser(@ApiParam(value = SCIMProviderConstants.ID_DESC, required = true) @PathParam(SCIMProviderConstants.ID) String id, @ApiParam(value = SCIMProviderConstants.ATTRIBUTES_DESC, required = false) @QueryParam(SCIMProviderConstants.ATTRIBUTES) String attribute, @ApiParam(value = SCIMProviderConstants.EXCLUDED_ATTRIBUTES_DESC, required = false) @QueryParam(SCIMProviderConstants.EXCLUDE_ATTRIBUTES) String excludedAttributes) throws FormatNotSupportedException, CharonException { try { // obtain the user store manager UserManager userManager = DefaultCharonManager.getInstance().getUserManager(); // create charon-SCIM user endpoint and hand-over the request. UserResourceManager userResourceManager = new UserResourceManager(); SCIMResponse scimResponse = userResourceManager.get(id, userManager, attribute, excludedAttributes); // appropriately. return buildResponse(scimResponse); } catch (CharonException e) { throw new CharonException(e.getDetail(), e); } }

Example 47

/** * list all parametrized Queries created in a Gemfire data node * * @return result as a JSON document. */ @RequestMapping(method = RequestMethod.GET, produces = { MediaType.APPLICATION_JSON_UTF8_VALUE }) @ApiOperation(value = "list all parametrized queries", notes = "List all parametrized queries by id/name", response = void.class) @ApiResponses({ @ApiResponse(code = 200, message = "OK."), @ApiResponse(code = 401, message = "Invalid Username or Password."), @ApiResponse(code = 403, message = "Insufficient privileges for operation."), @ApiResponse(code = 500, message = "if GemFire throws an error or exception") }) @ResponseBody @ResponseStatus(HttpStatus.OK) @PreAuthorize("@securityService.authorize('DATA', 'READ')") public ResponseEntity<?> list() { logger.debug("Listing all parametrized Queries in GemFire..."); final Region<String, String> parametrizedQueryRegion = getQueryStore(PARAMETERIZED_QUERIES_REGION); String queryListAsJson = JSONUtils.formulateJsonForListQueriesCall(parametrizedQueryRegion); final HttpHeaders headers = new HttpHeaders(); headers.setLocation(toUri("queries")); return new ResponseEntity<>(queryListAsJson, headers, HttpStatus.OK); }

Example 48

//TODO move to ProfileController? /** * Gets the endpoint profile by endpoint group id. * * @param endpointGroupId the endpoint group id * @param limit the limit * @param offset the offset * @param request the request * @return the endpoint profiles page dto * @throws KaaAdminServiceException the kaa admin service exception */ @ApiOperation(value = "Get endpoint profiles based on endpoint group id", notes = "Returns the endpoint profiles based on endpoint group id. " + "Only users with the TENANT_DEVELOPER or TENANT_USER role are allowed " + "to request this information. Default limit value equals \"20\", " + "default offset value equals \"0\". Maximum limit value is \"500\".") @ApiResponses(value = { @ApiResponse(code = 400, message = "Invalid endpointGroupId/limit/offset supplied"), @ApiResponse(code = 401, message = "The user is not authenticated or invalid credentials were provided"), @ApiResponse(code = 403, message = "The authenticated user does not have the " + "required role (TENANT_DEVELOPER or TENANT_USER) or the Tenant ID " + "of the application does not match the Tenant ID of the authenticated user"), @ApiResponse(code = 404, message = "Endpoint group with the specified endpointGroupId does not exist"), @ApiResponse(code = 500, message = "An unexpected error occurred on the server side") }) @RequestMapping(value = "endpointProfileByGroupId", method = RequestMethod.GET, produces = APPLICATION_JSON_VALUE) @ResponseBody public EndpointProfilesPageDto getEndpointProfileByEndpointGroupId(@ApiParam(name = "endpointGroupId", value = "The id of the endpoint group.", required = true) @RequestParam("endpointGroupId") String endpointGroupId, @ApiParam(name = "limit", value = "The maximum number of shown profiles. (optional parameter)", defaultValue = DEFAULT_LIMIT, required = false) @RequestParam(value = "limit", defaultValue = DEFAULT_LIMIT, required = false) String limit, @ApiParam(name = "offset", value = "The offset from beginning of profiles list. (Optional parameter)", defaultValue = DEFAULT_OFFSET, required = false) @RequestParam(value = "offset", defaultValue = DEFAULT_OFFSET, required = false) String offset, HttpServletRequest request) throws KaaAdminServiceException { EndpointProfilesPageDto endpointProfilesPageDto = groupService.getEndpointProfileByEndpointGroupId(endpointGroupId, limit, offset); if (endpointProfilesPageDto.hasEndpointProfiles()) { PageLinkDto pageLinkDto = createNext(endpointProfilesPageDto.getPageLinkDto(), request); endpointProfilesPageDto.setNext(pageLinkDto.getNext()); } return endpointProfilesPageDto; }

Example 49

private Swagger read(Class<?> cls, String parentPath, String parentMethod, boolean isSubresource, String[] parentConsumes, String[] parentProduces, Map<String, Tag> parentTags, List<Parameter> parentParameters, Set<Class<?>> scannedResources) { Map<String, Tag> tags = new LinkedHashMap<String, Tag>(); List<SecurityRequirement> securities = new ArrayList<SecurityRequirement>(); String[] consumes = new String[0]; String[] produces = new String[0]; final Set<Scheme> globalSchemes = EnumSet.noneOf(Scheme.class); Api api = ReflectionUtils.getAnnotation(cls, Api.class); boolean hasPathAnnotation = (ReflectionUtils.getAnnotation(cls, javax.ws.rs.Path.class) != null); boolean hasApiAnnotation = (api != null); boolean isApiHidden = hasApiAnnotation && api.hidden(); // class readable only if annotated with ((@Path and @Api) or isSubresource ) - and @Api not hidden boolean classReadable = ((hasPathAnnotation && hasApiAnnotation) || isSubresource) && !isApiHidden; // with scanAllResources true in config and @Api not hidden scan only if it has also @Path annotation or is subresource boolean scanAll = !isApiHidden && config.isScanAllResources() && (hasPathAnnotation || isSubresource); // readable if classReadable or scanAll boolean readable = classReadable || scanAll; if (!readable) { return swagger; } // api readable only if @Api present; cannot be hidden because checked in classReadable. boolean apiReadable = hasApiAnnotation; if (apiReadable) { // the value will be used as a tag for 2.0 UNLESS a Tags annotation is present Set<String> tagStrings = extractTags(api); for (String tagString : tagStrings) { Tag tag = new Tag().name(tagString); tags.put(tagString, tag); } for (String tagName : tags.keySet()) { swagger.tag(tags.get(tagName)); } if (!api.produces().isEmpty()) { produces = ReaderUtils.splitContentValues(new String[] { api.produces() }); } if (!api.consumes().isEmpty()) { consumes = ReaderUtils.splitContentValues(new String[] { api.consumes() }); } globalSchemes.addAll(parseSchemes(api.protocols())); for (Authorization auth : api.authorizations()) { if (auth.value() != null && !auth.value().isEmpty()) { SecurityRequirement security = new SecurityRequirement(); security.setName(auth.value()); for (AuthorizationScope scope : auth.scopes()) { if (scope.scope() != null && !scope.scope().isEmpty()) { security.addScope(scope.scope()); } } securities.add(security); } } } if (readable) { if (isSubresource) { if (parentTags != null) { tags.putAll(parentTags); } } // merge consumes, produces if (consumes.length == 0 && cls.getAnnotation(Consumes.class) != null) { consumes = ReaderUtils.splitContentValues(cls.getAnnotation(Consumes.class).value()); } if (produces.length == 0 && cls.getAnnotation(Produces.class) != null) { produces = ReaderUtils.splitContentValues(cls.getAnnotation(Produces.class).value()); } // look for method-level annotated properties // handle sub-resources by looking at return type final List<Parameter> globalParameters = new ArrayList<Parameter>(); // look for constructor-level annotated properties globalParameters.addAll(ReaderUtils.collectConstructorParameters(cls, swagger)); // look for field-level annotated properties globalParameters.addAll(ReaderUtils.collectFieldParameters(cls, swagger)); // build class/interface level @ApiResponse list ApiResponses classResponseAnnotation = ReflectionUtils.getAnnotation(cls, ApiResponses.class); List<ApiResponse> classApiResponses = new ArrayList<ApiResponse>(); if (classResponseAnnotation != null) { classApiResponses.addAll(Arrays.asList(classResponseAnnotation.value())); } // parse the method final javax.ws.rs.Path apiPath = ReflectionUtils.getAnnotation(cls, javax.ws.rs.Path.class); JavaType classType = TypeFactory.defaultInstance().constructType(cls); BeanDescription bd = new ObjectMapper().getSerializationConfig().introspect(classType); Method methods[] = cls.getMethods(); for (Method method : methods) { AnnotatedMethod annotatedMethod = bd.findMethod(method.getName(), method.getParameterTypes()); if (ReflectionUtils.isOverriddenMethod(method, cls)) { continue; } javax.ws.rs.Path methodPath = ReflectionUtils.getAnnotation(method, javax.ws.rs.Path.class); String operationPath = getPath(apiPath, methodPath, parentPath); Map<String, String> regexMap = new LinkedHashMap<String, String>(); operationPath = PathUtils.parsePath(operationPath, regexMap); if (operationPath != null) { if (isIgnored(operationPath)) { continue; } final ApiOperation apiOperation = ReflectionUtils.getAnnotation(method, ApiOperation.class); String httpMethod = extractOperationMethod(apiOperation, method, SwaggerExtensions.chain()); Operation operation = null; if (apiOperation != null || config.isScanAllResources() || httpMethod != null || methodPath != null) { operation = parseMethod(cls, method, annotatedMethod, globalParameters, classApiResponses); } if (operation == null) { continue; } if (parentParameters != null) { for (Parameter param : parentParameters) { operation.parameter(param); } } for (Parameter param : operation.getParameters()) { if (regexMap.get(param.getName()) != null) { String pattern = regexMap.get(param.getName()); param.setPattern(pattern); } } if (apiOperation != null) { for (Scheme scheme : parseSchemes(apiOperation.protocols())) { operation.scheme(scheme); } } if (operation.getSchemes() == null || operation.getSchemes().isEmpty()) { for (Scheme scheme : globalSchemes) { operation.scheme(scheme); } } String[] apiConsumes = consumes; if (parentConsumes != null) { Set<String> both = new LinkedHashSet<String>(Arrays.asList(apiConsumes)); both.addAll(new LinkedHashSet<String>(Arrays.asList(parentConsumes))); if (operation.getConsumes() != null) { both.addAll(new LinkedHashSet<String>(operation.getConsumes())); } apiConsumes = both.toArray(new String[both.size()]); } String[] apiProduces = produces; if (parentProduces != null) { Set<String> both = new LinkedHashSet<String>(Arrays.asList(apiProduces)); both.addAll(new LinkedHashSet<String>(Arrays.asList(parentProduces))); if (operation.getProduces() != null) { both.addAll(new LinkedHashSet<String>(operation.getProduces())); } apiProduces = both.toArray(new String[both.size()]); } final Class<?> subResource = getSubResourceWithJaxRsSubresourceLocatorSpecs(method); if (subResource != null && !scannedResources.contains(subResource)) { scannedResources.add(subResource); read(subResource, operationPath, httpMethod, true, apiConsumes, apiProduces, tags, operation.getParameters(), scannedResources); // remove the sub resource so that it can visit it later in another path // but we have a room for optimization in the future to reuse the scanned result // by caching the scanned resources in the reader instance to avoid actual scanning // the the resources again scannedResources.remove(subResource); } // can't continue without a valid http method httpMethod = (httpMethod == null) ? parentMethod : httpMethod; if (httpMethod != null) { if (apiOperation != null) { for (String tag : apiOperation.tags()) { if (!"".equals(tag)) { operation.tag(tag); swagger.tag(new Tag().name(tag)); } } operation.getVendorExtensions().putAll(BaseReaderUtils.parseExtensions(apiOperation.extensions())); } if (operation.getConsumes() == null) { for (String mediaType : apiConsumes) { operation.consumes(mediaType); } } if (operation.getProduces() == null) { for (String mediaType : apiProduces) { operation.produces(mediaType); } } if (operation.getTags() == null) { for (String tagString : tags.keySet()) { operation.tag(tagString); } } // Only add global @Api securities if operation doesn't already have more specific securities if (operation.getSecurity() == null) { for (SecurityRequirement security : securities) { operation.security(security); } } Path path = swagger.getPath(operationPath); if (path == null) { path = new Path(); swagger.path(operationPath, path); } path.set(httpMethod, operation); readImplicitParameters(method, operation); readExternalDocs(method, operation); } } } } return swagger; }

Example 50

/** * Gets the AWS credential to download to the specified business object data and storage. GET) @Secured(SecurityFunctions.FN_BUSINESS_OBJECT_DATA_DOWNLOAD_CREDENTIAL_GET) @ApiOperation(value = "Gets Business Object Data Download Credentials. This is not meant for public consumption.", hidden = true) public BusinessObjectDataDownloadCredential getBusinessObjectDataDownloadCredential(@PathVariable("namespace") String namespace, @PathVariable("businessObjectDefinitionName") String businessObjectDefinitionName, @PathVariable("businessObjectFormatUsage") String businessObjectFormatUsage, @PathVariable("businessObjectFormatFileType") String businessObjectFormatFileType, @PathVariable("businessObjectFormatVersion") Integer businessObjectFormatVersion, @PathVariable("partitionValue") String partitionValue, @PathVariable("businessObjectDataVersion") Integer businessObjectDataVersion, @RequestParam(value = "storageName", required = true) String storageName, @RequestParam(value = "subPartitionValues", required = false) DelimitedFieldValues subPartitionValues) { StorageUnitDownloadCredential storageUnitDownloadCredential = storageUnitService.getStorageUnitDownloadCredential(new BusinessObjectDataKey(namespace, businessObjectDefinitionName, businessObjectFormatUsage, businessObjectFormatFileType, businessObjectFormatVersion, partitionValue, getList(subPartitionValues), businessObjectDataVersion), storageName); return new BusinessObjectDataDownloadCredential(storageUnitDownloadCredential.getAwsCredential()); }

Example 51

@GET @Path("/schemaproviders") @ApiOperation(value = "Get list of registered Schema Providers", notes = "The Schema Registry supports different types of schemas, such as Avro, JSON etc. " + "" + "A Schema Provider is needed for each type of schema supported by the Schema Registry. " + "Schema Provider supports defining schema, serializing and deserializing data using the schema, " + " and checking compatibility between different versions of the schema.", response = SchemaProviderInfo.class, responseContainer = "List", tags = OPERATION_GROUP_OTHER) @Timed public Response getRegisteredSchemaProviderInfos(@Context UriInfo uriInfo) { try { Collection<SchemaProviderInfo> schemaProviderInfos = schemaRegistry.getRegisteredSchemaProviderInfos(); return WSUtils.respondEntities(schemaProviderInfos, Response.Status.OK); } catch (Exception ex) { LOG.error("Encountered error while listing schemas", ex); return WSUtils.respond(Response.Status.INTERNAL_SERVER_ERROR, CatalogResponse.ResponseMessage.EXCEPTION, ex.getMessage()); } }

Example 52

@ApiOperation(value = "List the projects accessible by the authenticated user") @RequestMapping(value = ("/" + PROJECTS), method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE) public ResponseEntity<List<RProject>> projectList() throws Exception { // Get current user - this will throw an exception if the current user does not exit User user = getCurrentUser(); // Get projects with permission List<Project> accessibleProjects = projectService.listAccessibleProjects(user); // Collect all the projects List<RProject> projectList = new ArrayList<>(); for (Project project : accessibleProjects) { projectList.add(new RProject(project)); } return ResponseEntity.ok(projectList); }

Example 53

////////////////////////////////////////////////////////////////////////// //////////// GRAPHS ////////////////////////////////////////////////////////////////////////// /** * Imports a graph. * @param nameStr The name for the graph. * @param creationTypeStr The creation type the graph was created by. * @param graphInputFormatStr The name of the graph input format. * @param doMakeUndirectedStr Optional query parameter. Defines whether directed edges shall be turned into undirected edges (TRUE) or not. * @param startDateStr Optional query parameter. For big graphs start date is the date from which the file will start parse. * @param endDateStr Optional query parameter. For big graphs end date is the date till which the file will parse. * @param indexPathStr Optional query parameter. Set index directory. * @param filePathStr Optional query parameter. For testing purpose, file location of local file can be given. * @param contentStr The graph input. * @return A graph id xml. * Or an error xml. */ @POST @Path("graphs") @Produces(MediaType.TEXT_XML) @Consumes(MediaType.TEXT_PLAIN) @ApiResponses(value = { @ApiResponse(code = 200, message = "Success"), @ApiResponse(code = 401, message = "Unauthorized") }) @ApiOperation(value = "User validation", notes = "Imports a graph.") public String createGraph(@DefaultValue("unnamed") @QueryParam("name") String nameStr, @DefaultValue("UNDEFINED") @QueryParam("creationType") String creationTypeStr, @DefaultValue("GRAPH_ML") @QueryParam("inputFormat") String graphInputFormatStr, @DefaultValue("FALSE") @QueryParam("doMakeUndirected") String doMakeUndirectedStr, @DefaultValue("2004-01-01") @QueryParam("startDate") String startDateStr, @DefaultValue("2004-01-20") @QueryParam("endDate") String endDateStr, @DefaultValue("indexes") @QueryParam("indexPath") String indexPathStr, @DefaultValue("ocd/test/input/stackexAcademia.xml") @QueryParam("filePath") String filePathStr, @ContentParam String contentStr) { try { String username = ((UserAgent) getActiveAgent()).getLoginName(); GraphInputFormat format; CustomGraph graph; try { format = GraphInputFormat.valueOf(graphInputFormatStr); } catch (Exception e) { requestHandler.log(Level.WARNING, "user: " + username, e); return requestHandler.writeError(Error.PARAMETER_INVALID, "Specified input format does not exist."); } GraphCreationType benchmarkType; try { benchmarkType = GraphCreationType.valueOf(creationTypeStr); } catch (Exception e) { requestHandler.log(Level.WARNING, "user: " + username, e); return requestHandler.writeError(Error.PARAMETER_INVALID, "Specified input format does not exist."); } try { int subDirName = 0; File indexPathDir = new File(indexPathStr); if (indexPathDir.exists()) { for (String subDir : indexPathDir.list()) { if (Integer.parseInt(subDir) == subDirName) { subDirName++; } } } indexPathStr = indexPathStr + File.separator + String.valueOf(subDirName); } catch (Exception e) { requestHandler.log(Level.WARNING, "user: " + username, e); return requestHandler.writeError(Error.INTERNAL, "Index path exception."); } try { Map<String, String> param = new HashMap<String, String>(); if (format == GraphInputFormat.NODE_CONTENT_EDGE_LIST || format == GraphInputFormat.XML) { param.put("startDate", startDateStr); param.put("endDate", endDateStr); if (format == GraphInputFormat.XML) { param.put("indexPath", indexPathStr); param.put("filePath", filePathStr); } else { param.put("path", indexPathStr); } } graph = requestHandler.parseGraph(contentStr, format, param); } catch (Exception e) { requestHandler.log(Level.WARNING, "user: " + username, e); return requestHandler.writeError(Error.PARAMETER_INVALID, "Input graph does not correspond to the specified format."); } boolean doMakeUndirected; try { doMakeUndirected = requestHandler.parseBoolean(doMakeUndirectedStr); } catch (Exception e) { requestHandler.log(Level.WARNING, "user: " + username, e); return requestHandler.writeError(Error.PARAMETER_INVALID, "Do make undirected ist not a boolean value."); } graph.setUserName(username); graph.setName(URLDecoder.decode(nameStr, "UTF-8")); GraphCreationLog log = new GraphCreationLog(benchmarkType, new HashMap<String, String>()); log.setStatus(ExecutionStatus.COMPLETED); graph.setCreationMethod(log); GraphProcessor processor = new GraphProcessor(); processor.determineGraphTypes(graph); if (doMakeUndirected) { Set<GraphType> graphTypes = graph.getTypes(); if (graphTypes.remove(GraphType.DIRECTED)) { processor.makeCompatible(graph, graphTypes); } } EntityManager em = requestHandler.getEntityManager(); EntityTransaction tx = em.getTransaction(); try { tx.begin(); em.persist(graph); tx.commit(); } catch (RuntimeException e) { if (tx != null && tx.isActive()) { tx.rollback(); } throw e; } em.close(); return requestHandler.writeId(graph); } catch (Exception e) { requestHandler.log(Level.SEVERE, "", e); return requestHandler.writeError(Error.INTERNAL, "Internal system error."); } }

Example 54

@ApiOperation(value = "Test API") @RequestMapping(value = "/api/testAPI", method = RequestMethod.GET, produces = "application/json") public String testAPI() { String responseJson = "{\n" + " \"columnNames\": [\"Col 1\", \"Col 2\"],\n" + " \"data\": [[\"aaa\", \"bbb\"], [\"ccc\", \"ddd\"], [\"eee\", \"fff\"]]\n" + "}"; logger.error(">>> responseJson: " + responseJson); return responseJson; }

Example 55

@POST @Path("/virtualizer/") @Consumes({ "application/json" }) @Produces({ "application/json" }) @io.swagger.annotations.ApiOperation(value = "Create virtualizer by ID", notes = "Create operation of resource: virtualizer", response = void.class, tags = {}) @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 200, message = "Successful operation", response = void.class), @io.swagger.annotations.ApiResponse(code = 400, message = "Internal Error", response = void.class) }) public Response createVirtualizerById(@ApiParam(value = "virtualizerbody object", required = true) VirtualizerSchema virtualizer, @Context SecurityContext securityContext) throws NotFoundException { return delegate.createVirtualizerById(virtualizer, securityContext); }

Example 56

@ApiOperation(value = "/testFeign", notes = "测试Feign", httpMethod = "GET") @ApiParam(name = "content", value = "�数:content") @RequestMapping("/testFeign") @ResponseBody public void testFeign(String content) { String ribbonStr = feignServer.testRealRibbon(content); System.out.println(ribbonStr); }

Example 57

@GET @Produces(MediaType.APPLICATION_JSON) @ApiOperation(value = "GET MyObject", response = MyObject.class) public void getAsync(@Suspended final AsyncResponse asyncResponse, @Context Vertx vertx) { vertx.runOnContext( aVoid -> { MyObject o = new MyObject(); o.setName("Andy"); asyncResponse.resume(o); }); }

Example 58

@Path("howdy") @GET @ApiOperation(value = "Say howdy", response = String.class) public String get() { return "howdy"; }

Example 59

@POST @Path("/artifact/deploy") @Consumes({ "text/plain" }) @Produces({ "application/json" }) @io.swagger.annotations.ApiOperation(value = "", notes = "Deploys the execution plan. Request **executionPlan** " + "explains the Siddhi Query ", response = Success.class, tags = {}) @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 200, message = "Successful response", response = Success.class), @io.swagger.annotations.ApiResponse(code = 200, message = "Unexpected error", response = Success.class) }) public Response siddhiArtifactDeployPost(@ApiParam(value = "Siddhi Execution Plan", required = true) String body) throws NotFoundException { return delegate.siddhiArtifactDeployPost(body); }

Example 60

@GET @Path("/config") @ApiOperation(OBTAIN_GENERAL_CONFIG_OD) public String getGeneralConfig() { return publicManager.getGeneralConfig(); }

Example 61

@ApiOperation(value = "get userinfo by id", notes = "") @ApiImplicitParam(name = "id", value = "user id ", required = true, paramType = "query") @RequestMapping(method = RequestMethod.GET) public User doGet(@RequestParam Long id) { User user = userDao.selectUserById(id); if (user == null) { throw new C404Exception("user not found"); } return userDao.selectUserById(id); }

Example 62

@Produces({ MediaType.APPLICATION_JSON }) @GET @ApiOperation(value = "Get books", notes = "Get books", response = Book.class, responseContainer = "List") public Response getBooks(@ApiParam(value = "Page to fetch", required = true) @QueryParam("page") @DefaultValue("1") int page) { return Response.ok(Arrays.asList(new Book("Book 1", 1), new Book("Book 2", 2))).build(); }

Example 63

@GET @ApiOperation(value = "Validates a spec based on a URL") @ApiResponses(value = {}) @Produces({ "image/png" }) public Response validateByUrl(@Context HttpServletRequest request, @Context HttpServletResponse response, @ApiParam(value = "url of spec to validate") @QueryParam("url") String url) throws WebApplicationException { try { service.validateByUrl(request, response, url); response.addHeader("Cache-Control", "no-cache"); } catch (Exception e) { e.printStackTrace(); } return Response.ok().build(); }

Example 64

/** * The GET order by id operation */ @GET @Path("/{id}") @ApiOperation(value = "Get order", response = Order.class) @ApiResponses({ @ApiResponse(code = 200, response = String.class, message = "The found order"), @ApiResponse(code = 404, response = String.class, message = "Cannot find order with the id") }) public Response getOrder(@ApiParam(value = "The id of the order", required = true) @PathParam("id") int orderId) { Order order = orderService.getOrder(orderId); if (order != null) { return Response.ok(order).build(); } else { return Response.status(Response.Status.NOT_FOUND).build(); } }

Example 65

@GET @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @ApiOperation(value = "Get all users", response = User.class, responseContainer = "List") public List<User> getUsers() { return users; }

Example 66

@RequestMapping(value = "", method = RequestMethod.POST, consumes = { MediaType.APPLICATION_JSON_VALUE }) @ResponseStatus(value = HttpStatus.OK) @ApiOperation(value = "create cluster", consumes = MediaType.APPLICATION_JSON_VALUE) @ApiResponses(value = { @ApiResponse(code = 200, message = "") }) public void createCluster(@ApiParam(value = "cluster", required = true) @RequestBody Cluster cluster) { LOG.trace("Method: createCluster called."); clusterManager.createCluster(cluster); }

Example 67

@GET @Path("/findConnector") @Produces("application/json") @ApiOperation(value = "Find all the connectors from the catalog") public List<ConnectorDto> findConnector(@ApiParam(value = "Whether to include latest version only", defaultValue = "true") @QueryParam("latestVersionOnly") Boolean latestVersionOnly) { boolean latest = latestVersionOnly != null ? latestVersionOnly : true; return catalog.findConnector(latest); }
Sours: https://www.javatips.net/api/io.swagger.annotations.apioperation

Similar news:

Best Java code snippets using io.swagger.annotations.ApiOperation(Showing top 20 results out of 4,266)

Refine searchRefine arrow

  • Common ways to obtain ApiOperation

    private void myMethod () {

    }

    @[email protected]("tables/{tableName}/segments/crc") @Produces(MediaType.APPLICATION_JSON) @ApiOperation(value = "Gets crc of all segments of a table", notes = "Gets crc of all segments") public String getCrcForAllSegments( @ApiParam(value = "Name of the table", required = true) @PathParam("tableName") String tableName) { return getAllCrcMetadataForTable(tableName); }
    @PUT @Produces(MediaType.APPLICATION_JSON) @Path("/schemas/{schemaName}") @ApiOperation(value = "Update a schema", notes = "Updates a schema") @ApiResponses(value = {@ApiResponse(code = 200, message = "Successfully updated schema"), @ApiResponse(code = 404, message = "Schema not found"), @ApiResponse(code = 400, message = "Missing or invalid request body"), @ApiResponse(code = 500, message = "Internal error")}) public SuccessResponse updateSchema( @ApiParam(value = "Name of the schema", required = true) @PathParam("schemaName") String schemaName, FormDataMultiPart multiPart) { return addOrUpdateSchema(schemaName, multiPart); }
    @GET @Path("/") @ApiOperation(value = "Check controller health") @ApiResponses(value = {@ApiResponse(code = 200, message = "Good")}) @Produces(MediaType.TEXT_PLAIN) public String checkHealth() { if (StringUtils.isNotBlank(controllerConf.generateVipUrl())) { return"GOOD"; } return""; } }
    @Override public LoggerDefine parse(MethodInterceptorHolder holder) { Api api = holder.findAnnotation(Api.class); ApiOperation operation = holder.findAnnotation(ApiOperation.class); String action = ""; if (api != null) { action = action.concat(api.value()); } if (null != operation) { action = StringUtils.isEmpty(action) ? operation.value() : action + "-" + operation.value(); } returnnew LoggerDefine(action, ""); } }
    @GET @Produces(MediaType.APPLICATION_JSON) @Path("/table/{tableName}/size") @ApiOperation(value = "Show table storage size", notes = "Lists size of all the segments of the table") @ApiResponses(value = {@ApiResponse(code = 200, message = "Success"), @ApiResponse(code = 500, message = "Internal server error"), @ApiResponse(code = 404, message = "Table not found")}) @Deprecated public String getTableSizeOld( @ApiParam(value = "Table Name with type", required = true) @PathParam("tableName") String tableName, @ApiParam(value = "Provide detailed information") @DefaultValue("true") @QueryParam("detailed") boolean detailed) throws WebApplicationException { returnthis.getTableSize(tableName, detailed); } }
    @GET @Path("memory/offheap") @ApiOperation(value = "View current off-heap allocations", notes = "Lists all off-heap allocations and their associated sizes") @ApiResponses(value = {@ApiResponse(code = 200, message = "Success")}) @Produces(MediaType.APPLICATION_JSON) public List<String> getOffHeapSizes() { return PinotDataBuffer.getBufferInfo(); } }
    @[email protected]("/{streamRuleId}") @Timed @ApiOperation(value = "Get a single stream rules") @Produces(MediaType.APPLICATION_JSON) public StreamRule get(@ApiParam(name = "streamid", value = "The id of the stream whose stream rule we want.", required = true) @PathParam("streamid") String streamid, @ApiParam(name = "streamRuleId", value = "The stream rule id we are getting", required = true) @PathParam("streamRuleId") String streamRuleId) throws NotFoundException { checkPermission(RestPermissions.STREAMS_READ, streamid); return streamRuleService.load(streamRuleId); }
    @DELETE @Produces(MediaType.APPLICATION_JSON) @Path("/schemas/{schemaName}") @ApiOperation(value = "Delete a schema", notes = "Deletes a schema by name") @ApiResponses(value = {@ApiResponse(code = 200, message = "Successfully deleted schema"), @ApiResponse(code = 404, message = "Schema not found"), @ApiResponse(code = 409, message = "Schema is in use"), @ApiResponse(code = 500, message = "Error deleting schema")}) public SuccessResponse deleteSchema( @ApiParam(value = "Schema name", required = true) @PathParam("schemaName") String schemaName) { deleteSchemaInternal(schemaName); returnnew SuccessResponse("Schema " + schemaName + " deleted"); }
    @POST @Produces(MediaType.APPLICATION_JSON) @Path("/schemas") @ApiOperation(value = "Add a new schema", notes = "Adds a new schema") @ApiResponses(value = {@ApiResponse(code = 200, message = "Successfully deleted schema"), @ApiResponse(code = 404, message = "Schema not found"), @ApiResponse(code = 400, message = "Missing or invalid request body"), @ApiResponse(code = 500, message = "Internal error")}) public SuccessResponse addSchema(FormDataMultiPart multiPart) { return addOrUpdateSchema(null, multiPart); }
    @[email protected]("/available") @Timed @ApiOperation(value = "Get a list of all alarm callback types") @Produces(MediaType.APPLICATION_JSON) @Deprecated public AvailableAlarmCallbacksResponse available(@ApiParam(name = "streamid", value = "The id of the stream whose alarm callbacks we want.", required = true) @PathParam("streamid") String streamid) { checkPermission(RestPermissions.STREAMS_READ, streamid); return alarmCallbacksResource.available(); }
    @[email protected]("/tenants/{tenantName}/tables") @Produces(MediaType.APPLICATION_JSON) @ApiOperation(value = "List tables on a a server tenant") @ApiResponses(value = {@ApiResponse(code = 200, message = "Success"), @ApiResponse(code = 500, message = "Error reading list")}) public String getTablesOnTenant( @ApiParam(value = "Tenant name", required = true) @PathParam("tenantName") String tenantName) { return getTablesServedFromTenant(tenantName); }
    @[email protected]("/instances") @Produces(MediaType.APPLICATION_JSON) @ApiOperation(value = "List all instances") @ApiResponses(value = {@ApiResponse(code = 200, message = "Success"), @ApiResponse(code = 500, message = "Internal error")}) public Instances getAllInstances() { returnnew Instances(pinotHelixResourceManager.getAllInstances()); }
    @Deprecated @[email protected]("tables/{tableName}/segments/reload") @Produces(MediaType.APPLICATION_JSON) @ApiOperation(value = "Reloads all segments of a table", notes = "Reloads all segments") public SuccessResponse reloadAllSegmentsDeprecated( @ApiParam(value = "Name of the table", required = true) @PathParam("tableName") String tableName, @ApiParam(value = "realtime|offline") @QueryParam("type") String tableTypeStr) { CommonConstants.Helix.TableType tableType = Constants.validateTableType(tableTypeStr); return reloadAllSegmentsForTable(tableName, tableType); }
    @[email protected](MediaType.APPLICATION_JSON) @Path("/routingTable/{tableName}") @ApiOperation(value = "Debugging routing table") @ApiResponses(value = {@ApiResponse(code = 200, message = "Routing table information of a table"), @ApiResponse(code = 500, message = "Internal server error")}) public String debugRoutingTable(@ApiParam(value = "Name of the table") @PathParam("tableName") String tableName) { try { return _routingTable.dumpSnapshot(tableName); } catch (Exception e) { LOGGER.error("Caught exception while processing GET request", e); _brokerMetrics.addMeteredGlobalValue(BrokerMeter.UNCAUGHT_GET_EXCEPTIONS, 1); thrownew WebApplicationException(e, Response.Status.INTERNAL_SERVER_ERROR); } }
    @[email protected]("/tables") @Produces(MediaType.APPLICATION_JSON) @ApiOperation(value = "List tables", notes = "List all the tables on this server") @ApiResponses(value = {@ApiResponse(code = 200, message = "Success", response = TablesList.class), @ApiResponse(code = 500, message = "Server initialization error", response = ErrorInfo.class)}) public String listTables() { InstanceDataManager instanceDataManager = checkGetInstanceDataManager(); List<String> tables = new ArrayList<>(instanceDataManager.getAllTables()); return ResourceUtils.convertToJsonString(new TablesList(tables)); }
    @[email protected](MediaType.APPLICATION_JSON) @Path("/tables/{tableName}/externalview") @ApiOperation(value = "Get table external view", notes = "Get table external view") public TableView getExternalView( @ApiParam(value = "Name of the table", required = true) @PathParam("tableName") String tableName, @ApiParam(value = "realtime|offline", required = false) @QueryParam("tableType") String tableTypeStr ) { CommonConstants.Helix.TableType tableType = validateTableType(tableTypeStr); return getTableState(tableName, EXTERNALVIEW, tableType); }
    @[email protected] @ApiOperation(value = "Get a single dashboards and all configurations of its widgets.") @Path("/{dashboardId}") @ApiResponses(value = { @ApiResponse(code = 404, message = "Dashboard not found."), }) @Produces(MediaType.APPLICATION_JSON) public Map<String, Object> get(@ApiParam(name = "dashboardId", required = true) @PathParam("dashboardId") String dashboardId) throws NotFoundException { checkPermission(RestPermissions.DASHBOARDS_READ, dashboardId); return dashboardService.load(dashboardId).asMap(); }
    @[email protected](MediaType.APPLICATION_JSON) @Path("/tables/{tableName}/idealstate") @ApiOperation(value = "Get table ideal state", notes = "Get table ideal state") public TableView getIdealState( @ApiParam(value = "Name of the table", required = true) @PathParam("tableName") String tableName, @ApiParam(value = "realtime|offline", required = false) @QueryParam("tableType") String tableTypeStr) { CommonConstants.Helix.TableType tableType = validateTableType(tableTypeStr); return getTableState(tableName, IDEALSTATE, tableType); }
    @[email protected] @Path("/nodes/{nodeId}") @ApiOperation(value = "Information about a node.", notes = "This is returning information of a node in context to its state in the cluster. " + "Use the system API of the node itself to get system information.") @ApiResponses(value = { @ApiResponse(code = 404, message = "Node not found.") }) public NodeSummary node(@ApiParam(name = "nodeId", required = true) @PathParam("nodeId") @NotEmpty String nodeId) throws NodeNotFoundException { return nodeSummary(nodeService.byNodeId(nodeId)); }
    @[email protected]("/{id}/configurations") @RequiresPermissions(SidecarRestPermissions.CONFIGURATIONS_READ) @Produces(MediaType.APPLICATION_JSON) @ApiOperation(value = "Show configurations using this variable") public List<Configuration> getConfigurationVariablesConfigurations(@ApiParam(name = "id", required = true) @PathParam("id") String id) { final ConfigurationVariable configurationVariable = findVariableOrFail(id); final List<Configuration> configurations = this.configurationService.findByConfigurationVariable(configurationVariable); return configurations; }
    Sours: https://www.tabnine.com/code/java/classes/io.swagger.annotations.ApiOperation


    82 83 84 85 86