Search in sources :

Example 16 with Tag

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

the class APIMapperTestCase method setupClass.

@Before
public void setupClass() throws Exception {
    System.setProperty("carbon.home", "");
    ServiceReferenceHolder serviceRefHolder = Mockito.mock(ServiceReferenceHolder.class);
    PowerMockito.mockStatic(ServiceReferenceHolder.class);
    PowerMockito.when(ServiceReferenceHolder.getInstance()).thenReturn(serviceRefHolder);
    RealmService realmService = Mockito.mock(RealmService.class);
    PowerMockito.when(serviceRefHolder.getRealmService()).thenReturn(realmService);
    TenantManager tenantManager = Mockito.mock(TenantManager.class);
    PowerMockito.when(realmService.getTenantManager()).thenReturn(tenantManager);
    PowerMockito.when(tenantManager.getTenantId(SUPER_TENANT_DOMAIN)).thenReturn(SUPER_TENANT_ID);
    registry = Mockito.mock(Registry.class);
    PowerMockito.mockStatic(MultitenantUtils.class);
    Resource resource = new ResourceImpl();
    Mockito.when(registry.get(anyString())).thenReturn(resource);
    Tag[] tags = new Tag[1];
    Tag tag = new Tag();
    tag.setTagName("testTag");
    tags[0] = tag;
    Mockito.when(registry.getTags(anyString())).thenReturn(tags);
    PowerMockito.mockStatic(GovernanceUtils.class);
    PowerMockito.mockStatic(PrivilegedCarbonContext.class);
    PrivilegedCarbonContext privilegedContext = Mockito.mock(PrivilegedCarbonContext.class);
    PowerMockito.when(PrivilegedCarbonContext.getThreadLocalCarbonContext()).thenReturn(privilegedContext);
    GenericArtifact genericArtifact = PersistenceHelper.getSampleAPIArtifact();
    api = RegistryPersistenceUtil.getAPI(genericArtifact, registry);
    GenericArtifact productGenericArtifact = PersistenceHelper.getSampleAPIProductArtifact();
    product = RegistryPersistenceUtil.getAPIProduct(productGenericArtifact, registry);
}
Also used : ServiceReferenceHolder(org.wso2.carbon.apimgt.persistence.internal.ServiceReferenceHolder) GenericArtifact(org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact) ResourceImpl(org.wso2.carbon.registry.core.ResourceImpl) RealmService(org.wso2.carbon.user.core.service.RealmService) Resource(org.wso2.carbon.registry.core.Resource) PrivilegedCarbonContext(org.wso2.carbon.context.PrivilegedCarbonContext) Registry(org.wso2.carbon.registry.core.Registry) Tag(org.wso2.carbon.registry.core.Tag) TenantManager(org.wso2.carbon.user.core.tenant.TenantManager) Before(org.junit.Before)

Example 17 with Tag

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

the class RegistryPersistenceUtilTestCase method setupClass.

@Before
public void setupClass() throws Exception {
    System.setProperty("carbon.home", "");
    ServiceReferenceHolder serviceRefHolder = Mockito.mock(ServiceReferenceHolder.class);
    PowerMockito.mockStatic(ServiceReferenceHolder.class);
    PowerMockito.when(ServiceReferenceHolder.getInstance()).thenReturn(serviceRefHolder);
    RealmService realmService = Mockito.mock(RealmService.class);
    PowerMockito.when(serviceRefHolder.getRealmService()).thenReturn(realmService);
    TenantManager tenantManager = Mockito.mock(TenantManager.class);
    PowerMockito.when(realmService.getTenantManager()).thenReturn(tenantManager);
    PowerMockito.when(tenantManager.getTenantId(SUPER_TENANT_DOMAIN)).thenReturn(SUPER_TENANT_ID);
    registry = Mockito.mock(Registry.class);
    PowerMockito.mockStatic(MultitenantUtils.class);
    Resource resource = new ResourceImpl();
    Mockito.when(registry.get(anyString())).thenReturn(resource);
    Tag[] tags = new Tag[1];
    Tag tag = new Tag();
    tag.setTagName("testTag");
    tags[0] = tag;
    Mockito.when(registry.getTags(anyString())).thenReturn(tags);
    PowerMockito.mockStatic(GovernanceUtils.class);
    PowerMockito.mockStatic(PrivilegedCarbonContext.class);
    PrivilegedCarbonContext privilegedContext = Mockito.mock(PrivilegedCarbonContext.class);
    PowerMockito.when(PrivilegedCarbonContext.getThreadLocalCarbonContext()).thenReturn(privilegedContext);
}
Also used : ServiceReferenceHolder(org.wso2.carbon.apimgt.persistence.internal.ServiceReferenceHolder) ResourceImpl(org.wso2.carbon.registry.core.ResourceImpl) RealmService(org.wso2.carbon.user.core.service.RealmService) Resource(org.wso2.carbon.registry.core.Resource) PrivilegedCarbonContext(org.wso2.carbon.context.PrivilegedCarbonContext) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) Registry(org.wso2.carbon.registry.core.Registry) Tag(org.wso2.carbon.registry.core.Tag) TenantManager(org.wso2.carbon.user.core.tenant.TenantManager) Before(org.junit.Before)

Example 18 with Tag

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

the class RegistryPersistenceUtilTestCase method testAPIGet.

@Test
public void testAPIGet() throws APIManagementException, RegistryException, UserStoreException {
    GenericArtifact artifact = PersistenceHelper.getSampleAPIArtifact();
    API api = RegistryPersistenceUtil.getAPI(artifact, registry);
    Assert.assertEquals("Attibute overview_type does not match", artifact.getAttribute("overview_type"), api.getType());
    Assert.assertEquals("API id does not match", artifact.getId(), api.getUuid());
    Assert.assertEquals("API tag does not match", "testTag", api.getTags().iterator().next());
}
Also used : GenericArtifact(org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact) PublisherAPI(org.wso2.carbon.apimgt.persistence.dto.PublisherAPI) API(org.wso2.carbon.apimgt.api.model.API) DevPortalAPI(org.wso2.carbon.apimgt.persistence.dto.DevPortalAPI) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 19 with Tag

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

the class APIProviderImpl method updateApiArtifact.

private String updateApiArtifact(API api, boolean updateMetadata, boolean updatePermissions) throws APIManagementException {
    // Validate Transports
    validateAndSetTransports(api);
    validateAndSetAPISecurity(api);
    boolean transactionCommitted = false;
    String apiUUID = null;
    try {
        registry.beginTransaction();
        String apiArtifactId = registry.get(APIUtil.getAPIPath(api.getId())).getUUID();
        GenericArtifactManager artifactManager = APIUtil.getArtifactManager(registry, APIConstants.API_KEY);
        GenericArtifact artifact = artifactManager.getGenericArtifact(apiArtifactId);
        if (artifactManager == null) {
            String errorMessage = "Artifact manager is null when updating API artifact ID " + api.getId();
            log.error(errorMessage);
            throw new APIManagementException(errorMessage);
        }
        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 = APIUtil.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);
            }
        }
        if (updateMetadata && api.getEndpointConfig() != null && !api.getEndpointConfig().isEmpty()) {
            // If WSDL URL get change only we update registry WSDL resource. If its registry resource patch we
            // will skip registry update. Only if this API created with WSDL end point type we need to update
            // wsdls for each update.
            // check for wsdl endpoint
            org.json.JSONObject response1 = new org.json.JSONObject(api.getEndpointConfig());
            boolean isWSAPI = APIConstants.APITransportType.WS.toString().equals(api.getType());
            String wsdlURL;
            if (!APIUtil.isStreamingApi(api) && "wsdl".equalsIgnoreCase(response1.get("endpoint_type").toString()) && response1.has("production_endpoints")) {
                wsdlURL = response1.getJSONObject("production_endpoints").get("url").toString();
                if (APIUtil.isValidWSDLURL(wsdlURL, true)) {
                    String path = APIUtil.createWSDL(registry, api);
                    if (path != null) {
                        // reset the wsdl path to permlink
                        updateApiArtifact.setAttribute(APIConstants.API_OVERVIEW_WSDL, api.getWsdlUrl());
                    }
                }
            }
        }
        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(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)) {
            APIUtil.notifyAPIStateChangeToAssociatedDocuments(artifact, registry);
        }
        if (updatePermissions) {
            APIUtil.clearResourcePermissions(artifactPath, api.getId(), ((UserRegistry) registry).getTenantId());
            String visibleRolesList = api.getVisibleRoles();
            if (visibleRolesList != null) {
                visibleRoles = visibleRolesList.split(",");
            }
            APIUtil.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());
            }
        }
        registry.commitTransaction();
        transactionCommitted = true;
        apiUUID = updateApiArtifact.getId();
        if (updatePermissions) {
            APIManagerConfiguration config = getAPIManagerConfiguration();
            boolean isSetDocLevelPermissions = Boolean.parseBoolean(config.getFirstProperty(APIConstants.API_PUBLISHER_ENABLE_API_DOC_VISIBILITY_LEVELS));
            String docRootPath = APIUtil.getAPIDocPath(api.getId());
            if (isSetDocLevelPermissions) {
                // Retain the docs
                List<Documentation> docs = getAllDocumentation(api.getId());
                for (Documentation doc : docs) {
                    if ((APIConstants.DOC_API_BASED_VISIBILITY).equalsIgnoreCase(doc.getVisibility().name())) {
                        String documentationPath = APIUtil.getAPIDocPath(api.getId()) + doc.getName();
                        APIUtil.setResourcePermissions(api.getId().getProviderName(), api.getVisibility(), visibleRoles, documentationPath, registry);
                        if (Documentation.DocumentSourceType.INLINE.equals(doc.getSourceType()) || Documentation.DocumentSourceType.MARKDOWN.equals(doc.getSourceType())) {
                            String contentPath = APIUtil.getAPIDocContentPath(api.getId(), doc.getName());
                            APIUtil.setResourcePermissions(api.getId().getProviderName(), api.getVisibility(), visibleRoles, contentPath, registry);
                        } else if (Documentation.DocumentSourceType.FILE.equals(doc.getSourceType()) && doc.getFilePath() != null) {
                            String filePath = APIUtil.getDocumentationFilePath(api.getId(), doc.getFilePath().split("files" + RegistryConstants.PATH_SEPARATOR)[1]);
                            APIUtil.setResourcePermissions(api.getId().getProviderName(), api.getVisibility(), visibleRoles, filePath, registry);
                        }
                    }
                }
            } else {
                APIUtil.setResourcePermissions(api.getId().getProviderName(), api.getVisibility(), visibleRoles, docRootPath, registry);
            }
        } else {
            // In order to support content search feature - we need to update resource permissions of document resources
            // if their visibility is set to API level.
            List<Documentation> docs = getAllDocumentation(api.getId());
            if (docs != null) {
                for (Documentation doc : docs) {
                    if ((APIConstants.DOC_API_BASED_VISIBILITY).equalsIgnoreCase(doc.getVisibility().name())) {
                        String documentationPath = APIUtil.getAPIDocPath(api.getId()) + doc.getName();
                        APIUtil.setResourcePermissions(api.getId().getProviderName(), api.getVisibility(), visibleRoles, documentationPath, registry);
                    }
                }
            }
        }
    } 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);
        }
        handleException("Error while performing registry transaction operation", e);
    } finally {
        try {
            if (!transactionCommitted) {
                registry.rollbackTransaction();
            }
        } catch (RegistryException ex) {
            handleException("Error occurred while rolling back the transaction.", ex);
        }
    }
    return apiUUID;
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) 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) 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) JSONObject(org.json.simple.JSONObject) APICategory(org.wso2.carbon.apimgt.api.model.APICategory)

Example 20 with Tag

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

the class APIConsumerImpl method getPaginatedAPIsWithTag.

/**
 * Returns the set of APIs with the given tag from the taggedAPIs Map.
 *
 * @param tag   The name of the tag
 * @param start The starting index of the return result set
 * @param end   The end index of the return result set
 * @return A {@link Map} of APIs(between the given indexes) and the total number indicating all the available
 * APIs count
 * @throws APIManagementException
 */
@Override
public Map<String, Object> getPaginatedAPIsWithTag(String tag, int start, int end, String tenantDomain) throws APIManagementException {
    List<API> apiList = new ArrayList<API>();
    Set<API> resultSet = new TreeSet<API>(new APIVersionComparator());
    Map<String, Object> results = new HashMap<String, Object>();
    Set<API> taggedAPISet = this.getAPIsWithTag(tag, tenantDomain);
    if (taggedAPISet != null) {
        if (taggedAPISet.size() < end) {
            end = taggedAPISet.size();
        }
        int totalLength;
        apiList.addAll(taggedAPISet);
        totalLength = apiList.size();
        if (totalLength <= ((start + end) - 1)) {
            end = totalLength;
        } else {
            end = start + end;
        }
        for (int i = start; i < end; i++) {
            resultSet.add(apiList.get(i));
        }
        results.put("apis", resultSet);
        results.put("length", taggedAPISet.size());
    } else {
        results.put("apis", null);
        results.put("length", 0);
    }
    return results;
}
Also used : APIVersionComparator(org.wso2.carbon.apimgt.impl.utils.APIVersionComparator) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) TreeSet(java.util.TreeSet) ArrayList(java.util.ArrayList) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) DevPortalAPI(org.wso2.carbon.apimgt.persistence.dto.DevPortalAPI) API(org.wso2.carbon.apimgt.api.model.API) JSONObject(org.json.simple.JSONObject)

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