Search in sources :

Example 81 with GenericArtifactManager

use of org.wso2.carbon.governance.api.generic.GenericArtifactManager in project carbon-apimgt by wso2.

the class APIProviderImpl method createAPI.

/**
 * Create an Api
 *
 * @param api API
 * @throws APIManagementException if failed to create API
 */
protected String createAPI(API api) throws APIManagementException {
    GenericArtifactManager artifactManager = APIUtil.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 APIManagementException(errorMessage);
    }
    if (api.isEndpointSecured() && StringUtils.isEmpty(api.getEndpointUTPassword())) {
        String errorMessage = "Empty password is given for endpointSecurity when creating API " + api.getId().getApiName();
        throw new APIManagementException(errorMessage);
    }
    // Validate Transports
    validateAndSetTransports(api);
    validateAndSetAPISecurity(api);
    boolean transactionCommitted = false;
    String apiUUID = null;
    try {
        registry.beginTransaction();
        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 APIManagementException(errorMessage);
        }
        GenericArtifact artifact = APIUtil.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 = APIUtil.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);
            }
        }
        if (APIUtil.isValidWSDLURL(api.getWsdlUrl(), false)) {
            String path = APIUtil.createWSDL(registry, api);
            updateWSDLUriInAPIArtifact(path, artifactManager, artifact, artifactPath);
        }
        if (api.getWsdlResource() != null) {
            String path = APIUtil.saveWSDLResource(registry, api);
            updateWSDLUriInAPIArtifact(path, artifactManager, artifact, artifactPath);
        }
        // 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();
        saveAPIStatus(artifactPath, apiStatus);
        String visibleRolesList = api.getVisibleRoles();
        String[] visibleRoles = new String[0];
        if (visibleRolesList != null) {
            visibleRoles = visibleRolesList.split(",");
        }
        String publisherAccessControlRoles = api.getAccessControlRoles();
        updateRegistryResources(artifactPath, publisherAccessControlRoles, api.getAccessControl(), api.getAdditionalProperties());
        APIUtil.setResourcePermissions(api.getId().getProviderName(), api.getVisibility(), visibleRoles, artifactPath, registry);
        registry.commitTransaction();
        transactionCommitted = true;
        if (log.isDebugEnabled()) {
            String logMessage = "API Name: " + api.getId().getApiName() + ", API Version " + api.getId().getVersion() + " created";
            log.debug(logMessage);
        }
        apiUUID = artifact.getId();
    } 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);
        }
        handleException("Error while performing registry transaction operation", e);
    } catch (APIManagementException e) {
        handleException("Error while creating API", e);
    } finally {
        try {
            if (!transactionCommitted) {
                registry.rollbackTransaction();
            }
        } catch (RegistryException ex) {
            handleException("Error while rolling back the transaction for API: " + api.getId().getApiName(), ex);
        }
    }
    return apiUUID;
}
Also used : GenericArtifact(org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact) GenericArtifactManager(org.wso2.carbon.governance.api.generic.GenericArtifactManager) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) QName(javax.xml.namespace.QName) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException)

Example 82 with GenericArtifactManager

use of org.wso2.carbon.governance.api.generic.GenericArtifactManager in project carbon-apimgt by wso2.

the class APIProviderImpl method configureMonetizationInAPIProductArtifact.

@Override
public void configureMonetizationInAPIProductArtifact(APIProduct apiProduct) throws APIManagementException {
    boolean transactionCommitted = false;
    try {
        registry.beginTransaction();
        String apiArtifactId = registry.get(APIUtil.getAPIProductPath(apiProduct.getId())).getId();
        GenericArtifactManager artifactManager = APIUtil.getArtifactManager(registry, APIConstants.API_KEY);
        if (artifactManager == null) {
            handleException("Artifact manager is null when updating monetization data for API ID " + apiProduct.getId());
        }
        GenericArtifact artifact = artifactManager.getGenericArtifact(apiProduct.getUuid());
        // set monetization status (i.e - enabled or disabled)
        artifact.setAttribute(APIConstants.Monetization.API_MONETIZATION_STATUS, Boolean.toString(apiProduct.getMonetizationStatus()));
        // clear existing monetization properties
        artifact.removeAttribute(APIConstants.Monetization.API_MONETIZATION_PROPERTIES);
        // set new additional monetization data
        if (apiProduct.getMonetizationProperties() != null) {
            artifact.setAttribute(APIConstants.Monetization.API_MONETIZATION_PROPERTIES, apiProduct.getMonetizationProperties().toJSONString());
        }
        artifactManager.updateGenericArtifact(artifact);
        registry.commitTransaction();
        transactionCommitted = true;
    } catch (Exception e) {
        try {
            registry.rollbackTransaction();
        } catch (RegistryException re) {
            handleException("Error while rolling back the transaction (monetization status update) for API product : " + apiProduct.getId().getName(), re);
        }
        handleException("Error while performing registry transaction (monetization status update) operation", e);
    } finally {
        try {
            if (!transactionCommitted) {
                registry.rollbackTransaction();
            }
        } catch (RegistryException e) {
            handleException("Error occurred while rolling back the transaction (monetization status update).", e);
        }
    }
}
Also used : GenericArtifact(org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact) GenericArtifactManager(org.wso2.carbon.governance.api.generic.GenericArtifactManager) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) APIPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException) XMLStreamException(javax.xml.stream.XMLStreamException) GraphQLPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.GraphQLPersistenceException) APIImportExportException(org.wso2.carbon.apimgt.impl.importexport.APIImportExportException) IOException(java.io.IOException) MediationPolicyPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.MediationPolicyPersistenceException) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) ArtifactSynchronizerException(org.wso2.carbon.apimgt.impl.gatewayartifactsynchronizer.exception.ArtifactSynchronizerException) WSDLPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.WSDLPersistenceException) UserStoreException(org.wso2.carbon.user.api.UserStoreException) GovernanceException(org.wso2.carbon.governance.api.exception.GovernanceException) DocumentationPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.DocumentationPersistenceException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) APIMgtResourceNotFoundException(org.wso2.carbon.apimgt.api.APIMgtResourceNotFoundException) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) PersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.PersistenceException) UnsupportedPolicyTypeException(org.wso2.carbon.apimgt.api.UnsupportedPolicyTypeException) FaultGatewaysException(org.wso2.carbon.apimgt.api.FaultGatewaysException) NotificationException(org.wso2.carbon.apimgt.impl.notification.exception.NotificationException) APIMgtResourceAlreadyExistsException(org.wso2.carbon.apimgt.api.APIMgtResourceAlreadyExistsException) MonetizationException(org.wso2.carbon.apimgt.api.MonetizationException) ThumbnailPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.ThumbnailPersistenceException) OASPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.OASPersistenceException) WorkflowException(org.wso2.carbon.apimgt.impl.workflow.WorkflowException) AsyncSpecPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.AsyncSpecPersistenceException) ParseException(org.json.simple.parser.ParseException) MalformedURLException(java.net.MalformedURLException) OMException(org.apache.axiom.om.OMException)

Example 83 with GenericArtifactManager

use of org.wso2.carbon.governance.api.generic.GenericArtifactManager in project carbon-apimgt by wso2.

the class APIProviderImpl method getAPIsByProvider.

/**
 * Get a list of APIs published by the given provider. If a given API has multiple APIs,
 * only the latest version will
 * be included in this list.
 *
 * @param providerId , provider id
 * @return set of API
 * @throws org.wso2.carbon.apimgt.api.APIManagementException if failed to get set of API
 */
@Override
public List<API> getAPIsByProvider(String providerId) throws APIManagementException {
    List<API> apiSortedList = new ArrayList<API>();
    try {
        providerId = APIUtil.replaceEmailDomain(providerId);
        String providerPath = APIConstants.API_ROOT_LOCATION + RegistryConstants.PATH_SEPARATOR + providerId;
        GenericArtifactManager artifactManager = APIUtil.getArtifactManager(registry, APIConstants.API_KEY);
        Association[] associations = registry.getAssociations(providerPath, APIConstants.PROVIDER_ASSOCIATION);
        for (Association association : associations) {
            String apiPath = association.getDestinationPath();
            if (registry.resourceExists(apiPath)) {
                Resource resource = registry.get(apiPath);
                String apiArtifactId = resource.getUUID();
                if (apiArtifactId != null) {
                    GenericArtifact apiArtifact = artifactManager.getGenericArtifact(apiArtifactId);
                    if (apiArtifact != null) {
                        String type = apiArtifact.getAttribute(APIConstants.API_OVERVIEW_TYPE);
                        if (!APIConstants.API_PRODUCT.equals(type)) {
                            apiSortedList.add(getAPI(apiArtifact));
                        }
                    }
                } else {
                    throw new GovernanceException("artifact id is null of " + apiPath);
                }
            }
        }
    } catch (RegistryException e) {
        handleException("Failed to get APIs for provider : " + providerId, e);
    }
    Collections.sort(apiSortedList, new APINameComparator());
    return apiSortedList;
}
Also used : GenericArtifact(org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact) GenericArtifactManager(org.wso2.carbon.governance.api.generic.GenericArtifactManager) Association(org.wso2.carbon.registry.core.Association) ArrayList(java.util.ArrayList) Resource(org.wso2.carbon.registry.core.Resource) APIProductResource(org.wso2.carbon.apimgt.api.model.APIProductResource) APIResource(org.wso2.carbon.apimgt.api.doc.model.APIResource) GovernanceException(org.wso2.carbon.governance.api.exception.GovernanceException) API(org.wso2.carbon.apimgt.api.model.API) ImportExportAPI(org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) PublisherAPI(org.wso2.carbon.apimgt.persistence.dto.PublisherAPI) APINameComparator(org.wso2.carbon.apimgt.impl.utils.APINameComparator) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException)

Example 84 with GenericArtifactManager

use of org.wso2.carbon.governance.api.generic.GenericArtifactManager in project carbon-apimgt by wso2.

the class APIProviderImpl method updateDocVisibility.

/**
 * Updates a visibility of the documentation
 *
 * @param api               API
 * @param documentation    Documentation
 * @throws APIManagementException if failed to update visibility
 */
private void updateDocVisibility(API api, Documentation documentation) throws APIManagementException {
    try {
        GenericArtifactManager artifactManager = APIUtil.getArtifactManager(registry, APIConstants.DOCUMENTATION_KEY);
        if (artifactManager == null) {
            String errorMessage = "Artifact manager is null when updating documentation of API " + api.getId().getApiName();
            throw new APIManagementException(errorMessage);
        }
        GenericArtifact artifact = artifactManager.getGenericArtifact(documentation.getId());
        String[] authorizedRoles = new String[0];
        String visibleRolesList = api.getVisibleRoles();
        if (visibleRolesList != null) {
            authorizedRoles = visibleRolesList.split(",");
        }
        int tenantId;
        String tenantDomain = MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(api.getId().getProviderName()));
        try {
            tenantId = getTenantId(tenantDomain);
            GenericArtifact updateApiArtifact = APIUtil.createDocArtifactContent(artifact, api.getId(), documentation);
            artifactManager.updateGenericArtifact(updateApiArtifact);
            APIUtil.clearResourcePermissions(artifact.getPath(), api.getId(), tenantId);
            APIUtil.setResourcePermissions(api.getId().getProviderName(), api.getVisibility(), authorizedRoles, artifact.getPath(), registry);
            String docType = artifact.getAttribute(APIConstants.DOC_SOURCE_TYPE);
            if (APIConstants.IMPLEMENTATION_TYPE_INLINE.equals(docType) || APIConstants.IMPLEMENTATION_TYPE_MARKDOWN.equals(docType)) {
                String docContentPath = APIUtil.getAPIDocPath(api.getId()) + APIConstants.INLINE_DOCUMENT_CONTENT_DIR + RegistryConstants.PATH_SEPARATOR + artifact.getAttribute(APIConstants.DOC_NAME);
                APIUtil.clearResourcePermissions(docContentPath, api.getId(), tenantId);
                APIUtil.setResourcePermissions(api.getId().getProviderName(), api.getVisibility(), authorizedRoles, docContentPath, registry);
            } else if (APIConstants.IMPLEMENTATION_TYPE_FILE.equals(docType)) {
                String docFilePath = APIUtil.getDocumentationFilePath(api.getId(), artifact.getAttribute(APIConstants.DOC_FILE_PATH).split(APIConstants.DOCUMENT_FILE_DIR + RegistryConstants.PATH_SEPARATOR)[1]);
                APIUtil.clearResourcePermissions(docFilePath, api.getId(), tenantId);
                APIUtil.setResourcePermissions(api.getId().getProviderName(), api.getVisibility(), authorizedRoles, docFilePath, registry);
            }
        } catch (UserStoreException e) {
            throw new APIManagementException("Error in retrieving Tenant Information while updating the " + "visibility of documentations for the API :" + api.getId().getApiName(), e);
        }
    } catch (RegistryException e) {
        handleException("Failed to update visibility of documentation" + api.getId().getApiName(), e);
    }
}
Also used : GenericArtifact(org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact) GenericArtifactManager(org.wso2.carbon.governance.api.generic.GenericArtifactManager) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) UserStoreException(org.wso2.carbon.user.api.UserStoreException) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException)

Example 85 with GenericArtifactManager

use of org.wso2.carbon.governance.api.generic.GenericArtifactManager in project carbon-apimgt by wso2.

the class APIProviderImpl method addProductDocumentationContent.

/**
 * This method used to save the product documentation content
 *
 * @param apiProduct,               API Product
 * @param documentationName, name of the inline documentation
 * @param text,              content of the inline documentation
 * @throws org.wso2.carbon.apimgt.api.APIManagementException if failed to add the document as a resource to registry
 */
public void addProductDocumentationContent(APIProduct apiProduct, String documentationName, String text) throws APIManagementException {
    APIProductIdentifier identifier = apiProduct.getId();
    String documentationPath = APIUtil.getProductDocPath(identifier) + documentationName;
    String contentPath = APIUtil.getProductDocPath(identifier) + APIConstants.INLINE_DOCUMENT_CONTENT_DIR + RegistryConstants.PATH_SEPARATOR + documentationName;
    boolean isTenantFlowStarted = false;
    try {
        if (tenantDomain != null && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
            PrivilegedCarbonContext.startTenantFlow();
            isTenantFlowStarted = true;
            PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);
        }
        Resource docResource = registry.get(documentationPath);
        GenericArtifactManager artifactManager = new GenericArtifactManager(registry, APIConstants.DOCUMENTATION_KEY);
        GenericArtifact docArtifact = artifactManager.getGenericArtifact(docResource.getUUID());
        Documentation doc = APIUtil.getDocumentation(docArtifact);
        Resource docContent;
        if (!registry.resourceExists(contentPath)) {
            docContent = registry.newResource();
        } else {
            docContent = registry.get(contentPath);
        }
        /* This is a temporary fix for doc content replace issue. We need to add
             * separate methods to add inline content resource in document update */
        if (!APIConstants.NO_CONTENT_UPDATE.equals(text)) {
            docContent.setContent(text);
        }
        docContent.setMediaType(APIConstants.DOCUMENTATION_INLINE_CONTENT_TYPE);
        registry.put(contentPath, docContent);
        registry.addAssociation(documentationPath, contentPath, APIConstants.DOCUMENTATION_CONTENT_ASSOCIATION);
        String productPath = APIUtil.getAPIProductPath(identifier);
        String[] authorizedRoles = getAuthorizedRoles(productPath);
        String docVisibility = doc.getVisibility().name();
        String visibility = apiProduct.getVisibility();
        if (docVisibility != null) {
            if (APIConstants.DOC_SHARED_VISIBILITY.equalsIgnoreCase(docVisibility)) {
                authorizedRoles = null;
                visibility = APIConstants.DOC_SHARED_VISIBILITY;
            } else if (APIConstants.DOC_OWNER_VISIBILITY.equalsIgnoreCase(docVisibility)) {
                authorizedRoles = null;
                visibility = APIConstants.DOC_OWNER_VISIBILITY;
            }
        }
        APIUtil.setResourcePermissions(apiProduct.getId().getProviderName(), visibility, authorizedRoles, contentPath, registry);
    } catch (RegistryException e) {
        String msg = "Failed to add the documentation content of : " + documentationName + " of API Product :" + identifier.getName();
        handleException(msg, e);
    } catch (UserStoreException e) {
        String msg = "Failed to add the documentation content of : " + documentationName + " of API Product :" + identifier.getName();
        handleException(msg, e);
    } finally {
        if (isTenantFlowStarted) {
            PrivilegedCarbonContext.endTenantFlow();
        }
    }
}
Also used : APIProductIdentifier(org.wso2.carbon.apimgt.api.model.APIProductIdentifier) GenericArtifact(org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact) GenericArtifactManager(org.wso2.carbon.governance.api.generic.GenericArtifactManager) Documentation(org.wso2.carbon.apimgt.api.model.Documentation) Resource(org.wso2.carbon.registry.core.Resource) APIProductResource(org.wso2.carbon.apimgt.api.model.APIProductResource) APIResource(org.wso2.carbon.apimgt.api.doc.model.APIResource) UserStoreException(org.wso2.carbon.user.api.UserStoreException) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException)

Aggregations

GenericArtifactManager (org.wso2.carbon.governance.api.generic.GenericArtifactManager)95 GenericArtifact (org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact)90 RegistryException (org.wso2.carbon.registry.core.exceptions.RegistryException)70 UserRegistry (org.wso2.carbon.registry.core.session.UserRegistry)63 Registry (org.wso2.carbon.registry.core.Registry)57 Resource (org.wso2.carbon.registry.core.Resource)54 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)51 API (org.wso2.carbon.apimgt.api.model.API)37 Test (org.junit.Test)29 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)29 DevPortalAPI (org.wso2.carbon.apimgt.persistence.dto.DevPortalAPI)29 APIPersistenceException (org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException)29 SubscribedAPI (org.wso2.carbon.apimgt.api.model.SubscribedAPI)28 UserStoreException (org.wso2.carbon.user.api.UserStoreException)27 ArrayList (java.util.ArrayList)26 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)26 GovernanceException (org.wso2.carbon.governance.api.exception.GovernanceException)20 HashMap (java.util.HashMap)18 DocumentationPersistenceException (org.wso2.carbon.apimgt.persistence.exceptions.DocumentationPersistenceException)17 APIProductResource (org.wso2.carbon.apimgt.api.model.APIProductResource)16