Search in sources :

Example 26 with Operation

use of org.wso2.carbon.apimgt.common.analytics.publishers.dto.Operation in project carbon-apimgt by wso2.

the class RegistryPersistenceImpl method addAPIRevision.

@Override
public String addAPIRevision(Organization org, String apiUUID, int revisionId) throws APIPersistenceException {
    String revisionUUID;
    boolean transactionCommitted = false;
    Registry registry = null;
    boolean tenantFlowStarted = false;
    try {
        RegistryHolder holder = getRegistry(org.getName());
        registry = holder.getRegistry();
        tenantFlowStarted = holder.isTenantFlowStarted();
        registry.beginTransaction();
        GenericArtifactManager artifactManager = RegistryPersistenceUtil.getArtifactManager(registry, APIConstants.API_KEY);
        GenericArtifact apiArtifact = artifactManager.getGenericArtifact(apiUUID);
        if (apiArtifact != null) {
            API api = RegistryPersistenceUtil.getApiForPublishing(registry, apiArtifact);
            APIIdentifier apiId = api.getId();
            String apiPath = RegistryPersistenceUtil.getAPIPath(apiId);
            int prependIndex = apiPath.lastIndexOf("/api");
            String apiSourcePath = apiPath.substring(0, prependIndex);
            String revisionTargetPath = RegistryPersistenceUtil.getRevisionPath(apiId.getUUID(), revisionId);
            if (registry.resourceExists(revisionTargetPath)) {
                throw new APIManagementException("API revision already exists with id: " + revisionId, ExceptionCodes.from(ExceptionCodes.EXISTING_API_REVISION_FOUND, String.valueOf(revisionId)));
            }
            registry.copy(apiSourcePath, revisionTargetPath);
            Resource apiRevisionArtifact = registry.get(revisionTargetPath + "api");
            registry.commitTransaction();
            transactionCommitted = true;
            if (log.isDebugEnabled()) {
                String logMessage = "Revision for API Name: " + apiId.getApiName() + ", API Version " + apiId.getVersion() + " created";
                log.debug(logMessage);
            }
            revisionUUID = apiRevisionArtifact.getUUID();
        } else {
            String msg = "Failed to get API. API artifact corresponding to artifactId " + apiUUID + " does not exist";
            throw new APIMgtResourceNotFoundException(msg);
        }
    } catch (RegistryException e) {
        try {
            registry.rollbackTransaction();
        } catch (RegistryException re) {
            // Throwing an error here would mask the original exception
            log.error("Error while rolling back the transaction for API Revision create for API: " + apiUUID, re);
        }
        throw new APIPersistenceException("Error while performing registry transaction operation", e);
    } catch (APIManagementException e) {
        throw new APIPersistenceException("Error while creating API Revision", e);
    } finally {
        try {
            if (tenantFlowStarted) {
                RegistryPersistenceUtil.endTenantFlow();
            }
            if (!transactionCommitted) {
                registry.rollbackTransaction();
            }
        } catch (RegistryException ex) {
            throw new APIPersistenceException("Error while rolling back the transaction for API Revision create for API: " + apiUUID, ex);
        }
    }
    return revisionUUID;
}
Also used : GenericArtifact(org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact) APIPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException) GenericArtifactManager(org.wso2.carbon.governance.api.generic.GenericArtifactManager) Resource(org.wso2.carbon.registry.core.Resource) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) Registry(org.wso2.carbon.registry.core.Registry) APIMgtResourceNotFoundException(org.wso2.carbon.apimgt.api.APIMgtResourceNotFoundException) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) DevPortalAPI(org.wso2.carbon.apimgt.persistence.dto.DevPortalAPI) PublisherAPI(org.wso2.carbon.apimgt.persistence.dto.PublisherAPI) API(org.wso2.carbon.apimgt.api.model.API) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier)

Example 27 with Operation

use of org.wso2.carbon.apimgt.common.analytics.publishers.dto.Operation in project carbon-apimgt by wso2.

the class GraphQLSchemaDefinition method extractGraphQLOperationList.

/**
 * Extract GraphQL Operations from given schema.
 *
 * @param typeRegistry graphQL Schema Type Registry
 * @param type operation type string
 * @return the arrayList of APIOperationsDTO
 */
public List<URITemplate> extractGraphQLOperationList(TypeDefinitionRegistry typeRegistry, String type) {
    List<URITemplate> operationArray = new ArrayList<>();
    Map<java.lang.String, TypeDefinition> operationList = typeRegistry.types();
    for (Map.Entry<String, TypeDefinition> entry : operationList.entrySet()) {
        Optional<SchemaDefinition> schemaDefinition = typeRegistry.schemaDefinition();
        if (schemaDefinition.isPresent()) {
            List<OperationTypeDefinition> operationTypeList = schemaDefinition.get().getOperationTypeDefinitions();
            for (OperationTypeDefinition operationTypeDefinition : operationTypeList) {
                if (entry.getValue().getName().equalsIgnoreCase(operationTypeDefinition.getTypeName().getName())) {
                    if (type == null) {
                        addOperations(entry, operationTypeDefinition.getName().toUpperCase(), operationArray);
                    } else if (type.equals(operationTypeDefinition.getName().toUpperCase())) {
                        addOperations(entry, operationTypeDefinition.getName().toUpperCase(), operationArray);
                    }
                }
            }
        } else {
            if (entry.getValue().getName().equalsIgnoreCase(APIConstants.GRAPHQL_QUERY) || entry.getValue().getName().equalsIgnoreCase(APIConstants.GRAPHQL_MUTATION) || entry.getValue().getName().equalsIgnoreCase(APIConstants.GRAPHQL_SUBSCRIPTION)) {
                if (type == null) {
                    addOperations(entry, entry.getKey(), operationArray);
                } else if (type.equals(entry.getValue().getName().toUpperCase())) {
                    addOperations(entry, entry.getKey(), operationArray);
                }
            }
        }
    }
    return operationArray;
}
Also used : SchemaDefinition(graphql.language.SchemaDefinition) URITemplate(org.wso2.carbon.apimgt.api.model.URITemplate) OperationTypeDefinition(graphql.language.OperationTypeDefinition) OperationTypeDefinition(graphql.language.OperationTypeDefinition) ObjectTypeDefinition(graphql.language.ObjectTypeDefinition) TypeDefinition(graphql.language.TypeDefinition)

Example 28 with Operation

use of org.wso2.carbon.apimgt.common.analytics.publishers.dto.Operation in project carbon-apimgt by wso2.

the class OAS2Parser method generateAPIDefinition.

/**
 * This method generates API definition using the given api's URI templates and the swagger.
 * It will alter the provided swagger definition based on the URI templates. For example: if there is a new
 * URI template which is not included in the swagger, it will be added to the swagger as a basic resource. Any
 * additional resources inside the swagger will be removed from the swagger. Changes to scopes, throtting policies,
 * on the resource will be updated on the swagger
 *
 * @param swaggerData api
 * @param swaggerObj  swagger
 * @return API definition in string format
 * @throws APIManagementException if error occurred when generating API Definition
 */
private String generateAPIDefinition(SwaggerData swaggerData, Swagger swaggerObj) throws APIManagementException {
    // Generates below model using the API's URI template
    // path -> [verb1 -> template1, verb2 -> template2, ..]
    Map<String, Map<String, SwaggerData.Resource>> resourceMap = getResourceMap(swaggerData);
    Iterator<Map.Entry<String, Path>> itr = swaggerObj.getPaths().entrySet().iterator();
    while (itr.hasNext()) {
        Map.Entry<String, Path> pathEntry = itr.next();
        String pathName = pathEntry.getKey();
        Path path = pathEntry.getValue();
        Map<String, SwaggerData.Resource> resourcesForPath = resourceMap.get(pathName);
        if (resourcesForPath == null) {
            // remove paths that are not in URI Templates
            itr.remove();
        } else {
            // If path is available in the URI template, then check for operations(verbs)
            for (Map.Entry<HttpMethod, Operation> operationEntry : path.getOperationMap().entrySet()) {
                HttpMethod httpMethod = operationEntry.getKey();
                Operation operation = operationEntry.getValue();
                SwaggerData.Resource resource = resourcesForPath.get(httpMethod.toString().toUpperCase());
                if (resource == null) {
                    // if particular operation is not available in URI templates, then remove it from swagger
                    path.set(httpMethod.toString().toLowerCase(), null);
                } else {
                    // if operation is available in URI templates, update swagger operation
                    // with auth type, scope etc
                    updateOperationManagedInfo(resource, operation);
                }
            }
            // if there are any verbs (operations) not defined in swagger then add them
            for (Map.Entry<String, SwaggerData.Resource> resourcesForPathEntry : resourcesForPath.entrySet()) {
                String verb = resourcesForPathEntry.getKey();
                SwaggerData.Resource resource = resourcesForPathEntry.getValue();
                HttpMethod method = HttpMethod.valueOf(verb.toUpperCase());
                Operation operation = path.getOperationMap().get(method);
                if (operation == null) {
                    operation = createOperation(resource);
                    path.set(resource.getVerb().toLowerCase(), operation);
                }
            }
        }
    }
    // add to swagger if there are any new templates
    for (Map.Entry<String, Map<String, SwaggerData.Resource>> resourceMapEntry : resourceMap.entrySet()) {
        String path = resourceMapEntry.getKey();
        Map<String, SwaggerData.Resource> verbMap = resourceMapEntry.getValue();
        if (swaggerObj.getPath(path) == null) {
            for (Map.Entry<String, SwaggerData.Resource> verbMapEntry : verbMap.entrySet()) {
                SwaggerData.Resource resource = verbMapEntry.getValue();
                addOrUpdatePathToSwagger(swaggerObj, resource);
            }
        }
    }
    updateSwaggerSecurityDefinition(swaggerObj, swaggerData, "https://test.com");
    updateLegacyScopesFromSwagger(swaggerObj, swaggerData);
    if (StringUtils.isEmpty(swaggerObj.getInfo().getTitle())) {
        swaggerObj.getInfo().setTitle(swaggerData.getTitle());
    }
    if (StringUtils.isEmpty(swaggerObj.getInfo().getVersion())) {
        swaggerObj.getInfo().setVersion(swaggerData.getVersion());
    }
    preserveResourcePathOrderFromAPI(swaggerData, swaggerObj);
    return getSwaggerJsonString(swaggerObj);
}
Also used : RefPath(io.swagger.models.RefPath) Path(io.swagger.models.Path) SwaggerData(org.wso2.carbon.apimgt.api.model.SwaggerData) Operation(io.swagger.models.Operation) Map(java.util.Map) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) HttpMethod(io.swagger.models.HttpMethod)

Example 29 with Operation

use of org.wso2.carbon.apimgt.common.analytics.publishers.dto.Operation in project carbon-apimgt by wso2.

the class OAS3Parser method modifyGraphQLSwagger.

/**
 * Construct openAPI definition for graphQL. Add get and post operations
 *
 * @param openAPI OpenAPI
 * @return modified openAPI for GraphQL
 */
private void modifyGraphQLSwagger(OpenAPI openAPI) {
    SwaggerData.Resource resource = new SwaggerData.Resource();
    resource.setAuthType(APIConstants.AUTH_APPLICATION_OR_USER_LEVEL_TOKEN);
    resource.setPolicy(APIConstants.DEFAULT_SUB_POLICY_UNLIMITED);
    resource.setPath("/");
    resource.setVerb(APIConstants.HTTP_POST);
    Operation postOperation = createOperation(resource);
    // post operation
    RequestBody requestBody = new RequestBody();
    requestBody.setDescription("Query or mutation to be passed to graphQL API");
    requestBody.setRequired(true);
    JSONObject typeOfPayload = new JSONObject();
    JSONObject payload = new JSONObject();
    typeOfPayload.put(APIConstants.TYPE, APIConstants.STRING);
    payload.put(APIConstants.OperationParameter.PAYLOAD_PARAM_NAME, typeOfPayload);
    Schema postSchema = new Schema();
    postSchema.setType(APIConstants.OBJECT);
    postSchema.setProperties(payload);
    MediaType mediaType = new MediaType();
    mediaType.setSchema(postSchema);
    Content content = new Content();
    content.addMediaType(APPLICATION_JSON_MEDIA_TYPE, mediaType);
    requestBody.setContent(content);
    postOperation.setRequestBody(requestBody);
    // add post and get operations to path /*
    PathItem pathItem = new PathItem();
    pathItem.setPost(postOperation);
    Paths paths = new Paths();
    paths.put("/", pathItem);
    openAPI.setPaths(paths);
}
Also used : PathItem(io.swagger.v3.oas.models.PathItem) JSONObject(org.json.simple.JSONObject) SwaggerData(org.wso2.carbon.apimgt.api.model.SwaggerData) Content(io.swagger.v3.oas.models.media.Content) Schema(io.swagger.v3.oas.models.media.Schema) MediaType(io.swagger.v3.oas.models.media.MediaType) Operation(io.swagger.v3.oas.models.Operation) Paths(io.swagger.v3.oas.models.Paths) RequestBody(io.swagger.v3.oas.models.parameters.RequestBody)

Example 30 with Operation

use of org.wso2.carbon.apimgt.common.analytics.publishers.dto.Operation in project carbon-apimgt by wso2.

the class OAS3Parser method removeExamplesFromOpenAPI.

/**
 * Remove x-examples from all the paths from the OpenAPI definition.
 *
 * @param apiDefinition OpenAPI definition as String
 */
public static String removeExamplesFromOpenAPI(String apiDefinition) throws APIManagementException {
    try {
        OpenAPIV3Parser openAPIV3Parser = new OpenAPIV3Parser();
        SwaggerParseResult parseAttemptForV3 = openAPIV3Parser.readContents(apiDefinition, null, null);
        if (CollectionUtils.isNotEmpty(parseAttemptForV3.getMessages())) {
            log.debug("Errors found when parsing OAS definition");
        }
        OpenAPI openAPI = parseAttemptForV3.getOpenAPI();
        for (Map.Entry<String, PathItem> entry : openAPI.getPaths().entrySet()) {
            String path = entry.getKey();
            List<Operation> operations = openAPI.getPaths().get(path).readOperations();
            for (Operation operation : operations) {
                if (operation.getExtensions() != null && operation.getExtensions().keySet().contains(APIConstants.SWAGGER_X_EXAMPLES)) {
                    operation.getExtensions().remove(APIConstants.SWAGGER_X_EXAMPLES);
                }
            }
        }
        return Yaml.pretty().writeValueAsString(openAPI);
    } catch (JsonProcessingException e) {
        throw new APIManagementException("Error while removing examples from OpenAPI definition", e, ExceptionCodes.ERROR_REMOVING_EXAMPLES);
    }
}
Also used : PathItem(io.swagger.v3.oas.models.PathItem) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) SwaggerParseResult(io.swagger.v3.parser.core.models.SwaggerParseResult) Operation(io.swagger.v3.oas.models.Operation) OpenAPIV3Parser(io.swagger.v3.parser.OpenAPIV3Parser) OpenAPI(io.swagger.v3.oas.models.OpenAPI) Map(java.util.Map) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException)

Aggregations

APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)79 HashMap (java.util.HashMap)55 ArrayList (java.util.ArrayList)43 APIProvider (org.wso2.carbon.apimgt.api.APIProvider)42 Test (org.testng.annotations.Test)34 URITemplate (org.wso2.carbon.apimgt.api.model.URITemplate)29 HttpResponse (org.wso2.carbon.automation.test.utils.http.client.HttpResponse)29 Map (java.util.Map)28 IOException (java.io.IOException)23 API (org.wso2.carbon.apimgt.api.model.API)22 List (java.util.List)20 JSONObject (org.json.simple.JSONObject)20 RegistryException (org.wso2.carbon.registry.core.exceptions.RegistryException)20 APIMgtResourceNotFoundException (org.wso2.carbon.apimgt.api.APIMgtResourceNotFoundException)19 LinkedHashMap (java.util.LinkedHashMap)18 FaultGatewaysException (org.wso2.carbon.apimgt.api.FaultGatewaysException)18 OperationPolicyData (org.wso2.carbon.apimgt.api.model.OperationPolicyData)18 APIInfo (org.wso2.carbon.apimgt.api.model.APIInfo)17 Connection (java.sql.Connection)16 PreparedStatement (java.sql.PreparedStatement)16