use of io.swagger.parser.SwaggerParser in project carbon-apimgt by wso2.
the class APIDefinitionFromSwagger20 method getScopeOfResourcePath.
@Override
public String getScopeOfResourcePath(String resourceConfigsJSON, Request request, ServiceMethodInfo serviceMethodInfo) throws APIManagementException {
SwaggerParser swaggerParser = new SwaggerParser();
Swagger swagger = swaggerParser.parse(resourceConfigsJSON);
String basepath = swagger.getBasePath();
String verb = (String) request.getProperty(APIMgtConstants.HTTP_METHOD);
// TODO change to this if msf4j2.3.0-m2 or higher
// Method resourceMethod = (Method) request.getProperty("method");
Method resourceMethod = serviceMethodInfo.getMethod();
if (resourceMethod == null || verb == null) {
String message = "Could not read required properties from HTTP Request. HTTP_METHOD=" + verb + " resourceTemplate=" + resourceMethod;
log.error(message);
throw new APIManagementException(message, ExceptionCodes.SWAGGER_URL_MALFORMED);
}
String apiPrefix = resourceMethod.getDeclaringClass().getAnnotation(javax.ws.rs.ApplicationPath.class).value();
String pathTemplate = "";
if (resourceMethod.getAnnotation(javax.ws.rs.Path.class) != null) {
pathTemplate = resourceMethod.getAnnotation(javax.ws.rs.Path.class).value();
}
String nameSpace = getNamespaceFromBasePath(basepath);
if (basepath.contains(APIMgtConstants.APPType.PUBLISHER)) {
nameSpace = APIMgtConstants.NAMESPACE_PUBLISHER_API;
} else if (basepath.contains(APIMgtConstants.APPType.STORE)) {
nameSpace = APIMgtConstants.NAMESPACE_STORE_API;
} else if (basepath.contains(APIMgtConstants.APPType.ADMIN)) {
nameSpace = APIMgtConstants.NAMESPACE_ADMIN_API;
} else if (basepath.contains(APIMgtConstants.APPType.ANALYTICS)) {
nameSpace = APIMgtConstants.NAMESPACE_ANALYTICS_API;
}
// if namespace is not available in local cache add it.
if (nameSpace != null && !localConfigMap.containsKey(nameSpace)) {
localConfigMap.put(nameSpace, new ConcurrentHashMap<>());
}
if (nameSpace != null && localConfigMap.containsKey(nameSpace) && localConfigMap.get(nameSpace).isEmpty()) {
populateConfigMapForScopes(swagger, nameSpace);
}
String resourceConfig = verb + "_" + apiPrefix + pathTemplate;
if (localConfigMap.get(nameSpace).containsKey(resourceConfig)) {
return localConfigMap.get(nameSpace).get(resourceConfig).toString();
}
return null;
}
use of io.swagger.parser.SwaggerParser in project carbon-apimgt by wso2.
the class APIDefinitionFromSwagger20 method getScopesFromSecurityDefinition.
@Override
public Map<String, String> getScopesFromSecurityDefinition(String resourceConfigJSON) throws APIManagementException {
SwaggerParser swaggerParser = new SwaggerParser();
Swagger swagger = swaggerParser.parse(resourceConfigJSON);
Map<String, String> scopes = new HashMap<>();
Map<String, SecuritySchemeDefinition> securityDefinitions = swagger.getSecurityDefinitions();
if (securityDefinitions != null) {
for (Map.Entry<String, SecuritySchemeDefinition> securitySchemeDefinitionEntry : securityDefinitions.entrySet()) {
if (securitySchemeDefinitionEntry.getValue() instanceof OAuth2Definition) {
OAuth2Definition securityDefinition = (OAuth2Definition) securitySchemeDefinitionEntry.getValue();
if (securityDefinition != null) {
scopes.putAll(securityDefinition.getScopes());
}
}
}
}
return scopes;
}
use of io.swagger.parser.SwaggerParser in project azure-iot-sdk-java by Azure.
the class MainApiVerticle method start.
@SuppressWarnings("deprecation")
@Override
public void start(Future<Void> startFuture) throws Exception {
Json.mapper.registerModule(new JavaTimeModule());
FileSystem vertxFileSystem = vertx.fileSystem();
vertxFileSystem.readFile("swagger.json", readFile -> {
if (readFile.succeeded()) {
Swagger swagger = new SwaggerParser().parse(readFile.result().toString(StandardCharsets.UTF_8));
Router swaggerRouter = SwaggerRouter.swaggerRouter(router, swagger, vertx.eventBus(), new OperationIdServiceIdResolver(), t -> new DeliveryOptions().setSendTimeout(90000));
deployVerticles(startFuture);
vertx.createHttpServer().requestHandler(swaggerRouter::accept).listen(8080);
startFuture.complete();
} else {
startFuture.fail(readFile.cause());
}
});
}
use of io.swagger.parser.SwaggerParser in project carbon-apimgt by wso2.
the class OAS2Parser method getOASDefinitionWithTierContentAwareProperty.
@Override
public String getOASDefinitionWithTierContentAwareProperty(String oasDefinition, List<String> contentAwareTiersList, String apiLevelTier) throws APIManagementException {
SwaggerParser parser = new SwaggerParser();
SwaggerDeserializationResult parseAttemptForV2 = parser.readWithInfo(oasDefinition);
Swagger swagger = parseAttemptForV2.getSwagger();
// check if API Level tier is content aware. if so, we set a extension as a global property
if (contentAwareTiersList.contains(apiLevelTier)) {
swagger.setVendorExtension(APIConstants.SWAGGER_X_THROTTLING_BANDWIDTH, true);
// no need to check resource levels since both cannot exist at the same time.
log.debug("API Level policy is content aware..");
return Json.pretty(swagger);
}
// if api level tier exists, skip checking for resource level tiers since both cannot exist at the same time.
if (apiLevelTier != null) {
log.debug("API Level policy is not content aware..");
return oasDefinition;
} else {
log.debug("API Level policy does not exist. Checking for resource level");
for (Map.Entry<String, Path> entry : swagger.getPaths().entrySet()) {
String path = entry.getKey();
List<Operation> operations = swagger.getPaths().get(path).getOperations();
for (Operation op : operations) {
if (contentAwareTiersList.contains(op.getVendorExtensions().get(APIConstants.SWAGGER_X_THROTTLING_TIER))) {
if (log.isDebugEnabled()) {
log.debug("API resource Level policy is content aware for operation " + op.getOperationId());
}
op.setVendorExtension(APIConstants.SWAGGER_X_THROTTLING_BANDWIDTH, true);
}
}
}
return Json.pretty(swagger);
}
}
use of io.swagger.parser.SwaggerParser in project carbon-apimgt by wso2.
the class OASParserUtil method extractAndValidateOpenAPIArchive.
/**
* Extract the archive file and validates the openAPI definition
*
* @param inputStream file as input stream
* @param returnContent whether to return the content of the definition in the response DTO
* @return APIDefinitionValidationResponse
* @throws APIManagementException if error occurred while parsing definition
*/
public static APIDefinitionValidationResponse extractAndValidateOpenAPIArchive(InputStream inputStream, boolean returnContent) throws APIManagementException {
String path = System.getProperty(APIConstants.JAVA_IO_TMPDIR) + File.separator + APIConstants.OPENAPI_ARCHIVES_TEMP_FOLDER + File.separator + UUID.randomUUID().toString();
String archivePath = path + File.separator + APIConstants.OPENAPI_ARCHIVE_ZIP_FILE;
String extractedLocation = APIFileUtil.extractUploadedArchive(inputStream, APIConstants.OPENAPI_EXTRACTED_DIRECTORY, archivePath, path);
File[] listOfFiles = new File(extractedLocation).listFiles();
File archiveDirectory = null;
if (listOfFiles != null) {
if (listOfFiles.length > 1) {
throw new APIManagementException("Swagger Definitions should be placed under one root folder.");
}
for (File file : listOfFiles) {
if (file.isDirectory()) {
archiveDirectory = file.getAbsoluteFile();
break;
}
}
}
// If it is a single swagger file without remote references it can be imported directly, without zipping.
if (archiveDirectory == null) {
throw new APIManagementException("Could not find an archive in the given ZIP file.");
}
File masterSwagger = checkMasterSwagger(archiveDirectory);
String content;
try {
InputStream masterInputStream = new FileInputStream(masterSwagger);
content = IOUtils.toString(masterInputStream, APIConstants.DigestAuthConstants.CHARSET);
} catch (IOException e) {
throw new APIManagementException("Error reading master swagger file" + e);
}
String openAPIContent = "";
SwaggerVersion version;
version = getSwaggerVersion(content);
String filePath = masterSwagger.getAbsolutePath();
if (SwaggerVersion.OPEN_API.equals(version)) {
OpenAPIV3Parser openAPIV3Parser = new OpenAPIV3Parser();
ParseOptions options = new ParseOptions();
options.setResolve(true);
OpenAPI openAPI = openAPIV3Parser.read(filePath, null, options);
openAPIContent = Json.pretty(openAPI);
} else if (SwaggerVersion.SWAGGER.equals(version)) {
SwaggerParser parser = new SwaggerParser();
Swagger swagger = parser.read(filePath, null, true);
try {
openAPIContent = Yaml.pretty().writeValueAsString(swagger);
} catch (IOException e) {
throw new APIManagementException("Error in converting swagger to openAPI content. " + e);
}
}
APIDefinitionValidationResponse apiDefinitionValidationResponse;
apiDefinitionValidationResponse = OASParserUtil.validateAPIDefinition(openAPIContent, returnContent);
return apiDefinitionValidationResponse;
}
Aggregations