use of io.swagger.v3.oas.models.security in project carbon-apimgt by wso2.
the class OAS3Parser method validateAPIDefinition.
/**
* This method validates the given OpenAPI definition by content
*
* @param apiDefinition OpenAPI Definition content
* @param host OpenAPI Definition url
* @param returnJsonContent whether to return the converted json form of the OpenAPI definition
* @return APIDefinitionValidationResponse object with validation information
*/
@Override
public APIDefinitionValidationResponse validateAPIDefinition(String apiDefinition, String host, boolean returnJsonContent) throws APIManagementException {
APIDefinitionValidationResponse validationResponse = new APIDefinitionValidationResponse();
OpenAPIV3Parser openAPIV3Parser = new OpenAPIV3Parser();
ParseOptions options = new ParseOptions();
options.setResolve(true);
SwaggerParseResult parseAttemptForV3 = openAPIV3Parser.readContents(apiDefinition, null, options);
if (CollectionUtils.isNotEmpty(parseAttemptForV3.getMessages())) {
validationResponse.setValid(false);
for (String message : parseAttemptForV3.getMessages()) {
OASParserUtil.addErrorToValidationResponse(validationResponse, message);
if (message.contains(APIConstants.OPENAPI_IS_MISSING_MSG)) {
ErrorItem errorItem = new ErrorItem();
errorItem.setErrorCode(ExceptionCodes.INVALID_OAS3_FOUND.getErrorCode());
errorItem.setMessage(ExceptionCodes.INVALID_OAS3_FOUND.getErrorMessage());
errorItem.setDescription(ExceptionCodes.INVALID_OAS3_FOUND.getErrorMessage());
validationResponse.getErrorItems().add(errorItem);
}
}
} else {
OpenAPI openAPI = parseAttemptForV3.getOpenAPI();
io.swagger.v3.oas.models.info.Info info = openAPI.getInfo();
List<String> endpoints;
String endpointWithHost = "";
if (openAPI.getServers() == null || openAPI.getServers().isEmpty()) {
endpoints = null;
} else {
endpoints = openAPI.getServers().stream().map(url -> url.getUrl()).collect(Collectors.toList());
for (String endpoint : endpoints) {
if (endpoint.startsWith("/")) {
if (StringUtils.isEmpty(host)) {
endpointWithHost = "http://api.yourdomain.com" + endpoint;
} else {
endpointWithHost = host + endpoint;
}
endpoints.set(endpoints.indexOf(endpoint), endpointWithHost);
}
}
}
String title = null;
String context = null;
if (!StringUtils.isBlank(info.getTitle())) {
title = info.getTitle();
context = info.getTitle().replaceAll("\\s", "").toLowerCase();
}
OASParserUtil.updateValidationResponseAsSuccess(validationResponse, apiDefinition, openAPI.getOpenapi(), title, info.getVersion(), context, info.getDescription(), endpoints);
validationResponse.setParser(this);
if (returnJsonContent) {
if (!apiDefinition.trim().startsWith("{")) {
// not a json (it is yaml)
JsonNode jsonNode = DeserializationUtils.readYamlTree(apiDefinition);
validationResponse.setJsonContent(jsonNode.toString());
} else {
validationResponse.setJsonContent(apiDefinition);
}
}
}
return validationResponse;
}
use of io.swagger.v3.oas.models.security in project gravitee-management-rest-api by gravitee-io.
the class WSDLToOpenAPIConverter method processPorts.
private void processPorts(Service serviceDefinition) {
Map<String, Port> ports = serviceDefinition.getPorts();
Iterator<Entry<String, Port>> portIterator = ports.entrySet().iterator();
final boolean singlePort = (ports.size() == 1);
while (portIterator.hasNext()) {
Entry<String, Port> entry = portIterator.next();
String portName = entry.getKey();
Port portDefinition = entry.getValue();
// create Server section for the given port
createServer(openAPI, portDefinition);
final Binding binding = wsdlDefinition.getBinding(portDefinition.getBinding().getQName());
for (int i = 0; i < binding.getBindingOperations().size(); ++i) {
final BindingOperation bindingOperation = (BindingOperation) binding.getBindingOperations().get(i);
final Operation operation = bindingOperation.getOperation();
final String operationName = operation.getName();
PathItem pathItem = new PathItem();
io.swagger.v3.oas.models.Operation openApiOperation = new io.swagger.v3.oas.models.Operation();
openApiOperation.operationId(String.join("_", binding.getQName().getLocalPart(), operationName));
if (operation.getDocumentationElement() != null) {
openApiOperation.description(operation.getDocumentationElement().getTextContent());
}
Input input = operation.getInput();
if (input != null) {
extractSOAPAction(bindingOperation).ifPresent(action -> openApiOperation.addExtension(SOAP_EXTENSION_ACTION, action));
this.soapBuilder.generateSoapEnvelop(wsdlDefinition, binding, bindingOperation).ifPresent(envelope -> openApiOperation.addExtension(SOAP_EXTENSION_ENVELOPE, envelope));
}
// create an empty Content definition used by each response description
Content nodefContent = new Content();
io.swagger.v3.oas.models.media.MediaType item = new io.swagger.v3.oas.models.media.MediaType();
io.swagger.v3.oas.models.media.Schema schema = new io.swagger.v3.oas.models.media.Schema();
schema.setType("object");
item.setSchema(schema);
nodefContent.addMediaType(MediaType.APPLICATION_JSON, item);
Output output = operation.getOutput();
ApiResponse successResp = new ApiResponse();
successResp.content(nodefContent);
// description is mandatory
successResp.setDescription("");
if (output != null) {
Message msg = output.getMessage();
if (msg != null) {
if (msg.getDocumentationElement() != null) {
successResp.description(operation.getDocumentationElement().getTextContent());
}
}
}
ApiResponse errorResp = new ApiResponse();
errorResp.description("Error throws by the Backend Service");
errorResp.content(nodefContent);
ApiResponses responses = new ApiResponses();
responses.addApiResponse(Integer.toString(HttpStatusCode.OK_200), successResp);
responses.addApiResponse(Integer.toString(HttpStatusCode.INTERNAL_SERVER_ERROR_500), errorResp);
openApiOperation.setResponses(responses);
// TODO use the http:binding element to extract the HTTP method (ยง4.4) ?
switch(detectHttpMethod(operationName)) {
case GET:
pathItem.get(openApiOperation);
break;
case DELETE:
pathItem.delete(openApiOperation);
break;
case PUT:
pathItem.put(openApiOperation);
break;
default:
pathItem.post(openApiOperation);
}
if (singlePort) {
openAPI.path(String.join("/", "", serviceDefinition.getQName().getLocalPart(), operationName), pathItem);
} else {
openAPI.path(String.join("/", "", serviceDefinition.getQName().getLocalPart(), portName, operationName), pathItem);
}
}
}
}
use of io.swagger.v3.oas.models.security in project swagger-parser by swagger-api.
the class OpenAPIV3ParserTest method testValidateExternalRefsFalse.
@Test(description = "option false, does not add Original Location to messages when ref is relative/local")
public void testValidateExternalRefsFalse() {
ParseOptions options = new ParseOptions();
options.setResolve(true);
options.setValidateExternalRefs(false);
SwaggerParseResult result = new OpenAPIV3Parser().readLocation("./swos-443/root.yaml", null, options);
OpenAPI openAPI = result.getOpenAPI();
assertNotNull(openAPI);
// keeps error messages only from original spec
assertTrue(result.getMessages().contains("attribute components.schemas.InvalidSchema.invalid is unexpected"));
assertTrue(result.getMessages().contains("An exception was thrown while trying to deserialize the contents of ./ref.yaml into type class io.swagger.v3.oas.models.callbacks.Callback"));
}
use of io.swagger.v3.oas.models.security in project swagger-core by swagger-api.
the class AnnotationsUtilsHeadersTest method extensionsTest.
@Test(dataProvider = "expectedData")
public void extensionsTest(String methodName, Optional<Map<String, io.swagger.v3.oas.models.headers.Header>> expected) throws NoSuchMethodException {
final Method method = getClass().getDeclaredMethod(methodName);
final Header[] headers = Arrays.stream(method.getAnnotation(Operation.class).responses()).flatMap(response -> Arrays.stream(response.headers())).toArray(Header[]::new);
final Optional<Map<String, io.swagger.v3.oas.models.headers.Header>> optionalMap = AnnotationsUtils.getHeaders(headers, null);
Assert.assertEquals(optionalMap, expected);
}
use of io.swagger.v3.oas.models.security 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;
}
Aggregations