Java Examples for io.swagger.annotations.ApiResponse
The following java examples will help you to understand the usage of io.swagger.annotations.ApiResponse. These source code samples are taken from different open source projects.
Example 1
Project: anythingworks-master File: RestRequestInfoService.java View source code |
@GET @Path("/requestinfo") @ApiOperation(value = "Ping the server", notes = "Shows information about the request as seen by the server, including the request method, user agent, and so on. This way a client can be confident about what the server actually gets through all the possible interceptors and proxies.", response = RequestInfo.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "Returns the RequestInfo object.") }) public Response info(@QueryParam(value = "apiKey") final String apiKey, @QueryParam(value = "envelope") final boolean envelope, @Context final HttpHeaders httpHeaders, @Context final Request request) { RequestInfo result = execute(new BaseCommand<Void, RequestInfo>() { @Override public RequestInfo call(@NotNull Optional<Void> arg, @NotNull ExecutionContext ec) throws Exception { RequestInfo.Builder builder = new RequestInfo.Builder(); builder.method(request.getMethod()); builder.uri(((ContainerRequest) request).getRequestUri().toString()); List<String> requestHeader = httpHeaders.getRequestHeader("user-agent"); if (requestHeader != null && !requestHeader.isEmpty()) { builder.userAgent(requestHeader.get(0)); } //TODO add more, that's not all yet. return builder.build(); } }).orNull(); Object entity = possiblyWrapInEnvelope(envelope, result); return Response.ok().entity(entity).build(); }
Example 2
Project: kylo-master File: FeedsController.java View source code |
@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 3
Project: che-master File: ProjectService.java View source code |
@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 4
Project: Gaffer-master File: StatusService.java View source code |
@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 5
Project: coner-master File: EventRegistrationsResource.java View source code |
@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 6
Project: hello-world-master File: TcAuthenticationController.java View source code |
/** * 0 ==> 登陆成功; * 1 ==> 验证码已过期; * 2 ==> 验证码输入错误; * 3 ==> 账号不存在; * 4 ==> 账号被锁定; * 5 ==> 账号密码错误; */ @ApiOperation(value = "登陆", notes = "登陆") @ApiResponse(code = 200, message = "成功") @RequestMapping(value = "/login", method = RequestMethod.POST) public ResponseEntity<TcR<Integer>> login(@RequestParam(value = "username") String username, @RequestParam(value = "password") String rsaEncryptedPassword, @RequestParam(value = "rememberMe", defaultValue = "false") Boolean rememberMe, @RequestParam(value = "verificationCode") String verificationCode, HttpServletResponse response) { // verify verification code String verificationCodeInCache = tcAuthenticationService.getVerificationCodeInCache(); if (Objects.isNull(verificationCodeInCache)) { return ResponseEntity.ok(TcR.code(1, "验证码已过期!")); } boolean verificationCodeMatch = tcAuthenticationService.isVerificationCodeMatch(verificationCodeInCache, verificationCode); if (!verificationCodeMatch) { return ResponseEntity.ok(TcR.code(2, "验证码输入错误!")); } // login String password = tcAuthenticationService.decryptRSAEncryptedPassword(rsaEncryptedPassword); UsernamePasswordToken token = new UsernamePasswordToken(username, password); token.setRememberMe(rememberMe); try { SecurityUtils.getSubject().login(token); } catch (UnknownAccountException e) { return ResponseEntity.ok(TcR.code(3, "账号不存在!")); } catch (LockedAccountException e) { return ResponseEntity.ok(TcR.code(4, "账号被锁定!")); } catch (IncorrectCredentialsException e) { return ResponseEntity.ok(TcR.code(5, "账号密码错误!")); } // set xsrf cookie TcXsrfTokenFilter.addXsrfCookie(response); // set session tcSessionService.initSessionAfterLogin(); // find menus // String accountId = tcSessionService.getAccountId(); // TcP<List<ToMenu>> menus = tcAuthenticationApi.findMenus(accountId); // TODO: 2016/11/26 // mq TODO log.info("session id -> [{}] login success", SecurityUtils.getSubject().getSession().getId()); // successful return ResponseEntity.ok(TcR.code(0, "登陆成功!")); }
Example 7
Project: strongbox-master File: ConfigurationManagementController.java View source code |
@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 8
Project: roda-master File: RepresentationsResource.java View source code |
@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 9
Project: pinot-master File: TablesResource.java View source code |
@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 10
Project: candlepin-master File: ConsumerResource.java View source code |
@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 11
Project: cartographer-master File: RepositoryResource.java View source code |
@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 12
Project: SmartHome-master File: SitemapResource.java View source code |
@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 13
Project: killbill-master File: AccountResource.java View source code |
@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 14
Project: hawkular-inventory-master File: RestResources.java View source code |
@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 15
Project: graylog2-server-master File: StreamResource.java View source code |
@PUT @Timed @Path("/{streamId}") @ApiOperation(value = "Update a stream") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @ApiResponses(value = { @ApiResponse(code = 404, message = "Stream not found."), @ApiResponse(code = 400, message = "Invalid ObjectId.") }) @AuditEvent(type = AuditEventTypes.STREAM_UPDATE) public StreamResponse update(@ApiParam(name = "streamId", required = true) @PathParam("streamId") String streamId, @ApiParam(name = "JSON body", required = true) @Valid @NotNull UpdateStreamRequest cr) throws NotFoundException, ValidationException { checkPermission(RestPermissions.STREAMS_EDIT, streamId); checkNotDefaultStream(streamId, "The default stream cannot be edited."); final Stream stream = streamService.load(streamId); if (!Strings.isNullOrEmpty(cr.title())) { stream.setTitle(cr.title()); } if (!Strings.isNullOrEmpty(cr.description())) { stream.setDescription(cr.description()); } if (cr.matchingType() != null) { try { stream.setMatchingType(Stream.MatchingType.valueOf(cr.matchingType())); } catch (IllegalArgumentException e) { throw new BadRequestException("Invalid matching type '" + cr.matchingType() + "' specified. Should be one of: " + Arrays.toString(Stream.MatchingType.values())); } } final Boolean removeMatchesFromDefaultStream = cr.removeMatchesFromDefaultStream(); if (removeMatchesFromDefaultStream != null) { stream.setRemoveMatchesFromDefaultStream(removeMatchesFromDefaultStream); } // id if it's null/empty in the update request. if (!Strings.isNullOrEmpty(cr.indexSetId())) { stream.setIndexSetId(cr.indexSetId()); } final Optional<IndexSet> indexSet = indexSetRegistry.get(stream.getIndexSetId()); if (!indexSet.isPresent()) { throw new BadRequestException("Index set with ID <" + stream.getIndexSetId() + "> does not exist!"); } else if (!indexSet.get().getConfig().isWritable()) { throw new BadRequestException("Assigned index set must be writable!"); } streamService.save(stream); clusterEventBus.post(StreamsChangedEvent.create(stream.getId())); return streamToResponse(stream); }
Example 16
Project: teiid-embedded-master File: CustomersResource.java View source code |
@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 17
Project: arsnova-backend-master File: SessionController.java View source code |
@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 18
Project: catwatch-master File: ContributorsApi.java View source code |
@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 19
Project: Pulsar-master File: PersistentTopics.java View source code |
@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 20
Project: swagger-maven-plugin-master File: AbstractReader.java View source code |
protected void updateApiResponse(Operation operation, ApiResponses responseAnnotation) { for (ApiResponse apiResponse : responseAnnotation.value()) { Map<String, Property> responseHeaders = parseResponseHeaders(apiResponse.responseHeaders()); Class<?> responseClass = apiResponse.response(); Response response = new Response().description(apiResponse.message()).headers(responseHeaders); if (responseClass.equals(Void.class)) { if (operation.getResponses() != null) { Response apiOperationResponse = operation.getResponses().get(String.valueOf(apiResponse.code())); if (apiOperationResponse != null) { response.setSchema(apiOperationResponse.getSchema()); } } } else { Map<String, Model> models = ModelConverters.getInstance().read(responseClass); for (String key : models.keySet()) { final Property schema = new RefProperty().asDefault(key); if (apiResponse.responseContainer().equals("List")) { response.schema(new ArrayProperty(schema)); } else { response.schema(schema); } swagger.model(key, models.get(key)); } models = ModelConverters.getInstance().readAll(responseClass); for (Map.Entry<String, Model> entry : models.entrySet()) { swagger.model(entry.getKey(), entry.getValue()); } if (response.getSchema() == null) { Map<String, Response> responses = operation.getResponses(); if (responses != null) { Response apiOperationResponse = responses.get(String.valueOf(apiResponse.code())); if (apiOperationResponse != null) { response.setSchema(apiOperationResponse.getSchema()); } } } } if (apiResponse.code() == 0) { operation.defaultResponse(response); } else { operation.response(apiResponse.code(), response); } } }
Example 21
Project: hawkular-alerts-master File: TriggersHandler.java View source code |
@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 22
Project: ff4j-master File: MonitoringResource.java View source code |
/** * Provide core information on store and available sub resources. */ @GET @Path("/{uid}") @Produces(MediaType.APPLICATION_JSON) @ApiOperation(value = "Display <b>Monitoring</b> for a <b><u>single</u></b> feature", notes = "Each feature will display a pieChart and a barChart for hits", response = FeatureMonitoringApiBean.class) @ApiResponses({ @ApiResponse(code = 200, message = "Status of current ff4j monitoring bean", response = FeatureMonitoringApiBean.class), @ApiResponse(code = 404, message = "Feature not found", response = String.class) }) public Response getFeatureMonitoring(@ApiParam(required = true, name = "uid", value = "Unique identifier of feature") @PathParam("uid") String uid, @ApiParam(required = false, name = "start", value = "Start of window <br>(default is today 00:00)") @QueryParam(PARAM_START) Long start, @ApiParam(required = false, name = "end", value = "End of window <br>(default is tomorrow 00:00)") @QueryParam(PARAM_END) Long end) { if (!ff4j.getFeatureStore().exist(uid)) { String errMsg = new FeatureNotFoundException(uid).getMessage(); return Response.status(Response.Status.NOT_FOUND).entity(errMsg).build(); } // Today Calendar c = Calendar.getInstance(); c.set(Calendar.HOUR_OF_DAY, 0); c.set(Calendar.MINUTE, 0); c.set(Calendar.SECOND, 0); if (start == null) { start = c.getTimeInMillis(); } // Tomorrow 00:00 Calendar c2 = Calendar.getInstance(); c2.setTime(new Date(System.currentTimeMillis() + 1000 * 3600 * 24)); c2.set(Calendar.HOUR_OF_DAY, 0); c2.set(Calendar.MINUTE, 0); c2.set(Calendar.SECOND, 0); if (end == null) { end = c2.getTimeInMillis(); } // Build response FeatureMonitoringApiBean fmab = new FeatureMonitoringApiBean(uid); int hitcount = 0; for (PieSectorApiBean sec : fmab.getEventsPie().getSectors()) { hitcount += sec.getValue(); } fmab.setHitCount(hitcount); return Response.ok().entity(fmab).build(); }
Example 23
Project: jagger-master File: TestEnvironmentRestController.java View source code |
@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 24
Project: hawkular-metrics-master File: CounterHandler.java View source code |
@POST @Path("/") @ApiOperation(value = "Create counter metric.", notes = "This operation also causes the rate to be calculated and " + "persisted periodically after raw count data is persisted. 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 = "Counter 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<Long> 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.", required = false) @DefaultValue("false") @QueryParam("overwrite") Boolean overwrite, @Context UriInfo uriInfo) { if (metric.getType() != null && MetricType.UNDEFINED != metric.getType() && MetricType.COUNTER != metric.getType()) { asyncResponse.resume(badRequest(new ApiError("Metric type does not match " + MetricType.COUNTER.getText()))); } metric = new Metric<>(new MetricId<>(getTenant(), COUNTER, metric.getId()), metric.getTags(), metric.getDataRetention()); URI location = uriInfo.getBaseUriBuilder().path("/counters/{id}").build(metric.getMetricId().getName()); metricsService.createMetric(metric, overwrite).subscribe(new MetricCreatedObserver(asyncResponse, location)); }
Example 25
Project: geode-master File: QueryAccessController.java View source code |
/** * 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 26
Project: kaa-master File: GroupController.java View source code |
//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 27
Project: swagger-core-master File: Reader.java View source code |
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 28
Project: teiid-master File: RestASMBasedWebArchiveBuilder.java View source code |
private void buildRestService(String vdbName, String vdbVersion, String modelName, Procedure procedure, String method, String uri, ClassWriter cw, String contentType, String charSet, boolean passthroughAuth) { List<ProcedureParameter> params = new ArrayList<ProcedureParameter>(procedure.getParameters().size()); boolean usingReturn = false; boolean hasLobInput = false; for (ProcedureParameter p : procedure.getParameters()) { if (p.getType() == Type.In || p.getType() == Type.InOut) { params.add(p); } else if (p.getType() == Type.ReturnValue && procedure.getResultSet() == null) { usingReturn = true; } if (!hasLobInput) { String runtimeType = p.getRuntimeType(); hasLobInput = DataTypeManager.isLOB(runtimeType); } } int paramsSize = params.size(); MethodVisitor mv; boolean useMultipart = false; if (method.toUpperCase().equals("POST") && hasLobInput) { useMultipart = true; } AnnotationVisitor av0; { StringBuilder paramSignature = new StringBuilder(); paramSignature.append("("); for (int i = 0; i < paramsSize; i++) { paramSignature.append("Ljava/lang/String;"); } paramSignature.append(")"); if (useMultipart) { mv = cw.visitMethod(ACC_PUBLIC, procedure.getName() + contentType.replace('/', '_'), "(Lorg/jboss/resteasy/plugins/providers/multipart/MultipartFormDataInput;)Ljavax/ws/rs/core/StreamingOutput;", null, new String[] { "javax/ws/rs/WebApplicationException" }); } else { mv = cw.visitMethod(ACC_PUBLIC, procedure.getName() + contentType.replace('/', '_'), paramSignature + "Ljavax/ws/rs/core/StreamingOutput;", null, new String[] { "javax/ws/rs/WebApplicationException" }); } { av0 = mv.visitAnnotation("Ljavax/ws/rs/Produces;", true); { AnnotationVisitor av1 = av0.visitArray("value"); av1.visit(null, contentType); av1.visitEnd(); } av0.visitEnd(); } { av0 = mv.visitAnnotation("Ljavax/ws/rs/" + method.toUpperCase() + ";", true); av0.visitEnd(); } { av0 = mv.visitAnnotation("Ljavax/ws/rs/Path;", true); av0.visit("value", uri); av0.visitEnd(); } { av0 = mv.visitAnnotation("Ljavax/annotation/security/PermitAll;", true); av0.visitEnd(); } { av0 = mv.visitAnnotation("Lio/swagger/annotations/ApiOperation;", true); av0.visit("value", procedure.getName()); av0.visitEnd(); } { av0 = mv.visitAnnotation("Lio/swagger/annotations/ApiResponses;", true); ApiResponse[] array = new ApiResponse[] {}; AnnotationVisitor av1 = av0.visitArray("value"); for (int i = 0; i < array.length; i++) { av1.visit("value", array[i]); } av1.visitEnd(); av0.visitEnd(); } if (useMultipart) { av0 = mv.visitAnnotation("Ljavax/ws/rs/Consumes;", true); { AnnotationVisitor av1 = av0.visitArray("value"); av1.visit(null, "multipart/form-data"); av1.visitEnd(); } av0.visitEnd(); } if (!useMultipart) { // post only accepts Form inputs, not path params HashSet<String> pathParms = getPathParameters(uri); for (int i = 0; i < paramsSize; i++) { String paramType = "Ljavax/ws/rs/FormParam;"; if (method.toUpperCase().equals("GET")) { paramType = "Ljavax/ws/rs/QueryParam;"; } if (pathParms.contains(params.get(i).getName())) { paramType = "Ljavax/ws/rs/PathParam;"; } av0 = mv.visitParameterAnnotation(i, paramType, true); av0.visit("value", params.get(i).getName()); av0.visitEnd(); av0 = mv.visitParameterAnnotation(i, "Lio/swagger/annotations/ApiParam;", true); av0.visit("value", params.get(i).getName()); av0.visitEnd(); } } mv.visitCode(); Label l0 = new Label(); Label l1 = new Label(); Label l2 = new Label(); mv.visitTryCatchBlock(l0, l1, l2, "java/sql/SQLException"); mv.visitLabel(l0); if (!useMultipart) { mv.visitTypeInsn(NEW, "java/util/LinkedHashMap"); mv.visitInsn(DUP); mv.visitMethodInsn(INVOKESPECIAL, "java/util/LinkedHashMap", "<init>", "()V"); mv.visitVarInsn(ASTORE, paramsSize + 1); for (int i = 0; i < paramsSize; i++) { mv.visitVarInsn(ALOAD, paramsSize + 1); mv.visitLdcInsn(params.get(i).getName()); mv.visitVarInsn(ALOAD, i + 1); mv.visitMethodInsn(INVOKEINTERFACE, "java/util/Map", "put", "(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;"); mv.visitInsn(POP); } mv.visitVarInsn(ALOAD, 0); mv.visitLdcInsn(vdbName); mv.visitLdcInsn(vdbVersion); mv.visitLdcInsn(procedure.getSQLString()); mv.visitVarInsn(ALOAD, paramsSize + 1); mv.visitLdcInsn(charSet == null ? "" : charSet); mv.visitInsn(passthroughAuth ? ICONST_1 : ICONST_0); mv.visitInsn(usingReturn ? ICONST_1 : ICONST_0); mv.visitMethodInsn(INVOKEVIRTUAL, "org/teiid/jboss/rest/" + modelName, "execute", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/util/LinkedHashMap;Ljava/lang/String;ZZ)Ljavax/ws/rs/core/StreamingOutput;"); mv.visitLabel(l1); mv.visitInsn(ARETURN); mv.visitLabel(l2); mv.visitFrame(F_SAME1, 0, null, 1, new Object[] { "java/sql/SQLException" }); mv.visitVarInsn(ASTORE, paramsSize + 1); mv.visitTypeInsn(NEW, "javax/ws/rs/WebApplicationException"); mv.visitInsn(DUP); mv.visitVarInsn(ALOAD, paramsSize + 1); mv.visitFieldInsn(GETSTATIC, "javax/ws/rs/core/Response$Status", "INTERNAL_SERVER_ERROR", "Ljavax/ws/rs/core/Response$Status;"); mv.visitMethodInsn(INVOKESPECIAL, "javax/ws/rs/WebApplicationException", "<init>", "(Ljava/lang/Throwable;Ljavax/ws/rs/core/Response$Status;)V"); mv.visitInsn(ATHROW); mv.visitMaxs(7, paramsSize + 2); mv.visitEnd(); } else { mv.visitVarInsn(ALOAD, 0); mv.visitLdcInsn(vdbName); mv.visitLdcInsn(vdbVersion); mv.visitLdcInsn(procedure.getSQLString()); mv.visitVarInsn(ALOAD, 1); mv.visitLdcInsn(charSet == null ? "" : charSet); mv.visitInsn(passthroughAuth ? ICONST_1 : ICONST_0); mv.visitInsn(usingReturn ? ICONST_1 : ICONST_0); mv.visitMethodInsn(INVOKEVIRTUAL, "org/teiid/jboss/rest/" + modelName, "executePost", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Lorg/jboss/resteasy/plugins/providers/multipart/MultipartFormDataInput;Ljava/lang/String;ZZ)Ljavax/ws/rs/core/StreamingOutput;"); mv.visitLabel(l1); mv.visitInsn(ARETURN); mv.visitLabel(l2); mv.visitFrame(Opcodes.F_SAME1, 0, null, 1, new Object[] { "java/sql/SQLException" }); mv.visitVarInsn(ASTORE, 2); mv.visitTypeInsn(NEW, "javax/ws/rs/WebApplicationException"); mv.visitInsn(DUP); mv.visitVarInsn(ALOAD, 2); mv.visitFieldInsn(GETSTATIC, "javax/ws/rs/core/Response$Status", "INTERNAL_SERVER_ERROR", "Ljavax/ws/rs/core/Response$Status;"); mv.visitMethodInsn(INVOKESPECIAL, "javax/ws/rs/WebApplicationException", "<init>", "(Ljava/lang/Throwable;Ljavax/ws/rs/core/Response$Status;)V"); mv.visitInsn(ATHROW); mv.visitMaxs(8, 3); mv.visitEnd(); } } }
Example 29
Project: REST-OCD-Services-master File: ServiceClass.java View source code |
////////////////////////////////////////////////////////////////////////// //////////// 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 30
Project: netphony-topology-master File: ConfigApi.java View source code |
@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 31
Project: siddhi-master File: SiddhiApi.java View source code |
@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 32
Project: fullstop-master File: ViolationTypesController.java View source code |
@RequestMapping(method = GET) @ApiResponses(@ApiResponse(code = 200, message = "The list of all available violation types", response = ViolationType.class, responseContainer = "List")) public List<ViolationType> getAll() { return violationTypeRepository.findAll().stream().map(entityToDto::convert).collect(toList()); }
Example 33
Project: ORCID-Source-master File: IdentifierApiServiceImplV2_0.java View source code |
/** * @return Available external-id types in the ORCID registry */ @GET @Produces(value = { MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) @Path("") @ApiOperation(value = "Fetch identifier type map. Defaults to English descriptions", authorizations = { @Authorization(value = "orcid_two_legs", scopes = { @AuthorizationScope(scope = ScopeConstants.READ_PUBLIC, description = "you need this") }) }) @ApiResponses(value = { @ApiResponse(code = 200, message = "") }) public Response viewIdentifierTypes(@ApiParam() @QueryParam("locale") String locale) { if (locale == null || locale.isEmpty()) locale = "en"; return serviceDelegator.getIdentifierTypes(locale); }
Example 34
Project: camelinaction2-master File: RestOrderService.java View source code |
/** * 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 35
Project: typescript-generator-master File: SwaggerTest.java View source code |
@ApiResponses({ @ApiResponse(code = 400, message = "", response = TestError.class) }) @GET public Response testOperationError() { return Response.status(Response.Status.BAD_REQUEST).build(); }
Example 36
Project: gondor-master File: ClusterController.java View source code |
@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 37
Project: cerebro-master File: CerebroController.java View source code |
//SOURCES @RequestMapping(value = "/datasources/locations", method = RequestMethod.GET) @ApiResponses(value = { @ApiResponse(code = 200, message = "Returns the datasource backend location(s)") }) public Collection<URI> sources() { return graphiteSources.getIpportsByUrl().keySet(); }