Search in sources :

Example 21 with Operation

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

the class MeResourceManager method updateWithPATCH.

/**
 * Update the user resource by sequence of operations.
 *
 * @param existingId
 * @param scimObjectString
 * @param userManager
 * @param attributes
 * @param excludeAttributes
 * @return
 */
public SCIMResponse updateWithPATCH(String existingId, String scimObjectString, UserManager userManager, String attributes, String excludeAttributes) {
    try {
        if (userManager == null) {
            String error = "Provided user manager handler is null.";
            throw new InternalErrorException(error);
        }
        // obtain the json decoder.
        JSONDecoder decoder = getDecoder();
        // decode the SCIM User object, encoded in the submitted payload.
        List<PatchOperation> opList = decoder.decodeRequest(scimObjectString);
        SCIMResourceTypeSchema schema = SCIMResourceSchemaManager.getInstance().getUserResourceSchema();
        // get the user from the user core
        User oldUser = userManager.getMe(existingId, ResourceManagerUtil.getAllAttributeURIs(schema));
        if (oldUser == null) {
            throw new NotFoundException("No associated user exits in the user store.");
        }
        // make a copy of the original user
        User copyOfOldUser = (User) CopyUtil.deepCopy(oldUser);
        // make another copy of original user.
        // this will be used to restore to the original condition if failure occurs.
        User originalUser = (User) CopyUtil.deepCopy(copyOfOldUser);
        User newUser = null;
        for (PatchOperation operation : opList) {
            if (operation.getOperation().equals(SCIMConstants.OperationalConstants.ADD)) {
                if (newUser == null) {
                    newUser = (User) PatchOperationUtil.doPatchAdd(operation, getDecoder(), oldUser, copyOfOldUser, schema);
                    copyOfOldUser = (User) CopyUtil.deepCopy(newUser);
                } else {
                    newUser = (User) PatchOperationUtil.doPatchAdd(operation, getDecoder(), newUser, copyOfOldUser, schema);
                    copyOfOldUser = (User) CopyUtil.deepCopy(newUser);
                }
            } else if (operation.getOperation().equals(SCIMConstants.OperationalConstants.REMOVE)) {
                if (newUser == null) {
                    newUser = (User) PatchOperationUtil.doPatchRemove(operation, oldUser, copyOfOldUser, schema);
                    copyOfOldUser = (User) CopyUtil.deepCopy(newUser);
                } else {
                    newUser = (User) PatchOperationUtil.doPatchRemove(operation, newUser, copyOfOldUser, schema);
                    copyOfOldUser = (User) CopyUtil.deepCopy(newUser);
                }
            } else if (operation.getOperation().equals(SCIMConstants.OperationalConstants.REPLACE)) {
                if (newUser == null) {
                    newUser = (User) PatchOperationUtil.doPatchReplace(operation, getDecoder(), oldUser, copyOfOldUser, schema);
                    copyOfOldUser = (User) CopyUtil.deepCopy(newUser);
                } else {
                    newUser = (User) PatchOperationUtil.doPatchReplace(operation, getDecoder(), newUser, copyOfOldUser, schema);
                    copyOfOldUser = (User) CopyUtil.deepCopy(newUser);
                }
            } else {
                throw new BadRequestException("Unknown operation.", ResponseCodeConstants.INVALID_SYNTAX);
            }
        }
        // get the URIs of required attributes which must be given a value
        Map<String, Boolean> requiredAttributes = ResourceManagerUtil.getOnlyRequiredAttributesURIs((SCIMResourceTypeSchema) CopyUtil.deepCopy(schema), attributes, excludeAttributes);
        User validatedUser = (User) ServerSideValidator.validateUpdatedSCIMObject(originalUser, newUser, schema);
        newUser = userManager.updateMe(validatedUser, requiredAttributes);
        // encode the newly created SCIM user object and add id attribute to Location header.
        String encodedUser;
        Map<String, String> httpHeaders = new HashMap<String, String>();
        if (newUser != null) {
            // create a deep copy of the user object since we are going to change it.
            User copiedUser = (User) CopyUtil.deepCopy(newUser);
            // need to remove password before returning
            ServerSideValidator.validateReturnedAttributes(copiedUser, attributes, excludeAttributes);
            encodedUser = getEncoder().encodeSCIMObject(copiedUser);
            // add location header
            httpHeaders.put(SCIMConstants.LOCATION_HEADER, getResourceEndpointURL(SCIMConstants.USER_ENDPOINT) + "/" + newUser.getId());
            httpHeaders.put(SCIMConstants.CONTENT_TYPE_HEADER, SCIMConstants.APPLICATION_JSON);
        } else {
            String error = "Updated User resource is null.";
            throw new CharonException(error);
        }
        // put the URI of the User object in the response header parameter.
        return new SCIMResponse(ResponseCodeConstants.CODE_OK, encodedUser, httpHeaders);
    } catch (NotFoundException e) {
        return encodeSCIMException(e);
    } catch (BadRequestException e) {
        return encodeSCIMException(e);
    } catch (NotImplementedException e) {
        return encodeSCIMException(e);
    } catch (CharonException e) {
        return encodeSCIMException(e);
    } catch (InternalErrorException e) {
        return encodeSCIMException(e);
    } catch (RuntimeException e) {
        CharonException e1 = new CharonException("Error in performing the patch operation on user resource.", e);
        return encodeSCIMException(e1);
    }
}
Also used : User(org.wso2.charon3.core.objects.User) HashMap(java.util.HashMap) NotImplementedException(org.wso2.charon3.core.exceptions.NotImplementedException) NotFoundException(org.wso2.charon3.core.exceptions.NotFoundException) InternalErrorException(org.wso2.charon3.core.exceptions.InternalErrorException) JSONDecoder(org.wso2.charon3.core.encoder.JSONDecoder) PatchOperation(org.wso2.charon3.core.utils.codeutils.PatchOperation) BadRequestException(org.wso2.charon3.core.exceptions.BadRequestException) SCIMResourceTypeSchema(org.wso2.charon3.core.schema.SCIMResourceTypeSchema) CharonException(org.wso2.charon3.core.exceptions.CharonException) SCIMResponse(org.wso2.charon3.core.protocol.SCIMResponse)

Example 22 with Operation

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

the class AbstractAPIManager method populateDevPortalAPIInformation.

protected void populateDevPortalAPIInformation(String uuid, String organization, API api) throws APIManagementException, OASPersistenceException, ParseException {
    Organization org = new Organization(organization);
    // UUID
    if (api.getUuid() == null) {
        api.setUuid(uuid);
    }
    api.setOrganization(organization);
    // environment
    String environmentString = null;
    if (api.getEnvironments() != null) {
        environmentString = String.join(",", api.getEnvironments());
    }
    api.setEnvironments(APIUtil.extractEnvironmentsForAPI(environmentString, organization));
    // workflow status
    APIIdentifier apiId = api.getId();
    String currentApiUuid = uuid;
    if (api.isRevision() && api.getRevisionedApiId() != null) {
        currentApiUuid = api.getRevisionedApiId();
    }
    // TODO try to use a single query to get info from db
    // Ratings
    int internalId = apiMgtDAO.getAPIID(currentApiUuid);
    api.setRating(APIUtil.getAverageRating(internalId));
    apiId.setId(internalId);
    // api level tier
    String apiLevelTier = apiMgtDAO.getAPILevelTier(internalId);
    api.setApiLevelPolicy(apiLevelTier);
    // available tier
    String tiers = null;
    Set<Tier> tiersSet = api.getAvailableTiers();
    Set<String> tierNameSet = new HashSet<String>();
    for (Tier t : tiersSet) {
        tierNameSet.add(t.getName());
    }
    if (api.getAvailableTiers() != null) {
        tiers = String.join("||", tierNameSet);
    }
    Map<String, Tier> definedTiers = APIUtil.getTiers(APIUtil.getInternalOrganizationId(organization));
    Set<Tier> availableTier = APIUtil.getAvailableTiers(definedTiers, tiers, api.getId().getApiName());
    api.setAvailableTiers(availableTier);
    // Scopes
    Map<String, Scope> scopeToKeyMapping = APIUtil.getAPIScopes(currentApiUuid, organization);
    api.setScopes(new LinkedHashSet<>(scopeToKeyMapping.values()));
    // templates
    String resourceConfigsString = null;
    if (api.getSwaggerDefinition() != null) {
        resourceConfigsString = api.getSwaggerDefinition();
    } else {
        resourceConfigsString = apiPersistenceInstance.getOASDefinition(org, uuid);
    }
    api.setSwaggerDefinition(resourceConfigsString);
    if (api.getType() != null && APIConstants.APITransportType.GRAPHQL.toString().equals(api.getType())) {
        api.setGraphQLSchema(getGraphqlSchemaDefinition(uuid, organization));
    }
    JSONParser jsonParser = new JSONParser();
    JSONObject paths = null;
    if (resourceConfigsString != null) {
        JSONObject resourceConfigsJSON = (JSONObject) jsonParser.parse(resourceConfigsString);
        paths = (JSONObject) resourceConfigsJSON.get(APIConstants.SWAGGER_PATHS);
    }
    Set<URITemplate> uriTemplates = apiMgtDAO.getURITemplatesOfAPI(api.getUuid());
    for (URITemplate uriTemplate : uriTemplates) {
        String uTemplate = uriTemplate.getUriTemplate();
        String method = uriTemplate.getHTTPVerb();
        List<Scope> oldTemplateScopes = uriTemplate.retrieveAllScopes();
        List<Scope> newTemplateScopes = new ArrayList<>();
        if (!oldTemplateScopes.isEmpty()) {
            for (Scope templateScope : oldTemplateScopes) {
                Scope scope = scopeToKeyMapping.get(templateScope.getKey());
                newTemplateScopes.add(scope);
            }
        }
        uriTemplate.addAllScopes(newTemplateScopes);
        uriTemplate.setResourceURI(api.getUrl());
        uriTemplate.setResourceSandboxURI(api.getSandboxUrl());
        // AWS Lambda: set arn & timeout to URI template
        if (paths != null) {
            JSONObject path = (JSONObject) paths.get(uTemplate);
            if (path != null) {
                JSONObject operation = (JSONObject) path.get(method.toLowerCase());
                if (operation != null) {
                    if (operation.containsKey(APIConstants.SWAGGER_X_AMZN_RESOURCE_NAME)) {
                        uriTemplate.setAmznResourceName((String) operation.get(APIConstants.SWAGGER_X_AMZN_RESOURCE_NAME));
                    }
                    if (operation.containsKey(APIConstants.SWAGGER_X_AMZN_RESOURCE_TIMEOUT)) {
                        uriTemplate.setAmznResourceTimeout(((Long) operation.get(APIConstants.SWAGGER_X_AMZN_RESOURCE_TIMEOUT)).intValue());
                    }
                }
            }
        }
    }
    if (APIConstants.IMPLEMENTATION_TYPE_INLINE.equalsIgnoreCase(api.getImplementation())) {
        for (URITemplate template : uriTemplates) {
            template.setMediationScript(template.getAggregatedMediationScript());
        }
    }
    api.setUriTemplates(uriTemplates);
    // CORS . if null is returned, set default config from the configuration
    if (api.getCorsConfiguration() == null) {
        api.setCorsConfiguration(APIUtil.getDefaultCorsConfiguration());
    }
    // set category
    List<APICategory> categories = api.getApiCategories();
    if (categories != null) {
        List<String> categoriesOfAPI = new ArrayList<String>();
        for (APICategory apiCategory : categories) {
            categoriesOfAPI.add(apiCategory.getName());
        }
        List<APICategory> categoryList = new ArrayList<>();
        if (!categoriesOfAPI.isEmpty()) {
            // category array retrieved from artifact has only the category name, therefore we need to fetch
            // categories
            // and fill out missing attributes before attaching the list to the api
            List<APICategory> allCategories = APIUtil.getAllAPICategoriesOfOrganization(organization);
            for (String categoryName : categoriesOfAPI) {
                for (APICategory category : allCategories) {
                    if (categoryName.equals(category.getName())) {
                        categoryList.add(category);
                        break;
                    }
                }
            }
        }
        api.setApiCategories(categoryList);
    }
}
Also used : Organization(org.wso2.carbon.apimgt.persistence.dto.Organization) Tier(org.wso2.carbon.apimgt.api.model.Tier) URITemplate(org.wso2.carbon.apimgt.api.model.URITemplate) ArrayList(java.util.ArrayList) Scope(org.wso2.carbon.apimgt.api.model.Scope) JSONObject(org.json.simple.JSONObject) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) JSONParser(org.json.simple.parser.JSONParser) APICategory(org.wso2.carbon.apimgt.api.model.APICategory) LinkedHashSet(java.util.LinkedHashSet) HashSet(java.util.HashSet)

Example 23 with Operation

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

the class RegistryPersistenceImpl method restoreAPIRevision.

@Override
public void restoreAPIRevision(Organization org, String apiUUID, String revisionUUID, int revisionId) throws APIPersistenceException {
    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);
        String lcState = ((GenericArtifactImpl) apiArtifact).getLcState();
        if (apiArtifact != null) {
            String apiPath = GovernanceUtils.getArtifactPath(registry, apiUUID);
            int prependIndex = apiPath.lastIndexOf("/api");
            String apiSourcePath = apiPath.substring(0, prependIndex);
            String revisionTargetPath = RegistryPersistenceUtil.getRevisionPath(apiUUID, revisionId);
            registry.delete(apiSourcePath);
            registry.copy(revisionTargetPath, apiSourcePath);
            Resource newAPIArtifact = registry.get(apiPath);
            newAPIArtifact.setUUID(apiUUID);
            newAPIArtifact.setProperty("registry.lifecycle.APILifeCycle.state", java.util.Arrays.asList((lcState)));
            registry.put(apiPath, newAPIArtifact);
        }
        registry.commitTransaction();
        transactionCommitted = true;
        if (log.isDebugEnabled()) {
            String logMessage = "Revision ID" + revisionId + " for API UUID: " + apiUUID + " restored";
            log.debug(logMessage);
        }
    } 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 restore for API: " + apiUUID, re);
        }
        throw new APIPersistenceException("Error while performing registry transaction operation", 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 restore for API: " + apiUUID, ex);
        }
    }
}
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) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) GenericArtifactImpl(org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifactImpl)

Example 24 with Operation

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

the class RegistryPersistenceImpl method updateAPI.

@SuppressWarnings("unchecked")
@Override
public PublisherAPI updateAPI(Organization org, PublisherAPI publisherAPI) throws APIPersistenceException {
    API api = APIMapper.INSTANCE.toApi(publisherAPI);
    boolean transactionCommitted = false;
    boolean tenantFlowStarted = false;
    Registry registry = null;
    try {
        RegistryHolder holder = getRegistry(org.getName());
        registry = holder.getRegistry();
        tenantFlowStarted = holder.isTenantFlowStarted();
        registry.beginTransaction();
        String apiArtifactId = registry.get(RegistryPersistenceUtil.getAPIPath(api.getId())).getUUID();
        GenericArtifactManager artifactManager = RegistryPersistenceUtil.getArtifactManager(registry, APIConstants.API_KEY);
        if (artifactManager == null) {
            String errorMessage = "Artifact manager is null when updating API artifact ID " + api.getId();
            log.error(errorMessage);
            throw new APIPersistenceException(errorMessage);
        }
        GenericArtifact artifact = getAPIArtifact(apiArtifactId, registry);
        boolean isSecured = Boolean.parseBoolean(artifact.getAttribute(APIConstants.API_OVERVIEW_ENDPOINT_SECURED));
        boolean isDigestSecured = Boolean.parseBoolean(artifact.getAttribute(APIConstants.API_OVERVIEW_ENDPOINT_AUTH_DIGEST));
        String userName = artifact.getAttribute(APIConstants.API_OVERVIEW_ENDPOINT_USERNAME);
        String password = artifact.getAttribute(APIConstants.API_OVERVIEW_ENDPOINT_PASSWORD);
        if (!isSecured && !isDigestSecured && userName != null) {
            api.setEndpointUTUsername(userName);
            api.setEndpointUTPassword(password);
        }
        String oldStatus = artifact.getAttribute(APIConstants.API_OVERVIEW_STATUS);
        Resource apiResource = registry.get(artifact.getPath());
        String oldAccessControlRoles = api.getAccessControlRoles();
        if (apiResource != null) {
            oldAccessControlRoles = registry.get(artifact.getPath()).getProperty(APIConstants.PUBLISHER_ROLES);
        }
        GenericArtifact updateApiArtifact = RegistryPersistenceUtil.createAPIArtifactContent(artifact, api);
        String artifactPath = GovernanceUtils.getArtifactPath(registry, updateApiArtifact.getId());
        org.wso2.carbon.registry.core.Tag[] oldTags = registry.getTags(artifactPath);
        if (oldTags != null) {
            for (org.wso2.carbon.registry.core.Tag tag : oldTags) {
                registry.removeTag(artifactPath, tag.getTagName());
            }
        }
        Set<String> tagSet = api.getTags();
        if (tagSet != null) {
            for (String tag : tagSet) {
                registry.applyTag(artifactPath, tag);
            }
        }
        artifactManager.updateGenericArtifact(updateApiArtifact);
        // write API Status to a separate property. This is done to support querying APIs using custom query (SQL)
        // to gain performance
        // String apiStatus = api.getStatus().toUpperCase();
        // saveAPIStatus(artifactPath, apiStatus);
        String[] visibleRoles = new String[0];
        String publisherAccessControlRoles = api.getAccessControlRoles();
        updateRegistryResources(registry, artifactPath, publisherAccessControlRoles, api.getAccessControl(), api.getAdditionalProperties());
        // propagate api status change and access control roles change to document artifact
        String newStatus = updateApiArtifact.getAttribute(APIConstants.API_OVERVIEW_STATUS);
        if (!StringUtils.equals(oldStatus, newStatus) || !StringUtils.equals(oldAccessControlRoles, publisherAccessControlRoles)) {
            RegistryPersistenceUtil.notifyAPIStateChangeToAssociatedDocuments(artifact, registry);
        }
        RegistryPersistenceUtil.clearResourcePermissions(artifactPath, api.getId(), ((UserRegistry) registry).getTenantId());
        String visibleRolesList = api.getVisibleRoles();
        if (visibleRolesList != null) {
            visibleRoles = visibleRolesList.split(",");
        }
        RegistryPersistenceUtil.setResourcePermissions(api.getId().getProviderName(), api.getVisibility(), visibleRoles, artifactPath, registry);
        // attaching api categories to the API
        List<APICategory> attachedApiCategories = api.getApiCategories();
        artifact.removeAttribute(APIConstants.API_CATEGORIES_CATEGORY_NAME);
        if (attachedApiCategories != null) {
            for (APICategory category : attachedApiCategories) {
                artifact.addAttribute(APIConstants.API_CATEGORIES_CATEGORY_NAME, category.getName());
            }
        }
        if (api.getSwaggerDefinition() != null) {
            String resourcePath = RegistryPersistenceUtil.getOpenAPIDefinitionFilePath(api.getId().getName(), api.getId().getVersion(), api.getId().getProviderName());
            resourcePath = resourcePath + APIConstants.API_OAS_DEFINITION_RESOURCE_NAME;
            Resource resource;
            if (!registry.resourceExists(resourcePath)) {
                resource = registry.newResource();
            } else {
                resource = registry.get(resourcePath);
            }
            resource.setContent(api.getSwaggerDefinition());
            resource.setMediaType("application/json");
            registry.put(resourcePath, resource);
            // Need to set anonymous if the visibility is public
            RegistryPersistenceUtil.clearResourcePermissions(resourcePath, api.getId(), ((UserRegistry) registry).getTenantId());
            RegistryPersistenceUtil.setResourcePermissions(api.getId().getProviderName(), api.getVisibility(), visibleRoles, resourcePath);
        }
        // doc visibility change
        String apiOrAPIProductDocPath = RegistryPersistenceDocUtil.getDocumentPath(api.getId().getProviderName(), api.getId().getApiName(), api.getId().getVersion());
        String pathToContent = apiOrAPIProductDocPath + APIConstants.INLINE_DOCUMENT_CONTENT_DIR;
        String pathToDocFile = apiOrAPIProductDocPath + APIConstants.DOCUMENT_FILE_DIR;
        if (registry.resourceExists(apiOrAPIProductDocPath)) {
            Resource resource = registry.get(apiOrAPIProductDocPath);
            if (resource instanceof org.wso2.carbon.registry.core.Collection) {
                String[] docsPaths = ((org.wso2.carbon.registry.core.Collection) resource).getChildren();
                for (String docPath : docsPaths) {
                    if (!(docPath.equalsIgnoreCase(pathToContent) || docPath.equalsIgnoreCase(pathToDocFile))) {
                        Resource docResource = registry.get(docPath);
                        GenericArtifactManager docArtifactManager = RegistryPersistenceDocUtil.getDocumentArtifactManager(registry);
                        GenericArtifact docArtifact = docArtifactManager.getGenericArtifact(docResource.getUUID());
                        Documentation doc = RegistryPersistenceDocUtil.getDocumentation(docArtifact);
                        if ((APIConstants.DOC_API_BASED_VISIBILITY).equalsIgnoreCase(doc.getVisibility().name())) {
                            String documentationPath = RegistryPersistenceDocUtil.getAPIDocPath(api.getId()) + doc.getName();
                            RegistryPersistenceUtil.setResourcePermissions(api.getId().getProviderName(), api.getVisibility(), visibleRoles, documentationPath, registry);
                            if (Documentation.DocumentSourceType.INLINE.equals(doc.getSourceType()) || Documentation.DocumentSourceType.MARKDOWN.equals(doc.getSourceType())) {
                                String contentPath = RegistryPersistenceDocUtil.getAPIDocPath(api.getId()) + APIConstants.INLINE_DOCUMENT_CONTENT_DIR + RegistryConstants.PATH_SEPARATOR + doc.getName();
                                RegistryPersistenceUtil.setResourcePermissions(api.getId().getProviderName(), api.getVisibility(), visibleRoles, contentPath, registry);
                            } else if (Documentation.DocumentSourceType.FILE.equals(doc.getSourceType()) && doc.getFilePath() != null) {
                                String filePath = RegistryPersistenceDocUtil.getDocumentationFilePath(api.getId(), doc.getFilePath().split("files" + RegistryConstants.PATH_SEPARATOR)[1]);
                                RegistryPersistenceUtil.setResourcePermissions(api.getId().getProviderName(), api.getVisibility(), visibleRoles, filePath, registry);
                            }
                        }
                    }
                }
            }
        }
        setSoapToRestSequences(publisherAPI, registry);
        registry.commitTransaction();
        transactionCommitted = true;
        return APIMapper.INSTANCE.toPublisherApi(api);
    } catch (Exception e) {
        try {
            registry.rollbackTransaction();
        } catch (RegistryException re) {
            // Throwing an error from this level will mask the original exception
            log.error("Error while rolling back the transaction for API: " + api.getId().getApiName(), re);
        }
        throw new APIPersistenceException("Error while performing registry transaction operation ", e);
    } finally {
        if (tenantFlowStarted) {
            RegistryPersistenceUtil.endTenantFlow();
        }
        try {
            if (!transactionCommitted) {
                registry.rollbackTransaction();
            }
        } catch (RegistryException ex) {
            throw new APIPersistenceException("Error occurred while rolling back the transaction. ", ex);
        }
    }
}
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) Documentation(org.wso2.carbon.apimgt.persistence.dto.Documentation) Resource(org.wso2.carbon.registry.core.Resource) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) Registry(org.wso2.carbon.registry.core.Registry) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) APIPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException) XMLStreamException(javax.xml.stream.XMLStreamException) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) PersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.PersistenceException) GraphQLPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.GraphQLPersistenceException) PersistenceUtil.handleException(org.wso2.carbon.apimgt.persistence.utils.PersistenceUtil.handleException) IOException(java.io.IOException) MediationPolicyPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.MediationPolicyPersistenceException) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) ThumbnailPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.ThumbnailPersistenceException) IndexerException(org.wso2.carbon.registry.indexing.indexer.IndexerException) WSDLPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.WSDLPersistenceException) OASPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.OASPersistenceException) AsyncSpecPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.AsyncSpecPersistenceException) UserStoreException(org.wso2.carbon.user.api.UserStoreException) GovernanceException(org.wso2.carbon.governance.api.exception.GovernanceException) DocumentationPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.DocumentationPersistenceException) APIMgtResourceNotFoundException(org.wso2.carbon.apimgt.api.APIMgtResourceNotFoundException) Collection(org.wso2.carbon.registry.core.Collection) DevPortalAPI(org.wso2.carbon.apimgt.persistence.dto.DevPortalAPI) PublisherAPI(org.wso2.carbon.apimgt.persistence.dto.PublisherAPI) API(org.wso2.carbon.apimgt.api.model.API) Tag(org.wso2.carbon.apimgt.api.model.Tag) APICategory(org.wso2.carbon.apimgt.api.model.APICategory)

Example 25 with Operation

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

the class RegistryPersistenceImpl method addAPI.

@SuppressWarnings("unchecked")
@Override
public PublisherAPI addAPI(Organization org, PublisherAPI publisherAPI) throws APIPersistenceException {
    API api = APIMapper.INSTANCE.toApi(publisherAPI);
    boolean transactionCommitted = false;
    boolean tenantFlowStarted = false;
    Registry registry = null;
    try {
        RegistryHolder holder = getRegistry(org.getName());
        registry = holder.getRegistry();
        tenantFlowStarted = holder.isTenantFlowStarted();
        registry.beginTransaction();
        GenericArtifactManager artifactManager = RegistryPersistenceUtil.getArtifactManager(registry, APIConstants.API_KEY);
        if (artifactManager == null) {
            String errorMessage = "Failed to retrieve artifact manager when creating API " + api.getId().getApiName();
            log.error(errorMessage);
            throw new APIPersistenceException(errorMessage);
        }
        GenericArtifact genericArtifact = artifactManager.newGovernanceArtifact(new QName(api.getId().getApiName()));
        if (genericArtifact == null) {
            String errorMessage = "Generic artifact is null when creating API " + api.getId().getApiName();
            log.error(errorMessage);
            throw new APIPersistenceException(errorMessage);
        }
        genericArtifact.setAttribute(APIConstants.API_OVERVIEW_VERSION_TIMESTAMP, api.getVersionTimestamp());
        GenericArtifact artifact = RegistryPersistenceUtil.createAPIArtifactContent(genericArtifact, api);
        artifactManager.addGenericArtifact(artifact);
        // Attach the API lifecycle
        artifact.attachLifecycle(APIConstants.API_LIFE_CYCLE);
        String artifactPath = GovernanceUtils.getArtifactPath(registry, artifact.getId());
        String providerPath = RegistryPersistenceUtil.getAPIProviderPath(api.getId());
        // provider ------provides----> API
        registry.addAssociation(providerPath, artifactPath, APIConstants.PROVIDER_ASSOCIATION);
        Set<String> tagSet = api.getTags();
        if (tagSet != null) {
            for (String tag : tagSet) {
                registry.applyTag(artifactPath, tag);
            }
        }
        String apiStatus = api.getStatus();
        saveAPIStatus(registry, artifactPath, apiStatus);
        String visibleRolesList = api.getVisibleRoles();
        String[] visibleRoles = new String[0];
        if (visibleRolesList != null) {
            visibleRoles = visibleRolesList.split(",");
        }
        String publisherAccessControlRoles = api.getAccessControlRoles();
        updateRegistryResources(registry, artifactPath, publisherAccessControlRoles, api.getAccessControl(), api.getAdditionalProperties());
        RegistryPersistenceUtil.setResourcePermissions(api.getId().getProviderName(), api.getVisibility(), visibleRoles, artifactPath, registry);
        if (api.getSwaggerDefinition() != null) {
            String resourcePath = RegistryPersistenceUtil.getOpenAPIDefinitionFilePath(api.getId().getName(), api.getId().getVersion(), api.getId().getProviderName());
            resourcePath = resourcePath + APIConstants.API_OAS_DEFINITION_RESOURCE_NAME;
            Resource resource;
            if (!registry.resourceExists(resourcePath)) {
                resource = registry.newResource();
            } else {
                resource = registry.get(resourcePath);
            }
            resource.setContent(api.getSwaggerDefinition());
            resource.setMediaType("application/json");
            registry.put(resourcePath, resource);
            // Need to set anonymous if the visibility is public
            RegistryPersistenceUtil.clearResourcePermissions(resourcePath, api.getId(), ((UserRegistry) registry).getTenantId());
            RegistryPersistenceUtil.setResourcePermissions(api.getId().getProviderName(), api.getVisibility(), visibleRoles, resourcePath);
        } else if (api.getAsyncApiDefinition() != null) {
            String resourcePath = RegistryPersistenceUtil.getOpenAPIDefinitionFilePath(api.getId().getName(), api.getId().getVersion(), api.getId().getProviderName());
            resourcePath = resourcePath + APIConstants.API_ASYNC_API_DEFINITION_RESOURCE_NAME;
            Resource resource;
            if (!registry.resourceExists(resourcePath)) {
                resource = registry.newResource();
            } else {
                resource = registry.get(resourcePath);
            }
            resource.setContent(api.getAsyncApiDefinition());
            // add a constant for app.json
            resource.setMediaType(APIConstants.APPLICATION_JSON_MEDIA_TYPE);
            registry.put(resourcePath, resource);
            RegistryPersistenceUtil.clearResourcePermissions(resourcePath, api.getId(), ((UserRegistry) registry).getTenantId());
            RegistryPersistenceUtil.setResourcePermissions(api.getId().getProviderName(), api.getVisibility(), visibleRoles, resourcePath);
        }
        // Set permissions to doc path
        String docLocation = RegistryPersistenceDocUtil.getDocumentPath(api.getId().getProviderName(), api.getId().getApiName(), api.getId().getVersion());
        RegistryPersistenceUtil.clearResourcePermissions(docLocation, api.getId(), ((UserRegistry) registry).getTenantId());
        RegistryPersistenceUtil.setResourcePermissions(api.getId().getProviderName(), api.getVisibility(), visibleRoles, docLocation);
        registry.commitTransaction();
        api.setUuid(artifact.getId());
        transactionCommitted = true;
        if (log.isDebugEnabled()) {
            log.debug("API details successfully added to the registry. API Name: " + api.getId().getApiName() + ", API Version : " + api.getId().getVersion() + ", API context : " + api.getContext());
        }
        // set current time as created time for returning api.
        api.setCreatedTime(String.valueOf(new Date().getTime()));
        PublisherAPI returnAPI = APIMapper.INSTANCE.toPublisherApi(api);
        if (log.isDebugEnabled()) {
            log.debug("Created API :" + returnAPI.toString());
        }
        return returnAPI;
    } 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: " + api.getId().getApiName(), re);
        }
        throw new APIPersistenceException("Error while performing registry transaction operation", e);
    } catch (APIManagementException e) {
        throw new APIPersistenceException("Error while creating API", e);
    } finally {
        if (tenantFlowStarted) {
            RegistryPersistenceUtil.endTenantFlow();
        }
        try {
            if (!transactionCommitted) {
                registry.rollbackTransaction();
            }
        } catch (RegistryException ex) {
            throw new APIPersistenceException("Error while rolling back the transaction for API: " + api.getId().getApiName(), ex);
        }
    }
}
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) QName(javax.xml.namespace.QName) Resource(org.wso2.carbon.registry.core.Resource) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) Registry(org.wso2.carbon.registry.core.Registry) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) Date(java.util.Date) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) PublisherAPI(org.wso2.carbon.apimgt.persistence.dto.PublisherAPI) DevPortalAPI(org.wso2.carbon.apimgt.persistence.dto.DevPortalAPI) PublisherAPI(org.wso2.carbon.apimgt.persistence.dto.PublisherAPI) API(org.wso2.carbon.apimgt.api.model.API)

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