Search in sources :

Example 21 with Hidden

use of io.swagger.v3.oas.annotations.Hidden in project snow-owl by b2ihealthcare.

the class RepositoryValidationRestService method getValidationResults.

@Operation(summary = "Retrieve the validation issues from a completed validation on a branch. Output may differ by the chosen content type.")
@ApiResponses({ @ApiResponse(responseCode = "200", description = "OK"), @ApiResponse(responseCode = "404", description = "Branch not found") })
@RequestMapping(value = "/validations/{validationId}/issues", method = RequestMethod.GET, produces = { AbstractRestService.JSON_MEDIA_TYPE, AbstractRestService.CSV_MEDIA_TYPE })
@ResponseBody
public Promise<Collection<Object>> getValidationResults(@Parameter(description = "The unique validation identifier.") @PathVariable(value = "validationId") final String validationId, @Parameter(description = "The search key to use for retrieving the next page of results") @RequestParam(value = "searchAfter", required = false) final String searchAfter, @Parameter(description = "The maximum number of items to return") @RequestParam(value = "limit", defaultValue = "50", required = false) final int limit, @Parameter(hidden = true) @RequestHeader(value = HttpHeaders.ACCEPT, defaultValue = AbstractRestService.JSON_MEDIA_TYPE, required = false) final String contentType) {
    final IEventBus bus = getBus();
    return getValidationRun(validationId).thenWith(validationJob -> {
        final ResourceURI codeSystemURI = getCodeSystemURIFromJob(validationJob);
        if (AbstractRestService.CSV_MEDIA_TYPE.equals(contentType)) {
            return ValidationRequests.issues().prepareSearch().isWhitelisted(false).all().filterByResourceUri(codeSystemURI).sortBy(Sort.fieldAsc(ValidationIssue.Fields.RULE_ID)).buildAsync().execute(bus).then(issues -> {
                final Set<String> rulesToFetch = issues.stream().map(ValidationIssue::getRuleId).collect(Collectors.toSet());
                final Map<String, String> ruleDescriptionById = ValidationRequests.rules().prepareSearch().all().filterByIds(rulesToFetch).buildAsync().execute(bus).getSync(1, TimeUnit.MINUTES).stream().collect(Collectors.toMap(ValidationRule::getId, ValidationRule::getMessageTemplate));
                return issues.stream().map(issue -> {
                    final String ruleId = issue.getRuleId();
                    final String ruleDescription = ruleDescriptionById.get(ruleId);
                    final String affectedComponentLabel = Iterables.getFirst(issue.getAffectedComponentLabels(), "No label found");
                    final String affectedComponentId = issue.getAffectedComponent().getComponentId();
                    return new ValidationIssueReport(ruleId, ruleDescription, affectedComponentId, affectedComponentLabel);
                }).collect(Collectors.toList());
            });
        } else {
            return ValidationRequests.issues().prepareSearch().isWhitelisted(false).setLimit(limit).setSearchAfter(searchAfter).filterByResourceUri(codeSystemURI).buildAsync().execute(bus).then(issues -> issues.getItems().stream().collect(Collectors.toList()));
        }
    });
}
Also used : Iterables(com.google.common.collect.Iterables) AbstractRestService(com.b2international.snowowl.core.rest.AbstractRestService) Promise(com.b2international.snowowl.core.events.util.Promise) Autowired(org.springframework.beans.factory.annotation.Autowired) ValidationIssue(com.b2international.snowowl.core.validation.issue.ValidationIssue) Operation(io.swagger.v3.oas.annotations.Operation) HttpHeaders(com.google.common.net.HttpHeaders) Map(java.util.Map) RemoteJobs(com.b2international.snowowl.core.jobs.RemoteJobs) ApiResponse(io.swagger.v3.oas.annotations.responses.ApiResponse) ResourceURI(com.b2international.snowowl.core.ResourceURI) ValidationRule(com.b2international.snowowl.core.validation.rule.ValidationRule) ImmutableMap(com.google.common.collect.ImmutableMap) Collection(java.util.Collection) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) Set(java.util.Set) RemoteJobEntry(com.b2international.snowowl.core.jobs.RemoteJobEntry) IEventBus(com.b2international.snowowl.eventbus.IEventBus) Collectors(java.util.stream.Collectors) IDs(com.b2international.snowowl.core.id.IDs) TimeUnit(java.util.concurrent.TimeUnit) Parameter(io.swagger.v3.oas.annotations.Parameter) HttpStatus(org.springframework.http.HttpStatus) List(java.util.List) JobRequests(com.b2international.snowowl.core.jobs.JobRequests) Sort(com.b2international.snowowl.core.request.SearchResourceRequest.Sort) Tag(io.swagger.v3.oas.annotations.tags.Tag) org.springframework.web.bind.annotation(org.springframework.web.bind.annotation) ValidationConfiguration(com.b2international.snowowl.core.internal.validation.ValidationConfiguration) ResponseEntity(org.springframework.http.ResponseEntity) ValidationRequests(com.b2international.snowowl.core.validation.ValidationRequests) ApiResponses(io.swagger.v3.oas.annotations.responses.ApiResponses) ResourceURI(com.b2international.snowowl.core.ResourceURI) IEventBus(com.b2international.snowowl.eventbus.IEventBus) Operation(io.swagger.v3.oas.annotations.Operation) ApiResponses(io.swagger.v3.oas.annotations.responses.ApiResponses)

Example 22 with Hidden

use of io.swagger.v3.oas.annotations.Hidden in project swagger-core by swagger-api.

the class HiddenFieldTest method testHiddenField.

@Test(description = "it should ignore a hidden field")
public void testHiddenField() {
    final Map<String, Schema> models = ModelConverters.getInstance().read(ModelWithHiddenFields.class);
    final Schema model = models.get("ModelWithHiddenFields");
    assertNotNull(model);
    assertEquals(model.getProperties().size(), 2);
    final Schema idValue = (Schema) model.getProperties().get("id");
    assertTrue(idValue instanceof IntegerSchema);
    assertTrue(model.getRequired().contains("id"));
    final Schema nameValue = (Schema) model.getProperties().get("name");
    assertTrue(nameValue instanceof StringSchema);
    final Schema passwordValue = (Schema) model.getProperties().get("password");
    assertNull(passwordValue);
}
Also used : IntegerSchema(io.swagger.v3.oas.models.media.IntegerSchema) StringSchema(io.swagger.v3.oas.models.media.StringSchema) Schema(io.swagger.v3.oas.models.media.Schema) IntegerSchema(io.swagger.v3.oas.models.media.IntegerSchema) StringSchema(io.swagger.v3.oas.models.media.StringSchema) Test(org.testng.annotations.Test)

Example 23 with Hidden

use of io.swagger.v3.oas.annotations.Hidden in project swagger-core by swagger-api.

the class DefaultParameterExtension method handleAdditionalAnnotation.

/**
 * Adds additional annotation processing support
 *
 * @param parameters
 * @param annotation
 * @param type
 * @param typesToSkip
 */
private boolean handleAdditionalAnnotation(List<Parameter> parameters, List<Parameter> formParameters, Annotation annotation, final Type type, Set<Type> typesToSkip, javax.ws.rs.Consumes classConsumes, javax.ws.rs.Consumes methodConsumes, Components components, boolean includeRequestBody, JsonView jsonViewAnnotation) {
    boolean processed = false;
    if (BeanParam.class.isAssignableFrom(annotation.getClass())) {
        // Use Jackson's logic for processing Beans
        final BeanDescription beanDesc = mapper.getSerializationConfig().introspect(constructType(type));
        final List<BeanPropertyDefinition> properties = beanDesc.findProperties();
        for (final BeanPropertyDefinition propDef : properties) {
            final AnnotatedField field = propDef.getField();
            final AnnotatedMethod setter = propDef.getSetter();
            final AnnotatedMethod getter = propDef.getGetter();
            final List<Annotation> paramAnnotations = new ArrayList<>();
            final Iterator<OpenAPIExtension> extensions = OpenAPIExtensions.chain();
            Type paramType = null;
            // Gather the field's details
            if (field != null) {
                paramType = field.getType();
                AnnotationMap annotationMap = field.getAllAnnotations();
                if (annotationMap != null) {
                    for (final Annotation fieldAnnotation : annotationMap.annotations()) {
                        if (!paramAnnotations.contains(fieldAnnotation)) {
                            paramAnnotations.add(fieldAnnotation);
                        }
                    }
                }
            }
            // Gather the setter's details but only the ones we need
            if (setter != null) {
                // Do not set the param class/type from the setter if the values are already identified
                if (paramType == null) {
                    // paramType will stay null if there is no parameter
                    paramType = setter.getParameterType(0);
                }
                AnnotationMap annotationMap = setter.getAllAnnotations();
                if (annotationMap != null) {
                    for (final Annotation fieldAnnotation : annotationMap.annotations()) {
                        if (!paramAnnotations.contains(fieldAnnotation)) {
                            paramAnnotations.add(fieldAnnotation);
                        }
                    }
                }
            }
            // Gather the getter's details but only the ones we need
            if (getter != null) {
                // Do not set the param class/type from the getter if the values are already identified
                if (paramType == null) {
                    paramType = getter.getType();
                }
                AnnotationMap annotationMap = getter.getAllAnnotations();
                if (annotationMap != null) {
                    for (final Annotation fieldAnnotation : annotationMap.annotations()) {
                        if (!paramAnnotations.contains(fieldAnnotation)) {
                            paramAnnotations.add(fieldAnnotation);
                        }
                    }
                }
            }
            if (paramType == null) {
                continue;
            }
            // skip hidden properties
            boolean hidden = false;
            for (Annotation a : paramAnnotations) {
                if (a instanceof io.swagger.v3.oas.annotations.media.Schema) {
                    if (((io.swagger.v3.oas.annotations.media.Schema) a).hidden()) {
                        hidden = true;
                        break;
                    }
                    ;
                } else if (a instanceof Hidden) {
                    hidden = true;
                    break;
                }
            }
            if (hidden) {
                continue;
            }
            // Re-process all Bean fields and let the default swagger-jaxrs/swagger-jersey-jaxrs processors do their thing
            ResolvedParameter resolvedParameter = extensions.next().extractParameters(paramAnnotations, paramType, typesToSkip, components, classConsumes, methodConsumes, includeRequestBody, jsonViewAnnotation, extensions);
            List<Parameter> extractedParameters = resolvedParameter.parameters;
            for (Parameter p : extractedParameters) {
                Parameter processedParam = ParameterProcessor.applyAnnotations(p, paramType, paramAnnotations, components, classConsumes == null ? new String[0] : classConsumes.value(), methodConsumes == null ? new String[0] : methodConsumes.value(), jsonViewAnnotation);
                if (processedParam != null) {
                    parameters.add(processedParam);
                }
            }
            List<Parameter> extractedFormParameters = resolvedParameter.formParameters;
            for (Parameter p : extractedFormParameters) {
                Parameter processedParam = ParameterProcessor.applyAnnotations(p, paramType, paramAnnotations, components, classConsumes == null ? new String[0] : classConsumes.value(), methodConsumes == null ? new String[0] : methodConsumes.value(), jsonViewAnnotation);
                if (processedParam != null) {
                    formParameters.add(processedParam);
                }
            }
            processed = true;
        }
    }
    return processed;
}
Also used : AnnotatedMethod(com.fasterxml.jackson.databind.introspect.AnnotatedMethod) BeanDescription(com.fasterxml.jackson.databind.BeanDescription) ArrayList(java.util.ArrayList) AbstractOpenAPIExtension(io.swagger.v3.jaxrs2.ext.AbstractOpenAPIExtension) OpenAPIExtension(io.swagger.v3.jaxrs2.ext.OpenAPIExtension) Annotation(java.lang.annotation.Annotation) Type(java.lang.reflect.Type) AnnotationMap(com.fasterxml.jackson.databind.introspect.AnnotationMap) BeanPropertyDefinition(com.fasterxml.jackson.databind.introspect.BeanPropertyDefinition) Hidden(io.swagger.v3.oas.annotations.Hidden) Parameter(io.swagger.v3.oas.models.parameters.Parameter) AnnotatedField(com.fasterxml.jackson.databind.introspect.AnnotatedField)

Example 24 with Hidden

use of io.swagger.v3.oas.annotations.Hidden in project Singularity by HubSpot.

the class TaskResource method postTaskMetadata.

@POST
@Path("/task/{taskId}/metadata")
@Operation(summary = "Post metadata about a task that will be persisted along with it and displayed in the UI", responses = { @ApiResponse(responseCode = "400", description = "Invalid metadata object or doesn't match allowed types"), @ApiResponse(responseCode = "404", description = "Task doesn't exist"), @ApiResponse(responseCode = "409", description = "Metadata with this type/timestamp already existed") })
@Consumes({ MediaType.APPLICATION_JSON })
public void postTaskMetadata(@Parameter(hidden = true) @Auth SingularityUser user, @Parameter(required = true, description = "Id of the task") @PathParam("taskId") String taskId, @RequestBody(description = "Metadata to attach to the task", required = true) final SingularityTaskMetadataRequest taskMetadataRequest) {
    SingularityTaskId taskIdObj = getTaskIdFromStr(taskId);
    authorizationHelper.checkForAuthorizationByTaskId(taskId, user, SingularityAuthorizationScope.WRITE);
    validator.checkActionEnabled(SingularityAction.ADD_METADATA);
    checkBadRequest(taskMetadataRequest.getTitle().length() < taskMetadataConfiguration.getMaxMetadataTitleLength(), "Task metadata title too long, must be less than %s bytes", taskMetadataConfiguration.getMaxMetadataTitleLength());
    int messageLength = taskMetadataRequest.getMessage().isPresent() ? taskMetadataRequest.getMessage().get().length() : 0;
    checkBadRequest(!taskMetadataRequest.getMessage().isPresent() || messageLength < taskMetadataConfiguration.getMaxMetadataMessageLength(), "Task metadata message too long, must be less than %s bytes", taskMetadataConfiguration.getMaxMetadataMessageLength());
    if (taskMetadataConfiguration.getAllowedMetadataTypes().isPresent()) {
        checkBadRequest(taskMetadataConfiguration.getAllowedMetadataTypes().get().contains(taskMetadataRequest.getType()), "%s is not one of the allowed metadata types %s", taskMetadataRequest.getType(), taskMetadataConfiguration.getAllowedMetadataTypes().get());
    }
    checkNotFound(taskManager.taskExistsInZk(taskIdObj), "Task %s not found in ZooKeeper (can not save metadata to tasks which have been persisted", taskIdObj);
    final SingularityTaskMetadata taskMetadata = new SingularityTaskMetadata(taskIdObj, System.currentTimeMillis(), taskMetadataRequest.getType(), taskMetadataRequest.getTitle(), taskMetadataRequest.getMessage(), user.getEmail(), taskMetadataRequest.getLevel());
    SingularityCreateResult result = taskManager.saveTaskMetadata(taskMetadata);
    WebExceptions.checkConflict(result == SingularityCreateResult.CREATED, "Task metadata conficted with existing metadata for %s at %s", taskMetadata.getType(), taskMetadata.getTimestamp());
}
Also used : SingularityTaskMetadata(com.hubspot.singularity.SingularityTaskMetadata) SingularityCreateResult(com.hubspot.singularity.SingularityCreateResult) SingularityTaskId(com.hubspot.singularity.SingularityTaskId) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes) Operation(io.swagger.v3.oas.annotations.Operation)

Example 25 with Hidden

use of io.swagger.v3.oas.annotations.Hidden in project Singularity by HubSpot.

the class TaskResource method getShellCommandHisotryUpdates.

@GET
@Path("/task/{taskId}/command/{commandName}/{commandTimestamp}")
@Operation(summary = "Retrieve a list of shell commands updates for a particular shell command on a task")
public List<SingularityTaskShellCommandUpdate> getShellCommandHisotryUpdates(@Parameter(hidden = true) @Auth SingularityUser user, @Parameter(required = true, description = "Id of the task") @PathParam("taskId") String taskId, @Parameter(required = true, description = "name of the command that was run") @PathParam("commandName") String commandName, @Parameter(required = true, description = "Timestamp of the original shell command request") @PathParam("commandTimestamp") Long commandTimestamp) {
    authorizationHelper.checkForAuthorizationByTaskId(taskId, user, SingularityAuthorizationScope.READ);
    SingularityTaskId taskIdObj = getTaskIdFromStr(taskId);
    return taskManager.getTaskShellCommandUpdates(new SingularityTaskShellCommandRequestId(taskIdObj, commandName, commandTimestamp));
}
Also used : SingularityTaskShellCommandRequestId(com.hubspot.singularity.SingularityTaskShellCommandRequestId) SingularityTaskId(com.hubspot.singularity.SingularityTaskId) Path(javax.ws.rs.Path) GET(javax.ws.rs.GET) Operation(io.swagger.v3.oas.annotations.Operation)

Aggregations

Operation (io.swagger.v3.oas.annotations.Operation)29 Path (javax.ws.rs.Path)25 GET (javax.ws.rs.GET)21 POST (javax.ws.rs.POST)6 SingularityTaskHistoryQuery (com.hubspot.singularity.SingularityTaskHistoryQuery)5 SingularityTaskId (com.hubspot.singularity.SingularityTaskId)5 List (java.util.List)4 Consumes (javax.ws.rs.Consumes)4 Produces (javax.ws.rs.Produces)4 SingularityPaginatedResponse (com.hubspot.singularity.SingularityPaginatedResponse)3 SingularityRequestWithState (com.hubspot.singularity.SingularityRequestWithState)3 SingularityTaskIdHistory (com.hubspot.singularity.SingularityTaskIdHistory)3 Schema (io.swagger.v3.oas.models.media.Schema)3 BeanDescription (com.fasterxml.jackson.databind.BeanDescription)2 AnnotatedMethod (com.fasterxml.jackson.databind.introspect.AnnotatedMethod)2 SingularityTaskHistory (com.hubspot.singularity.SingularityTaskHistory)2 Hidden (io.swagger.v3.oas.annotations.Hidden)2 GenericOpenApiContext (io.swagger.v3.oas.integration.GenericOpenApiContext)2 OpenAPIConfiguration (io.swagger.v3.oas.integration.api.OpenAPIConfiguration)2 OpenApiContext (io.swagger.v3.oas.integration.api.OpenApiContext)2