Search in sources :

Example 46 with Tag

use of org.wso2.carbon.registry.core.Tag in project carbon-apimgt by wso2.

the class RegistryPersistenceImplTestCase method testUpdateAPIProduct.

@Test
public void testUpdateAPIProduct() throws APIPersistenceException, RegistryException, APIManagementException {
    PublisherAPIProduct publisherAPI = new PublisherAPIProduct();
    publisherAPI.setDescription("Modified description");
    APIProduct api = APIProductMapper.INSTANCE.toApiProduct(publisherAPI);
    Registry registry = Mockito.mock(UserRegistry.class);
    Resource resource = new ResourceImpl();
    Mockito.when(registry.get(anyString())).thenReturn(resource);
    Tag[] tags = new Tag[0];
    Mockito.when(registry.getTags(anyString())).thenReturn(tags);
    GenericArtifact existArtifact = PersistenceHelper.getSampleAPIProductArtifact();
    String apiUUID = existArtifact.getId();
    PowerMockito.mockStatic(RegistryPersistenceUtil.class);
    GenericArtifactManager manager = Mockito.mock(GenericArtifactManager.class);
    PowerMockito.when(RegistryPersistenceUtil.getArtifactManager(registry, APIConstants.API_KEY)).thenReturn(manager);
    Mockito.when(manager.getGenericArtifact(apiUUID)).thenReturn(existArtifact);
    Mockito.doNothing().when(manager).updateGenericArtifact(existArtifact);
    PowerMockito.when(RegistryPersistenceUtil.getArtifactManager(registry, APIConstants.API_KEY)).thenReturn(manager);
    GenericArtifact updatedArtifact = PersistenceHelper.getSampleAPIProductArtifact();
    updatedArtifact.setAttribute(APIConstants.API_OVERVIEW_DESCRIPTION, api.getDescription());
    PowerMockito.when(RegistryPersistenceUtil.createAPIProductArtifactContent(any(GenericArtifact.class), any(APIProduct.class))).thenReturn(updatedArtifact);
    Organization org = new Organization(SUPER_TENANT_DOMAIN);
    APIPersistence apiPersistenceInstance = new RegistryPersistenceImplWrapper(registry, existArtifact);
    PublisherAPIProduct updatedAPI = apiPersistenceInstance.updateAPIProduct(org, publisherAPI);
    Assert.assertEquals("Updated API description does not match", "Modified description", updatedAPI.getDescription());
}
Also used : GenericArtifact(org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact) GenericArtifactManager(org.wso2.carbon.governance.api.generic.GenericArtifactManager) Organization(org.wso2.carbon.apimgt.persistence.dto.Organization) Resource(org.wso2.carbon.registry.core.Resource) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) Registry(org.wso2.carbon.registry.core.Registry) Matchers.anyString(org.mockito.Matchers.anyString) PublisherAPIProduct(org.wso2.carbon.apimgt.persistence.dto.PublisherAPIProduct) APIProduct(org.wso2.carbon.apimgt.api.model.APIProduct) ResourceImpl(org.wso2.carbon.registry.core.ResourceImpl) PublisherAPIProduct(org.wso2.carbon.apimgt.persistence.dto.PublisherAPIProduct) Tag(org.wso2.carbon.registry.core.Tag) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 47 with Tag

use of org.wso2.carbon.registry.core.Tag in project carbon-apimgt by wso2.

the class TagMappingUtil method fromTagListToDTO.

/**
 * Converts a List object of Tags into a DTO
 *
 * @param tags  a list of Tag objects
 * @param limit  max number of objects returned
 * @param offset starting index
 * @return TierListDTO object containing TierDTOs
 */
public static TagListDTO fromTagListToDTO(List<Tag> tags, int limit, int offset) {
    TagListDTO tagListDTO = new TagListDTO();
    List<TagDTO> tierDTOs = tagListDTO.getList();
    if (tierDTOs == null) {
        tierDTOs = new ArrayList<>();
        tagListDTO.setList(tierDTOs);
    }
    // identifying the proper start and end indexes
    int size = tags.size();
    int start = offset < size && offset >= 0 ? offset : Integer.MAX_VALUE;
    int end = offset + limit - 1 <= size - 1 ? offset + limit - 1 : size - 1;
    for (int i = start; i <= end; i++) {
        Tag tag = tags.get(i);
        tierDTOs.add(fromTagToDTO(tag));
    }
    tagListDTO.setCount(tierDTOs.size());
    return tagListDTO;
}
Also used : TagListDTO(org.wso2.carbon.apimgt.rest.api.store.v1.dto.TagListDTO) TagDTO(org.wso2.carbon.apimgt.rest.api.store.v1.dto.TagDTO) Tag(org.wso2.carbon.apimgt.api.model.Tag)

Example 48 with Tag

use of org.wso2.carbon.registry.core.Tag in project carbon-apimgt by wso2.

the class APIUtilTest method getTagsFromSet.

private Tag[] getTagsFromSet(Set<String> tagSet) {
    String[] tagNames = tagSet.toArray(new String[tagSet.size()]);
    Tag[] tags = new Tag[tagNames.length];
    for (int i = 0; i < tagNames.length; i++) {
        Tag tag = new Tag();
        tag.setTagName(tagNames[i]);
        tags[i] = tag;
    }
    return tags;
}
Also used : Tag(org.wso2.carbon.registry.core.Tag)

Example 49 with Tag

use of org.wso2.carbon.registry.core.Tag 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 50 with Tag

use of org.wso2.carbon.registry.core.Tag in project carbon-apimgt by wso2.

the class APIConsumerImpl method getAPIsWithTag.

/**
 * Returns the set of APIs with the given tag from the taggedAPIs Map
 *
 * @param tagName The name of the tag
 * @return Set of {@link API} with the given tag
 * @throws APIManagementException
 */
@Override
public Set<API> getAPIsWithTag(String tagName, String requestedTenantDomain) throws APIManagementException {
    /* We keep track of the lastUpdatedTime of the TagCache to determine its freshness.
         */
    long lastUpdatedTimeAtStart = lastUpdatedTimeForTagApi;
    long currentTimeAtStart = System.currentTimeMillis();
    if (isTagCacheEnabled && ((currentTimeAtStart - lastUpdatedTimeAtStart) < tagCacheValidityTime)) {
        if (taggedAPIs != null && taggedAPIs.containsKey(tagName)) {
            return taggedAPIs.get(tagName);
        }
    } else {
        synchronized (tagWithAPICacheMutex) {
            lastUpdatedTimeForTagApi = System.currentTimeMillis();
            taggedAPIs = new ConcurrentHashMap<String, Set<API>>();
        }
    }
    boolean isTenantMode = requestedTenantDomain != null && !"null".equalsIgnoreCase(requestedTenantDomain);
    this.isTenantModeStoreView = isTenantMode;
    if (requestedTenantDomain != null && !"null".equals(requestedTenantDomain)) {
        this.requestedTenant = requestedTenantDomain;
    }
    Registry userRegistry;
    boolean isTenantFlowStarted = false;
    Set<API> apisWithTag = null;
    try {
        // start the tenant flow prior to loading registry
        if (requestedTenant != null && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(requestedTenant)) {
            isTenantFlowStarted = startTenantFlowForTenantDomain(requestedTenantDomain);
        }
        if ((isTenantMode && this.tenantDomain == null) || (isTenantMode && isTenantDomainNotMatching(requestedTenantDomain))) {
            // Tenant store anonymous mode
            int tenantId = getTenantId(requestedTenantDomain);
            // explicitly load the tenant's registry
            APIUtil.loadTenantRegistry(tenantId);
            userRegistry = getGovernanceUserRegistry(tenantId);
            setUsernameToThreadLocalCarbonContext(CarbonConstants.REGISTRY_ANONNYMOUS_USERNAME);
        } else {
            userRegistry = registry;
            setUsernameToThreadLocalCarbonContext(this.username);
        }
        apisWithTag = getAPIsWithTag(userRegistry, tagName);
        /* Add the APIs against the tag name */
        if (!apisWithTag.isEmpty()) {
            if (taggedAPIs.containsKey(tagName)) {
                for (API api : apisWithTag) {
                    taggedAPIs.get(tagName).add(api);
                }
            } else {
                taggedAPIs.putIfAbsent(tagName, apisWithTag);
            }
        }
    } catch (RegistryException e) {
        handleException("Failed to get api by the tag", e);
    } catch (UserStoreException e) {
        handleException("Failed to get api by the tag", e);
    } finally {
        if (isTenantFlowStarted) {
            endTenantFlow();
        }
    }
    return apisWithTag;
}
Also used : Set(java.util.Set) TreeSet(java.util.TreeSet) LinkedHashSet(java.util.LinkedHashSet) SortedSet(java.util.SortedSet) HashSet(java.util.HashSet) UserStoreException(org.wso2.carbon.user.api.UserStoreException) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) DevPortalAPI(org.wso2.carbon.apimgt.persistence.dto.DevPortalAPI) API(org.wso2.carbon.apimgt.api.model.API) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) Registry(org.wso2.carbon.registry.core.Registry) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException)

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