Search in sources :

Example 76 with Identifier

use of org.wso2.carbon.apimgt.api.model.Identifier in project carbon-apimgt by wso2.

the class APIProviderImpl method getCustomSequence.

/**
 * Get the resource which matches the user selected resource type and the name from the custom uploaded sequences.
 *
 * @param identifier : The API Identifier.
 * @param type       : The sequence type.
 * @return : Resource object which matches the parameters. If no resource found, return null.
 */
private Resource getCustomSequence(APIIdentifier identifier, String type, String name) throws APIManagementException {
    Resource customSequence = null;
    boolean isTenantFlowStarted = false;
    try {
        String tenantDomain = null;
        if (identifier.getProviderName().contains("-AT-")) {
            String provider = identifier.getProviderName().replace("-AT-", "@");
            tenantDomain = MultitenantUtils.getTenantDomain(provider);
        }
        if (!MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
            PrivilegedCarbonContext.startTenantFlow();
            isTenantFlowStarted = true;
        }
        if (!StringUtils.isEmpty(tenantDomain)) {
            PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);
        } else {
            PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME, true);
        }
        UserRegistry registry = ServiceReferenceHolder.getInstance().getRegistryService().getGovernanceSystemRegistry(tenantId);
        String customSeqFileLocation = "";
        if (APIConstants.FAULT_SEQUENCE.equals(type)) {
            customSeqFileLocation = APIUtil.getSequencePath(identifier, APIConstants.API_CUSTOM_SEQUENCE_TYPE_FAULT);
        } else if (APIConstants.OUT_SEQUENCE.equals(type)) {
            customSeqFileLocation = APIUtil.getSequencePath(identifier, APIConstants.API_CUSTOM_SEQUENCE_TYPE_OUT);
        } else {
            customSeqFileLocation = APIUtil.getSequencePath(identifier, APIConstants.API_CUSTOM_SEQUENCE_TYPE_IN);
        }
        if (registry.resourceExists(customSeqFileLocation)) {
            org.wso2.carbon.registry.api.Collection customSeqCollection = (org.wso2.carbon.registry.api.Collection) registry.get(customSeqFileLocation);
            if (customSeqCollection != null) {
                String[] faultSeqChildPaths = customSeqCollection.getChildren();
                for (String customSeqChildPath : faultSeqChildPaths) {
                    customSequence = registry.get(customSeqChildPath);
                    OMElement seqElement = APIUtil.buildOMElement(customSequence.getContentStream());
                    if (name.equals(seqElement.getAttributeValue(new QName("name")))) {
                        return customSequence;
                    }
                }
            }
        }
    } catch (RegistryException e) {
        throw new APIManagementException("Error while retrieving registry for tenant " + tenantId, e);
    } catch (org.wso2.carbon.registry.api.RegistryException e) {
        throw new APIManagementException("Error while processing the " + type + " sequences of " + identifier + " in the registry", e);
    } catch (Exception e) {
        throw new APIManagementException("Error while building the OMElement from the sequence " + name, e);
    } finally {
        if (isTenantFlowStarted) {
            PrivilegedCarbonContext.endTenantFlow();
        }
    }
    return null;
}
Also used : QName(javax.xml.namespace.QName) Resource(org.wso2.carbon.registry.core.Resource) APIProductResource(org.wso2.carbon.apimgt.api.model.APIProductResource) APIResource(org.wso2.carbon.apimgt.api.doc.model.APIResource) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) OMElement(org.apache.axiom.om.OMElement) 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) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException)

Example 77 with Identifier

use of org.wso2.carbon.apimgt.api.model.Identifier in project carbon-apimgt by wso2.

the class APIProviderImpl method getLightweightAPIByUUID.

/**
 * Get minimal details of API by registry artifact id
 *
 * @param uuid Registry artifact id
 * @param organization identifier of the organization
 * @return API of the provided artifact id
 * @throws APIManagementException
 */
@Override
public API getLightweightAPIByUUID(String uuid, String organization) throws APIManagementException {
    try {
        Organization org = new Organization(organization);
        PublisherAPI publisherAPI = apiPersistenceInstance.getPublisherAPI(org, uuid);
        if (publisherAPI != null) {
            API api = APIMapper.INSTANCE.toApi(publisherAPI);
            checkAccessControlPermission(userNameWithoutChange, api.getAccessControl(), api.getAccessControlRoles());
            // / populate relavant external info
            // environment
            String environmentString = null;
            if (api.getEnvironments() != null) {
                environmentString = String.join(",", api.getEnvironments());
            }
            api.setEnvironments(APIUtil.extractEnvironmentsForAPI(environmentString, organization));
            // CORS . if null is returned, set default config from the configuration
            if (api.getCorsConfiguration() == null) {
                api.setCorsConfiguration(APIUtil.getDefaultCorsConfiguration());
            }
            api.setOrganization(organization);
            return api;
        } else {
            String msg = "Failed to get API. API artifact corresponding to artifactId " + uuid + " does not exist";
            throw new APIMgtResourceNotFoundException(msg);
        }
    } catch (APIPersistenceException e) {
        String msg = "Failed to get API with uuid " + uuid;
        throw new APIManagementException(msg, e);
    }
}
Also used : APIPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException) Organization(org.wso2.carbon.apimgt.persistence.dto.Organization) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) PublisherAPI(org.wso2.carbon.apimgt.persistence.dto.PublisherAPI) 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) APIMgtResourceNotFoundException(org.wso2.carbon.apimgt.api.APIMgtResourceNotFoundException)

Example 78 with Identifier

use of org.wso2.carbon.apimgt.api.model.Identifier in project carbon-apimgt by wso2.

the class APIConsumerImpl method removeSubscription.

/**
 * Removes a subscription specified by SubscribedAPI object
 *
 * @param subscription SubscribedAPI object
 * @param organization Organization
 * @throws APIManagementException
 */
@Override
public void removeSubscription(SubscribedAPI subscription, String organization) throws APIManagementException {
    String uuid = subscription.getUUID();
    if (subscription != null) {
        Application application = subscription.getApplication();
        Identifier identifier = subscription.getApiId() != null ? subscription.getApiId() : subscription.getProductId();
        String userId = application.getSubscriber().getName();
        removeSubscription(identifier, userId, application.getId(), organization);
        if (log.isDebugEnabled()) {
            String appName = application.getName();
            String logMessage = "Identifier:  " + identifier.toString() + " subscription (uuid : " + uuid + ") removed from app " + appName;
            log.debug(logMessage);
        }
        // get the workflow state once the executor is executed.
        WorkflowDTO wfDTO = apiMgtDAO.retrieveWorkflowFromInternalReference(Integer.toString(application.getId()), WorkflowConstants.WF_TYPE_AM_SUBSCRIPTION_DELETION);
        int tenantId = APIUtil.getTenantId(APIUtil.replaceEmailDomainBack(identifier.getProviderName()));
        String tenantDomain = MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(identifier.getProviderName()));
        // wfDTO is null when simple wf executor is used because wf state is not stored in the db and is always approved.
        if (wfDTO != null) {
            if (WorkflowStatus.APPROVED.equals(wfDTO.getStatus())) {
                SubscriptionEvent subscriptionEvent = new SubscriptionEvent(UUID.randomUUID().toString(), System.currentTimeMillis(), APIConstants.EventType.SUBSCRIPTIONS_DELETE.name(), tenantId, tenantDomain, subscription.getSubscriptionId(), subscription.getUUID(), identifier.getId(), identifier.getUUID(), application.getId(), application.getUUID(), identifier.getTier(), subscription.getSubStatus());
                APIUtil.sendNotification(subscriptionEvent, APIConstants.NotifierType.SUBSCRIPTIONS.name());
            }
        } else {
            SubscriptionEvent subscriptionEvent = new SubscriptionEvent(UUID.randomUUID().toString(), System.currentTimeMillis(), APIConstants.EventType.SUBSCRIPTIONS_DELETE.name(), tenantId, tenantDomain, subscription.getSubscriptionId(), subscription.getUUID(), identifier.getId(), identifier.getUUID(), application.getId(), application.getUUID(), identifier.getTier(), subscription.getSubStatus());
            APIUtil.sendNotification(subscriptionEvent, APIConstants.NotifierType.SUBSCRIPTIONS.name());
        }
    } else {
        throw new APIManagementException(String.format("Subscription for UUID:%s does not exist.", subscription.getUUID()));
    }
}
Also used : SubscriptionEvent(org.wso2.carbon.apimgt.impl.notifier.events.SubscriptionEvent) ApplicationWorkflowDTO(org.wso2.carbon.apimgt.impl.dto.ApplicationWorkflowDTO) WorkflowDTO(org.wso2.carbon.apimgt.impl.dto.WorkflowDTO) ApplicationRegistrationWorkflowDTO(org.wso2.carbon.apimgt.impl.dto.ApplicationRegistrationWorkflowDTO) SubscriptionWorkflowDTO(org.wso2.carbon.apimgt.impl.dto.SubscriptionWorkflowDTO) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) APIProductIdentifier(org.wso2.carbon.apimgt.api.model.APIProductIdentifier) Identifier(org.wso2.carbon.apimgt.api.model.Identifier) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) Application(org.wso2.carbon.apimgt.api.model.Application)

Example 79 with Identifier

use of org.wso2.carbon.apimgt.api.model.Identifier in project carbon-apimgt by wso2.

the class APIProviderImpl method getAPIProductUsageByAPIProductId.

/**
 * Returns usage details of a particular API
 *
 * @param apiProductId API Product identifier
 * @return UserApplicationAPIUsages for given provider
 * @throws org.wso2.carbon.apimgt.api.APIManagementException If failed to get UserApplicationAPIUsage
 */
@Override
public List<SubscribedAPI> getAPIProductUsageByAPIProductId(APIProductIdentifier apiProductId) throws APIManagementException {
    APIProductIdentifier apiIdEmailReplaced = new APIProductIdentifier(APIUtil.replaceEmailDomain(apiProductId.getProviderName()), apiProductId.getName(), apiProductId.getVersion());
    UserApplicationAPIUsage[] allApiProductResult = apiMgtDAO.getAllAPIProductUsageByProvider(apiProductId.getProviderName());
    List<SubscribedAPI> subscribedAPIs = new ArrayList<>();
    for (UserApplicationAPIUsage usage : allApiProductResult) {
        for (SubscribedAPI apiSubscription : usage.getApiSubscriptions()) {
            APIProductIdentifier subsApiProductId = apiSubscription.getProductId();
            APIProductIdentifier subsApiProductIdEmailReplaced = new APIProductIdentifier(APIUtil.replaceEmailDomain(subsApiProductId.getProviderName()), subsApiProductId.getName(), subsApiProductId.getVersion());
            if (subsApiProductIdEmailReplaced.equals(apiIdEmailReplaced)) {
                subscribedAPIs.add(apiSubscription);
            }
        }
    }
    return subscribedAPIs;
}
Also used : APIProductIdentifier(org.wso2.carbon.apimgt.api.model.APIProductIdentifier) UserApplicationAPIUsage(org.wso2.carbon.apimgt.api.dto.UserApplicationAPIUsage) ArrayList(java.util.ArrayList) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI)

Example 80 with Identifier

use of org.wso2.carbon.apimgt.api.model.Identifier in project carbon-apimgt by wso2.

the class APIProviderImpl method addDocumentationContent.

/**
 * This method used to save the documentation content
 *
 * @param api,               API
 * @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 addDocumentationContent(API api, String documentationName, String text) throws APIManagementException {
    APIIdentifier identifier = api.getId();
    String documentationPath = APIUtil.getAPIDocPath(identifier) + documentationName;
    String contentPath = APIUtil.getAPIDocPath(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);
        String apiPath = APIUtil.getAPIPath(identifier);
        String[] authorizedRoles = getAuthorizedRoles(apiPath);
        String docVisibility = doc.getVisibility().name();
        String visibility = api.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(api.getId().getProviderName(), visibility, authorizedRoles, contentPath, registry);
    } catch (RegistryException e) {
        String msg = "Failed to add the documentation content of : " + documentationName + " of API :" + identifier.getApiName();
        handleException(msg, e);
    } catch (UserStoreException e) {
        String msg = "Failed to add the documentation content of : " + documentationName + " of API :" + identifier.getApiName();
        handleException(msg, e);
    } finally {
        if (isTenantFlowStarted) {
            PrivilegedCarbonContext.endTenantFlow();
        }
    }
}
Also used : 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) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException)

Aggregations

APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)118 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)83 RegistryException (org.wso2.carbon.registry.core.exceptions.RegistryException)66 API (org.wso2.carbon.apimgt.api.model.API)42 Resource (org.wso2.carbon.registry.core.Resource)40 APIProductIdentifier (org.wso2.carbon.apimgt.api.model.APIProductIdentifier)39 Test (org.junit.Test)36 PreparedStatement (java.sql.PreparedStatement)34 SQLException (java.sql.SQLException)34 SubscribedAPI (org.wso2.carbon.apimgt.api.model.SubscribedAPI)34 Connection (java.sql.Connection)33 UserStoreException (org.wso2.carbon.user.core.UserStoreException)31 ResultSet (java.sql.ResultSet)29 ArrayList (java.util.ArrayList)29 APIProvider (org.wso2.carbon.apimgt.api.APIProvider)29 UserRegistry (org.wso2.carbon.registry.core.session.UserRegistry)27 IOException (java.io.IOException)26 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)26 APIProductResource (org.wso2.carbon.apimgt.api.model.APIProductResource)25 HumanTaskException (org.wso2.carbon.humantask.core.engine.HumanTaskException)24