@Override public void applyConsumes(ReaderContext context, Operation operation, Method method) { final List<String> consumes = new ArrayList<String>(); final ApiOperation apiOperation = ReflectionUtils.getAnnotation(method, ApiOperation.class); if (apiOperation != null) { consumes.addAll(parseStringValues(apiOperation.consumes())); } if (consumes.isEmpty()) { final Api apiAnnotation = context.getCls().getAnnotation(Api.class); if (apiAnnotation != null) { consumes.addAll(parseStringValues(apiAnnotation.consumes())); } consumes.addAll(context.getParentConsumes()); } for (String consume : consumes) { operation.consumes(consume); } }
@Override public void applyProduces(ReaderContext context, Operation operation, Method method) { final List<String> produces = new ArrayList<String>(); final ApiOperation apiOperation = ReflectionUtils.getAnnotation(method, ApiOperation.class); if (apiOperation != null) { produces.addAll(parseStringValues(apiOperation.produces())); } if (produces.isEmpty()) { final Api apiAnnotation = context.getCls().getAnnotation(Api.class); if (apiAnnotation != null) { produces.addAll(parseStringValues(apiAnnotation.produces())); } produces.addAll(context.getParentProduces()); } for (String produce : produces) { operation.produces(produce); } }
@Override public void applySchemes(ReaderContext context, Operation operation, Method method) { final List<Scheme> schemes = new ArrayList<Scheme>(); final ApiOperation apiOperation = ReflectionUtils.getAnnotation(method, ApiOperation.class); final Api apiAnnotation = context.getCls().getAnnotation(Api.class); if (apiOperation != null) { schemes.addAll(parseSchemes(apiOperation.protocols())); } if (schemes.isEmpty() && apiAnnotation != null) { schemes.addAll(parseSchemes(apiAnnotation.protocols())); } for (Scheme scheme : schemes) { operation.scheme(scheme); } }
@Override public void process(final CtInterface<?> restServiceInterface) { final CtAnnotation<Annotation> annotation = getFactory().Code().createAnnotation(getFactory().Code().createCtTypeReference(Api.class)); final String classFqn = restServiceInterface.getQualifiedName(); final RestService restService = context.getServiceDocumentation().get(classFqn); if (restService != null) { annotation.addValue("tags", restService.getTags()); restServiceInterface.addAnnotation(annotation); // Add path annotation if missing final Path pathAnnotation = restServiceInterface.getAnnotation(Path.class); if (pathAnnotation == null) { final CtAnnotation<Path> path = getFactory().Code().createAnnotation(getFactory().Code().createCtTypeReference(Path.class)); path.addValue("value", restService.getPath()); restServiceInterface.addAnnotation(path); } log.debug("Added @Api to {} [{}]", restServiceInterface.getQualifiedName(), classFqn); } else { log.error("No documentation found for {} [{}]", restServiceInterface.getQualifiedName(), classFqn); } }
@Override public void process(final CtInterface<?> resourceInterface) { final CtAnnotation<Annotation> annotation = getFactory().Code().createAnnotation(getFactory().Code().createCtTypeReference(Api.class)); final RestService restService = context.getServiceDocumentation().get(resourceInterface.getQualifiedName()); if (restService != null) { String[] tags; if (restService.getTags().contains(",")) { tags = restService.getTags().split(","); } else { tags = new String[]{ restService.getTags() }; } annotation // .addValue("tags", tags) .addValue("hidden", true); resourceInterface.addAnnotation(annotation); } else { log.error("No documentation for resource {} found.", resourceInterface.getQualifiedName()); } }
@Path("/events") @GET @Produces(MediaType.APPLICATION_JSON) @Permissions({ @Permission(value = RolePermission.API_AUDIT, acls = RolePermissionAction.READ) }) public Response getEvents() { List<Audit.AuditEvent> events = new ArrayList<>(); events.addAll(Arrays.asList(io.gravitee.repository.management.model.Api.AuditEvent.values())); events.addAll(Arrays.asList(ApiKey.AuditEvent.values())); events.addAll(Arrays.asList(Membership.AuditEvent.values())); events.addAll(Arrays.asList(Metadata.AuditEvent.values())); events.addAll(Arrays.asList(io.gravitee.repository.management.model.Page.AuditEvent.values())); events.addAll(Arrays.asList(Plan.AuditEvent.values())); events.addAll(Arrays.asList(Subscription.AuditEvent.values())); events.sort(Comparator.comparing(Audit.AuditEvent::name)); return Response.ok(events).build(); }
@Path("/events") @GET @Produces(MediaType.APPLICATION_JSON) @Permissions({ @Permission(value = RolePermission.MANAGEMENT_AUDIT, acls = RolePermissionAction.READ) }) public Response getEvents() { List<Audit.AuditEvent> events = new ArrayList<>(); events.addAll(Arrays.asList(io.gravitee.repository.management.model.Api.AuditEvent.values())); events.addAll(Arrays.asList(ApiKey.AuditEvent.values())); events.addAll(Arrays.asList(Application.AuditEvent.values())); events.addAll(Arrays.asList(Group.AuditEvent.values())); events.addAll(Arrays.asList(Membership.AuditEvent.values())); events.addAll(Arrays.asList(Metadata.AuditEvent.values())); events.addAll(Arrays.asList(io.gravitee.repository.management.model.Page.AuditEvent.values())); events.addAll(Arrays.asList(Plan.AuditEvent.values())); events.addAll(Arrays.asList(Role.AuditEvent.values())); events.addAll(Arrays.asList(Subscription.AuditEvent.values())); events.addAll(Arrays.asList(Tag.AuditEvent.values())); events.addAll(Arrays.asList(Tenant.AuditEvent.values())); events.addAll(Arrays.asList(User.AuditEvent.values())); events.addAll(Arrays.asList(View.AuditEvent.values())); events.sort(Comparator.comparing(Audit.AuditEvent::name)); return Response.ok(events).build(); }
protected Class<?> getSubResource(Method method) { final Class<?> rawType = method.getReturnType(); final Class<?> type; if (Class.class.equals(rawType)) { type = getClassArgument(method.getGenericReturnType()); if (type == null) { return null; } } else { type = rawType; } if (type.getAnnotation(Api.class) != null) { return type; } // For sub-resources that are not annotated with @Api, look for any HttpMethods. for (Method m : type.getMethods()) { if (extractOperationMethod(null, m, null) != null) { return type; } } return null; }
protected Set<String> extractTags(Api api) { Set<String> output = new LinkedHashSet<>(); boolean hasExplicitTags = false; for (String tag : api.tags()) { if (!"".equals(tag)) { hasExplicitTags = true; output.add(tag); } } if (!hasExplicitTags) { // derive tag from api path + description String tagString = api.value().replace("/", ""); if (!"".equals(tagString)) { output.add(tagString); } } return output; }
protected Set<String> extractTags(Api api) { Set<String> output = new LinkedHashSet<String>(); boolean hasExplicitTags = false; for (String tag : api.tags()) { if (!"".equals(tag)) { hasExplicitTags = true; output.add(tag); } } if (!hasExplicitTags) { // derive tag from api path + description String tagString = api.value().replace("/", ""); if (!"".equals(tagString)) { output.add(tagString); } } return output; }
@Test public void testNamespacingByAnnotation() { final Settings settings = TestUtils.settings(); settings.outputFileType = TypeScriptFileType.implementationFile; settings.generateJaxrsApplicationInterface = true; settings.generateJaxrsApplicationClient = true; settings.jaxrsNamespacing = JaxrsNamespacing.byAnnotation; settings.jaxrsNamespacingAnnotation = Api.class; final String output = new TypeScriptGenerator(settings).generateTypeScript(Input.from(OrganizationApplication.class)); final String errorMessage = "Unexpected output: " + output; Assert.assertTrue(errorMessage, output.contains("class OrgApiClient implements OrgApi ")); Assert.assertTrue(errorMessage, output.contains("class OrganizationApplicationClient implements OrganizationApplication ")); Assert.assertTrue(errorMessage, !output.contains("class OrganizationsResourceClient")); Assert.assertTrue(errorMessage, !output.contains("class OrganizationResourceClient")); Assert.assertTrue(errorMessage, !output.contains("class PersonResourceClient")); }
@Override public void execute() throws MojoExecutionException, MojoFailureException { checkState(!packageNames.isEmpty(), "Must specify package names"); ClassLoader classLoader = getProjectClassLoader(); ApiBuilder builder = ApiRoot.builder().version(apiVersion).basePath(apiBasePath); ClassCollector collector = new ClassCollector(); for (String packageName : packageNames) { collector.addClasses(classLoader, packageName, Api.class); if (!excludeUnannotatedApi) { collector.addClasses(classLoader, packageName, Path.class); } } for (Class<?> apiClass : collector.getClasses()) { getLog().info("API class: " + apiClass.getName()); builder.service(apiClass); } ApiRoot apiRoot = builder.create(); output(apiRoot); }
@SuppressWarnings("deprecation") public ApiBuilder service(Class<?> clazz) { checkNotNull(clazz, "Must provide a service class"); ServiceBuilder builder = Service.builder(); Path path = clazz.getAnnotation(Path.class); if (path != null) { builder.path(path.value()); } Api api = clazz.getAnnotation(Api.class); if (api != null) { builder.path(api.value()).description(api.description()); } builder.methods(clazz); serviceBuilders.add(builder); return this; }
protected List<SecurityRequirement> getSecurityRequirements(Api api) { List<SecurityRequirement> securities = new ArrayList<SecurityRequirement>(); if(api == null) { return securities; } for (Authorization auth : api.authorizations()) { if (auth.value().isEmpty()) { continue; } SecurityRequirement security = new SecurityRequirement(); security.setName(auth.value()); for (AuthorizationScope scope : auth.scopes()) { if (!scope.scope().isEmpty()) { security.addScope(scope.scope()); } } securities.add(security); } return securities; }
private void setTags(Api api, SwaggerGenerator swaggerGenerator) { String[] tags = api.tags(); for (String tagName : tags) { if (StringUtils.isEmpty(tagName)) { continue; } swaggerGenerator.addDefaultTag(tagName); } }
protected void initClassAnnotationMgr() { classAnnotationMgr.register(Api.class, new ApiProcessor()); classAnnotationMgr.register(SwaggerDefinition.class, new SwaggerDefinitionProcessor()); classAnnotationMgr.register(ApiImplicitParams.class, new ApiImplicitParamsClassProcessor()); classAnnotationMgr.register(ApiImplicitParam.class, new ApiImplicitParamClassProcessor()); classAnnotationMgr.register(ApiResponses.class, new ApiResponsesClassProcessor()); classAnnotationMgr.register(ApiResponse.class, new ApiResponseClassProcessor()); }
@Test public void process() { SwaggerGenerator swaggerGenerator = new SwaggerGenerator(Mockito.mock(SwaggerGeneratorContext.class), null); apiProcessor.process(SwaggerTestTarget.class.getAnnotation(Api.class), swaggerGenerator); assertThat(swaggerGenerator.getDefaultTags(), contains("tag1", "tag2")); }
@Test public void processOnNoTag() { SwaggerGenerator swaggerGenerator = new SwaggerGenerator(Mockito.mock(SwaggerGeneratorContext.class), null); apiProcessor.process(SwaggerTestTargetWithNoTag.class.getAnnotation(Api.class), swaggerGenerator); Set<String> tags = swaggerGenerator.getDefaultTags(); assertEquals(0, tags.size()); }
@Override public String getPath(ReaderContext context, Method method) { String p = null; Api apiAnnotation = context.getCls().getAnnotation(Api.class); ApiOperation apiOperation = ReflectionUtils.getAnnotation(method, ApiOperation.class); String operationPath = apiOperation == null ? null : apiOperation.nickname(); if (operationPath != null && !operationPath.isEmpty()) { // same logic as ServletReaderExtension p = PathUtils.collectPath(context.getParentPath(), apiAnnotation == null ? null : apiAnnotation.value(), operationPath); } else { // try JAX-RS annotations Path parentPath = ReflectionUtils.getAnnotation(method.getDeclaringClass(), Path.class); if (parentPath != null && parentPath.value() != null && !parentPath.value().isEmpty()) { p = parentPath.value(); } Path path = ReflectionUtils.getAnnotation(method, Path.class); if (path != null && path.value() != null && !path.value().isEmpty()) { if (p == null) p = path.value(); else { if (path.value().startsWith("/")) p += path.value(); else p = p + "/" + path.value(); } } } return p; }
public void applyTags(ReaderContext context, Operation operation, Method method) { super.applyTags(context, operation, method); Class<?> declaringClass = method.getDeclaringClass(); Api apiAnnotation = declaringClass.getAnnotation(Api.class); if (apiAnnotation != null && apiAnnotation.value() != null && !apiAnnotation.value().isEmpty()) { operation.addTag(apiAnnotation.value()); } }
public Set<Class<?>> getClasses() throws ClassNotFoundException { Set<Class<?>> classes = new HashSet<>(); List<String> apiDefinitionClasses = getApiDefinitionClasses(); if (apiDefinitionClasses == null) { classes.add(DefaultSwaggerDefinition.class); } else { for (String apiDefClass : apiDefinitionClasses) { classes.add(Class.forName(apiDefClass)); } } // service classes ServiceRegistry.getInstance().getClasses().stream().filter(c -> { Api apiAnnotation = c.getAnnotation(Api.class); if (apiAnnotation != null) { if ("/".equals(servicePath)) { return true; } else { String path = c.getSimpleName(); Path pathAnnotation = c.getAnnotation(Path.class); if (pathAnnotation != null && pathAnnotation.value() != null) path = pathAnnotation.value(); return path.startsWith(servicePath) || ("/" + path).startsWith(servicePath); } } return false; }).forEach(c -> classes.add(c)); return classes; }
public SwaggerHandler( final Class<? extends Application> applicationClass) { final ApplicationPath annotation = applicationClass.getAnnotation(ApplicationPath.class); if (annotation != null) { baseUri = URI.create(annotation.value()).normalize(); } else { baseUri = URI.create("/"); } Application application; try { application = applicationClass.newInstance(); } catch (InstantiationException | IllegalAccessException e) { throw new ExceptionInInitializerError(e); } swagger = new ClonableSwagger(); final Reader swaggerReader = new Reader(swagger); final Set<Class<?>> resourceClasses = application.getClasses(); if (resourceClasses.isEmpty()) { final String packageName = applicationClass.getPackage().getName(); final Reflections reflections = new Reflections(packageName); reflections.getTypesAnnotatedWith(Api.class).forEach(swaggerReader::read); reflections.getTypesAnnotatedWith(SwaggerDefinition.class).forEach(swaggerReader::read); } else { swaggerReader.read(applicationClass); resourceClasses.forEach(swaggerReader::read); } }
/** * Api docket. * * @return the docket */ @Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.withClassAnnotation(Api.class)) .paths(PathSelectors.any()) .build() .apiInfo(aipInfo()); }
@Override @SneakyThrows public JCodeModel generate() { final JDefinedClass c = camundaRestService.getDefinedClass(); // class information c._extends(camundaRestService.getServiceImplClass()); c.annotate(codeModel.ref(Path.class)).param("value", camundaRestService.getPath()); final String tags = TagRespository.lookup(camundaRestService); camundaRestService.getRestService().setPath(camundaRestService.getPath()); camundaRestService.getRestService().setTags(tags); camundaRestService.getRestService().setDescription(camundaRestService.getName()); c.annotate(codeModel.ref(Api.class)).param("value", camundaRestService.getName()).param("tags", tags); // generate constructor for (final Constructor<?> constructor : camundaRestService.getServiceImplClass().getConstructors()) { new InvocationStep(c.constructor(constructor.getModifiers())).constructor(constructor); } // construct return type information final Map<Method, ReturnTypeInfo> returnTypes = Arrays.stream(camundaRestService.getServiceInterfaceClass().getDeclaredMethods()) // iterate over interface // methods .map(m -> new ReturnTypeInfo(camundaRestService.getModelRepository(), codeModel, m) .applyImplementationMethods(camundaRestService.getServiceImplClass().getDeclaredMethods())) // apply impl methods .collect(Collectors.toMap(r -> r.getMethod(), r -> r)); // build the map generateMethods(c, camundaRestService.getRestService(), returnTypes, NO_PREFIX); return this.codeModel; }
private Operation buildOperation(ExecutableElement executableElement) { Operation operation = new Operation(); String operationId = ofNullable(executableElement.getAnnotation(ApiOperation.class)) .map(ApiOperation::nickname) .filter(StringUtils::isNotBlank) .orElse(executableElement.getSimpleName().toString()); operation.setOperationId(operationId); Element controller = executableElement.getEnclosingElement(); Optional<Api> apiAnnotation = ofNullable(controller.getAnnotation(Api.class)); apiAnnotation.ifPresent(annotation -> Stream.of(annotation.tags()) .filter(StringUtils::isNotBlank) .forEach(operation::addTag)); executableElement.getParameters() .stream() .map(this::buildParameter) .filter(Optional::isPresent) .map(Optional::get) .forEach(operation::addParameter); Response okResponse = new Response(); Property returnProperty = ofNullable(executableElement.getAnnotation(ApiOperation.class)) .map(apiOperation -> annotationUtils.extractType(apiOperation, ApiOperation::response)) .filter(returnType -> returnType.getKind() != TypeKind.VOID) .map(propertyUtils::toProperty) .orElseGet(() -> propertyUtils.toProperty(executableElement.getReturnType())); okResponse.schema(returnProperty); operation.response(200, okResponse); return operation; }
@Override public boolean support(Class clazz, Method method) { Api api = AnnotationUtils.findAnnotation(clazz, Api.class); ApiOperation operation = AnnotationUtils.findAnnotation(method, ApiOperation.class); return api != null || operation != null; }
@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(); } return new LoggerDefine(action, ""); }
private boolean isAnnotated(Class<?> clz) { if (clz.getAnnotation(Api.class) != null) { return true; } if (clz.getAnnotation(SwaggerDefinition.class) != null) { return true; } if (clz.getAnnotation(javax.ws.rs.Path.class) != null) { return true; } return false; }
@Override public void applyTags(ReaderContext context, Operation operation, Method method) { super.applyTags(context, operation, method); Class<?> declaringClass = method.getDeclaringClass(); Api apiAnnotation = declaringClass.getAnnotation(Api.class); if (apiAnnotation != null && apiAnnotation.value() != null && !apiAnnotation.value().isEmpty()) { operation.addTag(apiAnnotation.value()); } }
private Subscription convert(SubscriptionEntity subscriptionEntity) { Subscription subscription = new Subscription(); subscription.setId(subscriptionEntity.getId()); subscription.setCreatedAt(subscriptionEntity.getCreatedAt()); subscription.setUpdatedAt(subscriptionEntity.getUpdatedAt()); subscription.setStartingAt(subscriptionEntity.getStartingAt()); subscription.setEndingAt(subscriptionEntity.getEndingAt()); subscription.setProcessedAt(subscriptionEntity.getProcessedAt()); subscription.setProcessedBy(subscriptionEntity.getProcessedBy()); subscription.setReason(subscriptionEntity.getReason()); subscription.setStatus(subscriptionEntity.getStatus()); ApplicationEntity application = applicationService.findById(subscriptionEntity.getApplication()); subscription.setApplication( new Subscription.Application( application.getId(), application.getName(), application.getType(), new Subscription.Owner( application.getPrimaryOwner().getUsername(), application.getPrimaryOwner().getFirstname(), application.getPrimaryOwner().getLastname() ) )); PlanEntity plan = planService.findById(subscriptionEntity.getPlan()); subscription.setPlan(new Subscription.Plan(plan.getId(), plan.getName())); subscription.getPlan().setApis(plan.getApis().stream().map(api -> { io.gravitee.management.model.ApiEntity apiEntity = apiService.findById(api); return new Subscription.Api(apiEntity.getId(), apiEntity.getName(), apiEntity.getVersion()); }).collect(Collectors.toList())); subscription.setClosedAt(subscriptionEntity.getClosedAt()); return subscription; }
@Bean public Docket api(){ return new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.withClassAnnotation(Api.class)) .paths(PathSelectors.any()) .build() .apiInfo(apiInfo()); }
protected Class<?> getSubResource(Method method) { final Class<?> rawType = method.getReturnType(); final Class<?> type; if (Class.class.equals(rawType)) { type = getClassArgument(method.getGenericReturnType()); if (type == null) { return null; } } else { type = rawType; } if (type.getAnnotation(Api.class) != null) { return type; } if (config.isScanAllResources()) { // For sub-resources that are not annotated with @Api, look for any HttpMethods. for (Method m : type.getMethods()) { if (extractOperationMethod(null, m, null) != null) { return type; } } } return null; }
@Bean public Docket grassrootApi() { return new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.withClassAnnotation(Api.class)) .paths(PathSelectors.any()) .build() .useDefaultResponseMessages(false) .apiInfo(apiInfo()); }
private String calculatePath(Class<?> clazz, Method method) { Path path = clazz.getAnnotation(Path.class); String apiPath = path.value(); Api api = clazz.getAnnotation(Api.class); if (api != null) { apiPath = api.value(); } Path methodPath = method.getAnnotation(Path.class); if (methodPath != null) { apiPath += '/' + stripLeadingSlash(methodPath.value()); } return apiPath; }