Search in sources :

Example 6 with Tag

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

the class TagMappingUtilTestCase method testFromTagToDTO.

@Test
public void testFromTagToDTO() {
    Tag.Builder tagBuilder = new Tag.Builder();
    Tag tag = tagBuilder.name("tag1").count(1).build();
    TagDTO tagDTO = TagMappingUtil.fromTagToDTO(tag);
    assertEquals(tag.getName(), tagDTO.getName());
    assertEquals((Integer) tag.getCount(), tagDTO.getWeight());
}
Also used : TagDTO(org.wso2.carbon.apimgt.rest.api.store.dto.TagDTO) Tag(org.wso2.carbon.apimgt.core.models.Tag) Test(org.testng.annotations.Test)

Example 7 with Tag

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

the class AbstractAPIManager method registerCustomQueries.

/**
 * method to register custom registry queries
 *
 * @param registry Registry instance to use
 * @throws RegistryException n error
 */
protected void registerCustomQueries(UserRegistry registry, String username) throws RegistryException, APIManagementException {
    String tagsQueryPath = RegistryConstants.QUERIES_COLLECTION_PATH + "/tag-summary";
    String latestAPIsQueryPath = RegistryConstants.QUERIES_COLLECTION_PATH + "/latest-apis";
    String resourcesByTag = RegistryConstants.QUERIES_COLLECTION_PATH + "/resource-by-tag";
    String path = RegistryUtils.getAbsolutePath(RegistryContext.getBaseInstance(), APIUtil.getMountedPath(RegistryContext.getBaseInstance(), RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH) + APIConstants.GOVERNANCE_COMPONENT_REGISTRY_LOCATION);
    if (username == null) {
        try {
            UserRealm realm = ServiceReferenceHolder.getUserRealm();
            RegistryAuthorizationManager authorizationManager = new RegistryAuthorizationManager(realm);
            authorizationManager.authorizeRole(APIConstants.ANONYMOUS_ROLE, path, ActionConstants.GET);
        } catch (UserStoreException e) {
            String msg = "Error while setting the permissions";
            throw new APIManagementException(msg, e);
        }
    } else if (!MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
        int tenantId;
        try {
            tenantId = getTenantManager().getTenantId(tenantDomain);
            AuthorizationManager authManager = ServiceReferenceHolder.getInstance().getRealmService().getTenantUserRealm(tenantId).getAuthorizationManager();
            authManager.authorizeRole(APIConstants.ANONYMOUS_ROLE, path, ActionConstants.GET);
        } catch (org.wso2.carbon.user.api.UserStoreException e) {
            String msg = "Error while setting the permissions";
            throw new APIManagementException(msg, e);
        }
    }
    if (!registry.resourceExists(tagsQueryPath)) {
        Resource resource = registry.newResource();
        // Tag Search Query
        // 'MOCK_PATH' used to bypass ChrootWrapper -> filterSearchResult. A valid registry path is
        // a must for executeQuery results to be passed to client side
        String sql1 = "SELECT '" + APIUtil.getMountedPath(RegistryContext.getBaseInstance(), RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH) + APIConstants.GOVERNANCE_COMPONENT_REGISTRY_LOCATION + "' AS MOCK_PATH, " + "   RT.REG_TAG_NAME AS TAG_NAME, " + "   COUNT(RT.REG_TAG_NAME) AS USED_COUNT " + "FROM " + "   REG_RESOURCE_TAG RRT, " + "   REG_TAG RT, " + "   REG_RESOURCE R, " + "   REG_RESOURCE_PROPERTY RRP, " + "   REG_PROPERTY RP " + "WHERE " + "   RT.REG_ID = RRT.REG_TAG_ID  " + "   AND R.REG_MEDIA_TYPE = 'application/vnd.wso2-api+xml' " + "   AND RRT.REG_VERSION = R.REG_VERSION " + "   AND RRP.REG_VERSION = R.REG_VERSION " + "   AND RP.REG_NAME = 'STATUS' " + "   AND RRP.REG_PROPERTY_ID = RP.REG_ID " + "   AND (RP.REG_VALUE !='DEPRECATED' AND RP.REG_VALUE !='CREATED' AND RP.REG_VALUE !='BLOCKED' AND RP.REG_VALUE !='RETIRED') " + "GROUP BY " + "   RT.REG_TAG_NAME";
        resource.setContent(sql1);
        resource.setMediaType(RegistryConstants.SQL_QUERY_MEDIA_TYPE);
        resource.addProperty(RegistryConstants.RESULT_TYPE_PROPERTY_NAME, RegistryConstants.TAG_SUMMARY_RESULT_TYPE);
        registry.put(tagsQueryPath, resource);
    }
    if (!registry.resourceExists(latestAPIsQueryPath)) {
        // Recently added APIs
        Resource resource = registry.newResource();
        String sql = "SELECT " + "   RR.REG_PATH_ID AS REG_PATH_ID, " + "   RR.REG_NAME AS REG_NAME " + "FROM " + "   REG_RESOURCE RR, " + "   REG_RESOURCE_PROPERTY RRP, " + "   REG_PROPERTY RP " + "WHERE " + "   RR.REG_MEDIA_TYPE = 'application/vnd.wso2-api+xml' " + "   AND RRP.REG_VERSION = RR.REG_VERSION " + "   AND RP.REG_NAME = 'STATUS' " + "   AND RRP.REG_PROPERTY_ID = RP.REG_ID " + "   AND (RP.REG_VALUE !='DEPRECATED' AND RP.REG_VALUE !='CREATED') " + "ORDER BY " + "   RR.REG_LAST_UPDATED_TIME " + "DESC ";
        resource.setContent(sql);
        resource.setMediaType(RegistryConstants.SQL_QUERY_MEDIA_TYPE);
        resource.addProperty(RegistryConstants.RESULT_TYPE_PROPERTY_NAME, RegistryConstants.RESOURCES_RESULT_TYPE);
        registry.put(latestAPIsQueryPath, resource);
    }
    if (!registry.resourceExists(resourcesByTag)) {
        Resource resource = registry.newResource();
        String sql = "SELECT '" + APIUtil.getMountedPath(RegistryContext.getBaseInstance(), RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH) + APIConstants.GOVERNANCE_COMPONENT_REGISTRY_LOCATION + "' AS MOCK_PATH, " + "   R.REG_UUID AS REG_UUID " + "FROM " + "   REG_RESOURCE_TAG RRT, " + "   REG_TAG RT, " + "   REG_RESOURCE R, " + "   REG_PATH RP " + "WHERE " + "   RT.REG_TAG_NAME = ? " + "   AND R.REG_MEDIA_TYPE = 'application/vnd.wso2-api+xml' " + "   AND RP.REG_PATH_ID = R.REG_PATH_ID " + "   AND RT.REG_ID = RRT.REG_TAG_ID " + "   AND RRT.REG_VERSION = R.REG_VERSION ";
        resource.setContent(sql);
        resource.setMediaType(RegistryConstants.SQL_QUERY_MEDIA_TYPE);
        resource.addProperty(RegistryConstants.RESULT_TYPE_PROPERTY_NAME, RegistryConstants.RESOURCE_UUID_RESULT_TYPE);
        registry.put(resourcesByTag, resource);
    }
}
Also used : UserRealm(org.wso2.carbon.user.core.UserRealm) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) RegistryAuthorizationManager(org.wso2.carbon.registry.core.jdbc.realm.RegistryAuthorizationManager) UserStoreException(org.wso2.carbon.user.core.UserStoreException) Resource(org.wso2.carbon.registry.core.Resource) APIProductResource(org.wso2.carbon.apimgt.api.model.APIProductResource) RegistryAuthorizationManager(org.wso2.carbon.registry.core.jdbc.realm.RegistryAuthorizationManager) AuthorizationManager(org.wso2.carbon.user.api.AuthorizationManager)

Example 8 with Tag

use of org.wso2.carbon.apimgt.api.model.Tag 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 9 with Tag

use of org.wso2.carbon.apimgt.api.model.Tag 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)

Example 10 with Tag

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

the class RegistryPersistenceImpl method getAllTags.

@Override
public Set<Tag> getAllTags(Organization org, UserContext ctx) throws APIPersistenceException {
    TreeSet<Tag> tempTagSet = new TreeSet<Tag>(new Comparator<Tag>() {

        @Override
        public int compare(Tag o1, Tag o2) {
            return o1.getName().compareTo(o2.getName());
        }
    });
    Registry userRegistry = null;
    boolean tenantFlowStarted = false;
    String tagsQueryPath = null;
    try {
        RegistryHolder holder = getRegistry(org.getName());
        tenantFlowStarted = holder.isTenantFlowStarted();
        userRegistry = holder.getRegistry();
        tagsQueryPath = RegistryConstants.QUERIES_COLLECTION_PATH + "/tag-summary";
        Map<String, String> params = new HashMap<String, String>();
        params.put(RegistryConstants.RESULT_TYPE_PROPERTY_NAME, RegistryConstants.TAG_SUMMARY_RESULT_TYPE);
        String userNameLocal;
        if (holder.isAnonymousMode()) {
            userNameLocal = APIConstants.WSO2_ANONYMOUS_USER;
        } else {
            userNameLocal = getTenantAwareUsername(ctx.getUserame());
        }
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(userNameLocal);
        Map<String, Tag> tagsData = new HashMap<String, Tag>();
        Map<String, List<String>> criteriaPublished = new HashMap<String, List<String>>();
        criteriaPublished.put(APIConstants.LCSTATE_SEARCH_KEY, new ArrayList<String>() {

            {
                add(APIConstants.PUBLISHED);
            }
        });
        // rxt api media type
        List<TermData> termsPublished = GovernanceUtils.getTermDataList(criteriaPublished, APIConstants.API_OVERVIEW_TAG, APIConstants.API_RXT_MEDIA_TYPE, true);
        if (termsPublished != null) {
            for (TermData data : termsPublished) {
                tempTagSet.add(new Tag(data.getTerm(), (int) data.getFrequency()));
            }
        }
        Map<String, List<String>> criteriaPrototyped = new HashMap<String, List<String>>();
        criteriaPrototyped.put(APIConstants.LCSTATE_SEARCH_KEY, new ArrayList<String>() {

            {
                add(APIConstants.PROTOTYPED);
            }
        });
        // rxt api media type
        List<TermData> termsPrototyped = GovernanceUtils.getTermDataList(criteriaPrototyped, APIConstants.API_OVERVIEW_TAG, APIConstants.API_RXT_MEDIA_TYPE, true);
        if (termsPrototyped != null) {
            for (TermData data : termsPrototyped) {
                tempTagSet.add(new Tag(data.getTerm(), (int) data.getFrequency()));
            }
        }
        return tempTagSet;
    } catch (RegistryException e) {
        try {
            // give a warn.
            if (userRegistry != null && !userRegistry.resourceExists(tagsQueryPath)) {
                log.warn("Failed to retrieve tags query resource at " + tagsQueryPath);
                return Collections.EMPTY_SET;
            }
        } catch (RegistryException e1) {
            // Even if we should ignore this exception, we are logging this as a warn log.
            // The reason is that, this error happens when we try to add some additional logs in an error
            // scenario and it does not affect the execution path.
            log.warn("Unable to execute the resource exist method for tags query resource path : " + tagsQueryPath, e1);
        }
        throw new APIPersistenceException("Failed to get all the tags", e);
    } finally {
        if (tenantFlowStarted) {
            RegistryPersistenceUtil.endTenantFlow();
        }
    }
}
Also used : APIPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException) HashMap(java.util.HashMap) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) Registry(org.wso2.carbon.registry.core.Registry) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) TreeSet(java.util.TreeSet) TermData(org.wso2.carbon.registry.common.TermData) SolrDocumentList(org.apache.solr.common.SolrDocumentList) ArrayList(java.util.ArrayList) List(java.util.List) Tag(org.wso2.carbon.apimgt.api.model.Tag)

Aggregations

ArrayList (java.util.ArrayList)21 UserRegistry (org.wso2.carbon.registry.core.session.UserRegistry)21 Registry (org.wso2.carbon.registry.core.Registry)20 GenericArtifact (org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact)19 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)18 Tag (org.wso2.carbon.registry.core.Tag)18 RegistryException (org.wso2.carbon.registry.core.exceptions.RegistryException)18 API (org.wso2.carbon.apimgt.api.model.API)17 GenericArtifactManager (org.wso2.carbon.governance.api.generic.GenericArtifactManager)16 Resource (org.wso2.carbon.registry.core.Resource)16 DevPortalAPI (org.wso2.carbon.apimgt.persistence.dto.DevPortalAPI)14 UserStoreException (org.wso2.carbon.user.api.UserStoreException)14 HashSet (java.util.HashSet)13 BType (org.wso2.ballerinalang.compiler.semantics.model.types.BType)12 Test (org.junit.Test)11 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)11 JSONObject (org.json.simple.JSONObject)10 Tag (org.wso2.carbon.apimgt.api.model.Tag)10 List (java.util.List)9 GovernanceException (org.wso2.carbon.governance.api.exception.GovernanceException)9