org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact Java Examples

The following examples show how to use org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: APIConsumerImplTest.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetTopRatedAPIs() throws APIManagementException, RegistryException {
    Registry userRegistry = Mockito.mock(Registry.class);
    APIConsumerImpl apiConsumer = new APIConsumerImplWrapper(userRegistry, apiMgtDAO);
    GenericArtifactManager artifactManager = Mockito.mock(GenericArtifactManager.class);
    PowerMockito.when(APIUtil.getArtifactManager((UserRegistry)(Mockito.anyObject()), Mockito.anyString())).
            thenReturn(artifactManager);
    GenericArtifact artifact = Mockito.mock(GenericArtifact.class);
    GenericArtifact[] genericArtifacts = new GenericArtifact[]{artifact};
    Mockito.when(artifactManager.getAllGenericArtifacts()).thenReturn(genericArtifacts);
    Mockito.when(artifact.getAttribute(Mockito.anyString())).thenReturn("PUBLISHED");
    Mockito.when(artifact.getPath()).thenReturn("testPath");

    Mockito.when(userRegistry.getAverageRating("testPath")).thenReturn((float)20.0);
    APIIdentifier apiId1 = new APIIdentifier("admin", "API1", "1.0.0");
    API api = new API(apiId1);
    Mockito.when(APIUtil.getAPI(artifact, userRegistry)).thenReturn(api);
    assertNotNull(apiConsumer.getTopRatedAPIs(10));
}
 
Example #2
Source File: APIConsumerImplTest.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetPublishedAPIsByProvider() throws APIManagementException, RegistryException {
    Registry userRegistry = Mockito.mock(Registry.class);
    APIConsumerImpl apiConsumer = new APIConsumerImplWrapper(userRegistry, apiMgtDAO);
    PowerMockito.when(APIUtil.isAllowDisplayMultipleVersions()).thenReturn(true, false);
    PowerMockito.when(APIUtil.isAllowDisplayAPIsWithMultipleStatus()).thenReturn(true, false);
    GenericArtifactManager artifactManager = Mockito.mock(GenericArtifactManager.class);
    PowerMockito.when(APIUtil.getArtifactManager((UserRegistry)(Mockito.anyObject()), Mockito.anyString())).
            thenReturn(artifactManager);
    Association association = Mockito.mock(Association.class);
    Association[] associations = new Association[]{association};
    Mockito.when(userRegistry.getAssociations(Mockito.anyString(), Mockito.anyString())).thenReturn(associations);
    Mockito.when(association.getDestinationPath()).thenReturn("testPath");
    Resource resource = Mockito.mock(Resource.class);
    Mockito.when(userRegistry.get("testPath")).thenReturn(resource);
    Mockito.when(resource.getUUID()).thenReturn("testID");
    GenericArtifact genericArtifact = Mockito.mock(GenericArtifact.class);
    Mockito.when(artifactManager.getGenericArtifact(Mockito.anyString())).thenReturn(genericArtifact);
    Mockito.when(genericArtifact.getAttribute("overview_status")).thenReturn("PUBLISHED");
    APIIdentifier apiId1 = new APIIdentifier("admin", "API1", "1.0.0");
    API api = new API(apiId1);
    Mockito.when(APIUtil.getAPI(genericArtifact)).thenReturn(api);
    assertNotNull(apiConsumer.getPublishedAPIsByProvider("testID", 10));
    assertNotNull(apiConsumer.getPublishedAPIsByProvider("testID", 10));
}
 
Example #3
Source File: APIKeyMgtUtil.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * This returns API object for given APIIdentifier. Reads from registry entry for given APIIdentifier
 * creates API object
 *
 * @param identifier APIIdentifier object for the API
 * @return API object for given identifier
 * @throws APIManagementException on error in getting API artifact
 */
public static API getAPI(APIIdentifier identifier) throws APIManagementException {
    String apiPath = APIUtil.getAPIPath(identifier);

    try {
        Registry registry = APIKeyMgtDataHolder.getRegistryService().getGovernanceSystemRegistry();
        GenericArtifactManager artifactManager = APIUtil.getArtifactManager(registry,
                APIConstants.API_KEY);
        if (artifactManager == null) {
            String errorMessage = "Artifact manager is null when retrieving API " + identifier.getApiName();
            log.error(errorMessage);
            throw new APIManagementException(errorMessage);
        }
        Resource apiResource = registry.get(apiPath);
        String artifactId = apiResource.getUUID();
        if (artifactId == null) {
            throw new APIManagementException("artifact id is null for : " + apiPath);
        }
        GenericArtifact apiArtifact = artifactManager.getGenericArtifact(artifactId);
        return APIUtil.getAPI(apiArtifact, registry);

    } catch (RegistryException e) {
        return null;
    }
}
 
Example #4
Source File: RegistryBasedLicenseManager.java    From carbon-device-mgt with Apache License 2.0 6 votes vote down vote up
private License populateLicense(GenericArtifact artifact) throws GovernanceException, ParseException {
    License license = new License();
    license.setName(artifact.getAttribute(DeviceManagementConstants.LicenseProperties.NAME));
    license.setProvider(artifact.getAttribute(DeviceManagementConstants.LicenseProperties.PROVIDER));
    license.setVersion(artifact.getAttribute(DeviceManagementConstants.LicenseProperties.VERSION));
    license.setLanguage(artifact.getAttribute(DeviceManagementConstants.LicenseProperties.LANGUAGE));
    license.setText(artifact.getAttribute(DeviceManagementConstants.LicenseProperties.TEXT));

    DateFormat format = new SimpleDateFormat("dd-mm-yyyy", Locale.ENGLISH);
    String validFrom = artifact.getAttribute(DeviceManagementConstants.LicenseProperties.VALID_FROM);
    if (validFrom != null && !validFrom.isEmpty()) {
        license.setValidFrom(format.parse(validFrom));
    }
    String validTo = artifact.getAttribute(DeviceManagementConstants.LicenseProperties.VALID_TO);
    if (validTo != null && !validTo.isEmpty()) {
        license.setValidFrom(format.parse(validTo));
    }
    return license;
}
 
Example #5
Source File: APIConsumerImplTest.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetAllPublishedAPIs() throws APIManagementException, GovernanceException {
    APIConsumerImpl apiConsumer = new APIConsumerImplWrapper();
    APINameComparator apiNameComparator = Mockito.mock(APINameComparator.class);
    SortedSet<API> apiSortedSet = new TreeSet<API>(apiNameComparator);
    GenericArtifactManager artifactManager = Mockito.mock(GenericArtifactManager.class);
    PowerMockito.when(APIUtil.getArtifactManager(apiConsumer.registry, APIConstants.API_KEY)).
            thenReturn(artifactManager);
    GenericArtifact artifact = Mockito.mock(GenericArtifact.class);
    GenericArtifact[] genericArtifacts = new GenericArtifact[]{artifact};
    APIIdentifier apiId1 = new APIIdentifier(API_PROVIDER, SAMPLE_API_NAME, SAMPLE_API_VERSION);
    API api = new API(apiId1);

    Mockito.when(artifactManager.getAllGenericArtifacts()).thenReturn(genericArtifacts);
    Mockito.when(artifact.getAttribute(APIConstants.API_OVERVIEW_STATUS)).thenReturn("PUBLISHED");
    Mockito.when(APIUtil.getAPI(artifact)).thenReturn(api);

    Map<String, API> latestPublishedAPIs = new HashMap<String, API>();
    latestPublishedAPIs.put("user:key", api);
    apiSortedSet.addAll(latestPublishedAPIs.values());
    assertNotNull(apiConsumer.getAllPublishedAPIs("testDomain"));
}
 
Example #6
Source File: APIConsumerImplTest.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetAPIsWithTag() throws Exception {
    APIConsumerImpl apiConsumer = new APIConsumerImplWrapper();
    PowerMockito.doNothing().when(APIUtil.class, "loadTenantRegistry", Mockito.anyInt());
    PowerMockito.mockStatic(GovernanceUtils.class);
    GenericArtifactManager artifactManager = Mockito.mock(GenericArtifactManager.class);
    PowerMockito.when(APIUtil.getArtifactManager(apiConsumer.registry, APIConstants.API_KEY)).
            thenReturn(artifactManager);
    List<GovernanceArtifact> governanceArtifacts = new ArrayList<GovernanceArtifact>();
    GenericArtifact artifact = Mockito.mock(GenericArtifact.class);
    governanceArtifacts.add(artifact);
    Mockito.when(GovernanceUtils.findGovernanceArtifacts(Mockito.anyString(),(UserRegistry)Mockito.anyObject(),
            Mockito.anyString())).thenReturn(governanceArtifacts);
    APIIdentifier apiId1 = new APIIdentifier("admin", "API1", "1.0.0");
    API api = new API(apiId1);
    Mockito.when(APIUtil.getAPI(artifact)).thenReturn(api);
    Mockito.when(artifact.getAttribute("overview_status")).thenReturn("PUBLISHED");
    assertNotNull(apiConsumer.getAPIsWithTag("testTag", "testDomain"));
}
 
Example #7
Source File: AbstractAPIManager.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
public APIProduct getAPIProduct(String productPath) throws APIManagementException {
    try {
        GenericArtifactManager artifactManager = getAPIGenericArtifactManagerFromUtil(registry,
                APIConstants.API_KEY);
        Resource productResource = registry.get(productPath);
        String artifactId = productResource.getUUID();
        if (artifactId == null) {
            throw new APIManagementException("artifact id is null for : " + productPath);
        }
        GenericArtifact productArtifact = artifactManager.getGenericArtifact(artifactId);
        return APIUtil.getAPIProduct(productArtifact, registry);

    } catch (RegistryException e) {
        String msg = "Failed to get API Product from : " + productPath;
        throw new APIManagementException(msg, e);
    }
}
 
Example #8
Source File: RegistryForumManager.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * Return the registry resources ratings for the given topic resource.
 * @param topicId Id of the topic which the ratings should be returned of.
 * @param username Username
 * @param tenantDomain Tenant domain.
 * @return User rating if the user is signed in, and average rating.
 * @throws ForumException
 */
@Override
public Map<String, Object> getRating(String topicId, String username, String tenantDomain) throws ForumException {

    Map<String, Object> rating = new HashMap<String, Object>();

    try {
        Registry registry = getRegistry(username, tenantDomain);
        GenericArtifactManager artifactManager = getArtifactManager(registry, TOPIC_RXT_KEY);
        GenericArtifact genericArtifact = artifactManager.getGenericArtifact(topicId);

        // Get the user rating.
        if(username != null){
            rating.put("userRating", registry.getRating(genericArtifact.getPath(), username));
        }

        // Get average rating.
        rating.put("averageRating", registry.getAverageRating(genericArtifact.getPath()));

        return rating;

    } catch (RegistryException e) {
        throw new ForumException(String.format("Cannot get rating for the topic id : '%s'", topicId), e);
    }

}
 
Example #9
Source File: AbstractAPIManager.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
public API getAPI(APIIdentifier identifier, APIIdentifier oldIdentifier, String oldContext) throws
        APIManagementException {
    String apiPath = APIUtil.getAPIPath(identifier);
    try {
        GenericArtifactManager artifactManager = getAPIGenericArtifactManagerFromUtil(registry,
                APIConstants.API_KEY);
        Resource apiResource = registry.get(apiPath);
        String artifactId = apiResource.getUUID();
        if (artifactId == null) {
            throw new APIManagementException("artifact id is null for : " + apiPath);
        }
        GenericArtifact apiArtifact = artifactManager.getGenericArtifact(artifactId);
        return APIUtil.getAPI(apiArtifact, registry, oldIdentifier, oldContext);

    } catch (RegistryException e) {
        String msg = "Failed to get API from : " + apiPath;
        throw new APIManagementException(msg, e);
    }
}
 
Example #10
Source File: CustomAPIIndexerTest.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * This method checks the indexer's behaviour for APIs which does not have the relevant custom properties.
 *
 * @throws RegistryException Registry Exception.
 * @throws APIManagementException API Management Exception.
 */
@Test
public void testIndexingCustomProperties() throws RegistryException, APIManagementException {
    Resource resource = new ResourceImpl();
    PowerMockito.mockStatic(APIUtil.class);
    Mockito.doReturn(resource).when(userRegistry).get(Mockito.anyString());
    GenericArtifactManager artifactManager = Mockito.mock(GenericArtifactManager.class);
    GenericArtifact genericArtifact = Mockito.mock(GenericArtifact.class);
    PowerMockito.when(APIUtil.getArtifactManager((UserRegistry)(Mockito.anyObject()), Mockito.anyString())).
            thenReturn(artifactManager);
    Mockito.when(artifactManager.getGenericArtifact(Mockito.anyString())).thenReturn(genericArtifact);
    Mockito.when(genericArtifact.getAttribute(APIConstants.API_OVERVIEW_VISIBILITY)).thenReturn("public");
    PowerMockito.when(APIUtil.getAPI(genericArtifact, userRegistry))
            .thenReturn(Mockito.mock(API.class));
    resource.setProperty(APIConstants.API_RELATED_CUSTOM_PROPERTIES_PREFIX + APIConstants.
            CUSTOM_API_INDEXER_PROPERTY, APIConstants.CUSTOM_API_INDEXER_PROPERTY);
    Assert.assertEquals(APIConstants.OVERVIEW_PREFIX + APIConstants.API_RELATED_CUSTOM_PROPERTIES_PREFIX +
            APIConstants.CUSTOM_API_INDEXER_PROPERTY, indexer.getIndexedDocument(file2Index).getFields().keySet().
            toArray()[0].toString());
}
 
Example #11
Source File: DocumentIndexer.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * Fetch api status and access control details to document artifacts
 *
 * @param registry
 * @param documentResource
 * @param fields
 * @throws RegistryException
 * @throws APIManagementException
 */
private void fetchRequiredDetailsFromAssociatedAPI(Registry registry, Resource documentResource,
        Map<String, List<String>> fields) throws RegistryException, APIManagementException {
    Association apiAssociations[] = registry
            .getAssociations(documentResource.getPath(), APIConstants.DOCUMENTATION_ASSOCIATION);

    //a document can have one api association
    Association apiAssociation = apiAssociations[0];
    String apiPath = apiAssociation.getSourcePath();

    if (registry.resourceExists(apiPath)) {
        Resource apiResource = registry.get(apiPath);
        GenericArtifactManager apiArtifactManager = APIUtil.getArtifactManager(registry, APIConstants.API_KEY);
        GenericArtifact apiArtifact = apiArtifactManager.getGenericArtifact(apiResource.getUUID());
        String apiStatus = apiArtifact.getAttribute(APIConstants.API_OVERVIEW_STATUS).toLowerCase();
        String publisherRoles = apiResource.getProperty(APIConstants.PUBLISHER_ROLES);
        fields.put(APIConstants.API_OVERVIEW_STATUS, Arrays.asList(apiStatus));
        fields.put(APIConstants.PUBLISHER_ROLES, Arrays.asList(publisherRoles));
    } else {
        log.warn("API does not exist at " + apiPath);
    }
}
 
Example #12
Source File: CustomAPIIndexerTest.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * This method checks the indexer's behaviour for new APIs which does not have the relevant properties.
 *
 * @throws RegistryException Registry Exception.
 * @throws APIManagementException API Management Exception.
 */
@Test
public void testIndexDocumentForNewAPI() throws APIManagementException, RegistryException {
    Resource resource = new ResourceImpl();
    PowerMockito.mockStatic(APIUtil.class);
    GenericArtifactManager artifactManager = Mockito.mock(GenericArtifactManager.class);
    PowerMockito.when(APIUtil.getArtifactManager((UserRegistry)(Mockito.anyObject()), Mockito.anyString())).
            thenReturn(artifactManager);
    GenericArtifact genericArtifact = Mockito.mock(GenericArtifact.class);
    Mockito.when(artifactManager.getGenericArtifact(Mockito.anyString())).thenReturn(genericArtifact);
    Mockito.when(genericArtifact.getAttribute(APIConstants.API_OVERVIEW_VISIBILITY)).thenReturn("public");
    PowerMockito.when(APIUtil.getAPI(genericArtifact, userRegistry))
            .thenReturn(Mockito.mock(API.class));
    resource.setProperty(APIConstants.ACCESS_CONTROL, APIConstants.NO_ACCESS_CONTROL);
    resource.setProperty(APIConstants.PUBLISHER_ROLES, APIConstants.NULL_USER_ROLE_LIST);
    resource.setProperty(APIConstants.STORE_VIEW_ROLES, APIConstants.NULL_USER_ROLE_LIST);
    Mockito.doReturn(resource).when(userRegistry).get(Mockito.anyString());
    indexer.getIndexedDocument(file2Index);
    Assert.assertNull(APIConstants.CUSTOM_API_INDEXER_PROPERTY + " property was set for the API which does not "
            + "require migration", resource.getProperty(APIConstants.CUSTOM_API_INDEXER_PROPERTY));
}
 
Example #13
Source File: AbstractAPIManager.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
public Documentation getDocumentation(APIIdentifier apiId, DocumentationType docType,
                                      String docName) throws APIManagementException {
    Documentation documentation = null;
    String docPath = APIUtil.getAPIDocPath(apiId) + docName;
    GenericArtifactManager artifactManager = getAPIGenericArtifactManagerFromUtil(registry,
            APIConstants.DOCUMENTATION_KEY);
    try {
        Resource docResource = registry.get(docPath);
        GenericArtifact artifact = artifactManager.getGenericArtifact(docResource.getUUID());
        documentation = APIUtil.getDocumentation(artifact);
    } catch (RegistryException e) {
        String msg = "Failed to get documentation details";
        throw new APIManagementException(msg, e);
    }
    return documentation;
}
 
Example #14
Source File: AbstractAPIManager.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
public API getAPI(String apiPath) throws APIManagementException {
    try {
        GenericArtifactManager artifactManager = getAPIGenericArtifactManagerFromUtil(registry,
                APIConstants.API_KEY);
        Resource apiResource = registry.get(apiPath);
        String artifactId = apiResource.getUUID();
        if (artifactId == null) {
            throw new APIManagementException("artifact id is null for : " + apiPath);
        }
        GenericArtifact apiArtifact = artifactManager.getGenericArtifact(artifactId);
        return getApi(apiArtifact);

    } catch (RegistryException e) {
        String msg = "Failed to get API from : " + apiPath;
        throw new APIManagementException(msg, e);
    }
}
 
Example #15
Source File: APIUtilTest.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetDocumentation() throws GovernanceException, APIManagementException {
    PowerMockito.mockStatic(CarbonUtils.class);
    ServerConfiguration serverConfiguration = Mockito.mock(ServerConfiguration.class);
    Mockito.when(serverConfiguration.getFirstProperty("WebContextRoot")).thenReturn("/abc").thenReturn("/");
    PowerMockito.when(CarbonUtils.getServerConfiguration()).thenReturn(serverConfiguration);
    GenericArtifact genericArtifact = Mockito.mock(GenericArtifact.class);
    Mockito.when(genericArtifact.getAttribute(APIConstants.DOC_TYPE)).thenReturn(DocumentationType.HOWTO.getType
            ()).thenReturn(DocumentationType.PUBLIC_FORUM.getType()).thenReturn(DocumentationType.SUPPORT_FORUM
            .getType()).thenReturn(DocumentationType.API_MESSAGE_FORMAT.getType()).thenReturn(DocumentationType
            .SAMPLES.getType()).thenReturn(DocumentationType.OTHER.getType());
    Mockito.when(genericArtifact.getAttribute(APIConstants.DOC_NAME)).thenReturn("Docname");
    Mockito.when(genericArtifact.getAttribute(APIConstants.DOC_VISIBILITY)).thenReturn(null).thenReturn
            (Documentation.DocumentVisibility.API_LEVEL.name()).thenReturn(Documentation.DocumentVisibility
            .PRIVATE.name()).thenReturn(Documentation.DocumentVisibility.OWNER_ONLY.name());
    Mockito.when(genericArtifact.getAttribute(APIConstants.DOC_SOURCE_TYPE)).thenReturn(Documentation
            .DocumentSourceType.URL.name()).thenReturn(Documentation.DocumentSourceType.FILE.name());
    Mockito.when(genericArtifact.getAttribute(APIConstants.DOC_SOURCE_URL)).thenReturn("https://localhost");
    Mockito.when(genericArtifact.getAttribute(APIConstants.DOC_FILE_PATH)).thenReturn("file://abc");
    Mockito.when(genericArtifact.getAttribute(APIConstants.DOC_OTHER_TYPE_NAME)).thenReturn("abc");
    APIUtil.getDocumentation(genericArtifact);
    APIUtil.getDocumentation(genericArtifact);
    APIUtil.getDocumentation(genericArtifact);
    APIUtil.getDocumentation(genericArtifact);
    APIUtil.getDocumentation(genericArtifact);
    APIUtil.getDocumentation(genericArtifact);

}
 
Example #16
Source File: APIUtilTest.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateAPIArtifactContent() throws Exception {
    System.setProperty("carbon.home", APIUtilTest.class.getResource("/").getFile());
    try {
        PrivilegedCarbonContext.startTenantFlow();
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(MultitenantConstants
                .SUPER_TENANT_DOMAIN_NAME);
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(MultitenantConstants.SUPER_TENANT_ID);
        GenericArtifact genericArtifact = Mockito.mock(GenericArtifact.class);
        API api = getUniqueAPI();
        Mockito.when(genericArtifact.getAttributeKeys()).thenReturn(new String[] {"URITemplate"}).thenThrow
                (GovernanceException.class);
        ApiMgtDAO apiMgtDAO = Mockito.mock(ApiMgtDAO.class);
        PowerMockito.mockStatic(ApiMgtDAO.class);
        Mockito.when(ApiMgtDAO.getInstance()).thenReturn(apiMgtDAO);
        Mockito.when(apiMgtDAO.getAllLabels(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME))
                .thenReturn(new ArrayList<Label>());
        APIUtil.createAPIArtifactContent(genericArtifact, api);
        Assert.assertTrue(true);
        APIUtil.createAPIArtifactContent(genericArtifact, api);
        Assert.fail();
    } catch (APIManagementException ex) {
        Assert.assertTrue(ex.getMessage().contains("Failed to create API for :"));
    } finally {
        PrivilegedCarbonContext.endTenantFlow();
    }

}
 
Example #17
Source File: APIConsumerImplTest.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetAllPaginatedPublishedLightWeightAPIs() throws Exception {
    APIConsumerImpl apiConsumer = new APIConsumerImplWrapper();
    PowerMockito.doNothing().when(APIUtil.class, "loadTenantRegistry", Mockito.anyInt());
    PowerMockito.when(APIUtil.isAllowDisplayMultipleVersions()).thenReturn(false, true);
    System.setProperty(CARBON_HOME, "");

    GenericArtifactManager artifactManager = Mockito.mock(GenericArtifactManager.class);
    PowerMockito.when(APIUtil.getArtifactManager(apiConsumer.registry, APIConstants.API_KEY)).
            thenReturn(artifactManager);
    GenericArtifact artifact = Mockito.mock(GenericArtifact.class);
    GenericArtifact[] genericArtifacts = new GenericArtifact[]{artifact};
    Mockito.when(artifactManager.findGenericArtifacts(Mockito.anyMap())).thenReturn(genericArtifacts);
    APIIdentifier apiId1 = new APIIdentifier("admin", "API1", "1.0.0");
    API api = new API(apiId1);
    Mockito.when(APIUtil.getLightWeightAPI(artifact)).thenReturn(api);
    assertNotNull(apiConsumer.getAllPaginatedPublishedLightWeightAPIs(MultitenantConstants
            .SUPER_TENANT_DOMAIN_NAME, 0, 10));
    assertNotNull(apiConsumer.getAllPaginatedPublishedLightWeightAPIs(MultitenantConstants
            .SUPER_TENANT_DOMAIN_NAME, 0, 10));

    //artifact manager null path
    PowerMockito.when(APIUtil.getArtifactManager((UserRegistry)(Mockito.anyObject()), Mockito.anyString())).
            thenReturn(null);
    assertNotNull(apiConsumer.getAllPaginatedPublishedLightWeightAPIs(MultitenantConstants
            .SUPER_TENANT_DOMAIN_NAME, 0, 10));

    //generic artifact null path
    PowerMockito.when(APIUtil.getArtifactManager((UserRegistry)(Mockito.anyObject()), Mockito.anyString())).
            thenReturn(artifactManager);
    Mockito.when(artifactManager.findGenericArtifacts(Mockito.anyMap())).thenReturn(null);
    assertNotNull(apiConsumer.getAllPaginatedPublishedLightWeightAPIs(MultitenantConstants
            .SUPER_TENANT_DOMAIN_NAME, 0, 10));
}
 
Example #18
Source File: APIUtilTest.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetDocumentationByDocCreator() throws Exception {
    PowerMockito.mockStatic(CarbonUtils.class);
    ServerConfiguration serverConfiguration = Mockito.mock(ServerConfiguration.class);
    Mockito.when(serverConfiguration.getFirstProperty("WebContextRoot")).thenReturn("/abc").thenReturn("/");
    PowerMockito.when(CarbonUtils.getServerConfiguration()).thenReturn(serverConfiguration);
    GenericArtifact genericArtifact = Mockito.mock(GenericArtifact.class);
    Mockito.when(genericArtifact.getAttribute(APIConstants.DOC_TYPE)).thenReturn(DocumentationType.HOWTO.getType
            ()).thenReturn(DocumentationType.PUBLIC_FORUM.getType()).thenReturn(DocumentationType.SUPPORT_FORUM
            .getType()).thenReturn(DocumentationType.API_MESSAGE_FORMAT.getType()).thenReturn(DocumentationType
            .SAMPLES.getType()).thenReturn(DocumentationType.OTHER.getType());
    Mockito.when(genericArtifact.getAttribute(APIConstants.DOC_NAME)).thenReturn("Docname");
    Mockito.when(genericArtifact.getAttribute(APIConstants.DOC_VISIBILITY)).thenReturn(null).thenReturn
            (Documentation.DocumentVisibility.API_LEVEL.name()).thenReturn(Documentation.DocumentVisibility
            .PRIVATE.name()).thenReturn(Documentation.DocumentVisibility.OWNER_ONLY.name());
    Mockito.when(genericArtifact.getAttribute(APIConstants.DOC_SOURCE_TYPE)).thenReturn(Documentation
            .DocumentSourceType.URL.name()).thenReturn(Documentation.DocumentSourceType.FILE.name());
    Mockito.when(genericArtifact.getAttribute(APIConstants.DOC_SOURCE_URL)).thenReturn("https://localhost");
    Mockito.when(genericArtifact.getAttribute(APIConstants.DOC_FILE_PATH)).thenReturn("file://abc");
    Mockito.when(genericArtifact.getAttribute(APIConstants.DOC_OTHER_TYPE_NAME)).thenReturn("abc");
    APIUtil.getDocumentation(genericArtifact, "admin");
    APIUtil.getDocumentation(genericArtifact, "admin");
    APIUtil.getDocumentation(genericArtifact, "admin");
    APIUtil.getDocumentation(genericArtifact, "admin");
    APIUtil.getDocumentation(genericArtifact, "admin");
    APIUtil.getDocumentation(genericArtifact, "admin");
    APIUtil.getDocumentation(genericArtifact, "[email protected]");
}
 
Example #19
Source File: APIUtilTest.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Test
public void testVisibilityOfDoc() throws Exception {
    PowerMockito.mockStatic(CarbonUtils.class);
    ServerConfiguration serverConfiguration = Mockito.mock(ServerConfiguration.class);
    Mockito.when(serverConfiguration.getFirstProperty("WebContextRoot")).thenReturn("/abc").thenReturn("/");
    PowerMockito.when(CarbonUtils.getServerConfiguration()).thenReturn(serverConfiguration);
    GenericArtifact genericArtifact = Mockito.mock(GenericArtifact.class);
    Mockito.when(genericArtifact.getAttribute(APIConstants.DOC_TYPE)).thenReturn(DocumentationType.HOWTO.getType
            ()).thenReturn(DocumentationType.PUBLIC_FORUM.getType()).thenReturn(DocumentationType.SUPPORT_FORUM
            .getType()).thenReturn(DocumentationType.API_MESSAGE_FORMAT.getType()).thenReturn(DocumentationType
            .SAMPLES.getType()).thenReturn(DocumentationType.OTHER.getType());
    Mockito.when(genericArtifact.getAttribute(APIConstants.DOC_NAME)).thenReturn("Docname");
    Mockito.when(genericArtifact.getAttribute(APIConstants.DOC_SOURCE_TYPE)).thenReturn(Documentation
            .DocumentSourceType.URL.name()).thenReturn(Documentation.DocumentSourceType.FILE.name());
    Mockito.when(genericArtifact.getAttribute(APIConstants.DOC_SOURCE_URL)).thenReturn("https://localhost");
    Mockito.when(genericArtifact.getAttribute(APIConstants.DOC_FILE_PATH)).thenReturn("file://abc");
    Mockito.when(genericArtifact.getAttribute(APIConstants.DOC_OTHER_TYPE_NAME)).thenReturn("abc");

    Mockito.when(genericArtifact.getAttribute(APIConstants.DOC_VISIBILITY)).thenReturn(null);
    Assert.assertEquals(APIUtil.getDocumentation(genericArtifact, "[email protected]").getVisibility()
            .name(), Documentation.DocumentVisibility.API_LEVEL.name());

    Mockito.when(genericArtifact.getAttribute(APIConstants.DOC_VISIBILITY)).
            thenReturn(Documentation.DocumentVisibility.API_LEVEL.name());
    Assert.assertEquals(APIUtil.getDocumentation(genericArtifact, "[email protected]").getVisibility().
            name(), Documentation.DocumentVisibility.API_LEVEL.name());

    Mockito.when(genericArtifact.getAttribute(APIConstants.DOC_VISIBILITY)).
            thenReturn(Documentation.DocumentVisibility.PRIVATE.name());
    Assert.assertEquals(APIUtil.getDocumentation(genericArtifact, "[email protected]").getVisibility().
            name(), Documentation.DocumentVisibility.PRIVATE.name());

    Mockito.when(genericArtifact.getAttribute(APIConstants.DOC_VISIBILITY)).
            thenReturn(Documentation.DocumentVisibility.OWNER_ONLY.name());
    Assert.assertEquals(APIUtil.getDocumentation(genericArtifact, "[email protected]").getVisibility().
            name(), Documentation.DocumentVisibility.OWNER_ONLY.name());
}
 
Example #20
Source File: APIUtilTest.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateDocArtifactContent() throws GovernanceException, APIManagementException {
    API api = getUniqueAPI();
    PowerMockito.mockStatic(CarbonUtils.class);
    ServerConfiguration serverConfiguration = Mockito.mock(ServerConfiguration.class);
    Mockito.when(serverConfiguration.getFirstProperty("WebContextRoot")).thenReturn("/abc").thenReturn("/");
    PowerMockito.when(CarbonUtils.getServerConfiguration()).thenReturn(serverConfiguration);
    GenericArtifact genericArtifact = Mockito.mock(GenericArtifact.class);
    Documentation documentation = new Documentation(DocumentationType.HOWTO, "this is a doc");
    documentation.setSourceType(Documentation.DocumentSourceType.FILE);
    documentation.setCreatedDate(new Date(System.currentTimeMillis()));
    documentation.setSummary("abcde");
    documentation.setVisibility(Documentation.DocumentVisibility.API_LEVEL);
    documentation.setSourceUrl("/abcd/def");
    documentation.setOtherTypeName("aa");
    APIUtil.createDocArtifactContent(genericArtifact, api.getId(), documentation);
    documentation.setSourceType(Documentation.DocumentSourceType.INLINE);
    APIUtil.createDocArtifactContent(genericArtifact, api.getId(), documentation);
    documentation.setSourceType(Documentation.DocumentSourceType.URL);
    APIUtil.createDocArtifactContent(genericArtifact, api.getId(), documentation);

    try {
        documentation.setSourceType(Documentation.DocumentSourceType.URL);
        Mockito.doThrow(GovernanceException.class).when(genericArtifact).setAttribute(APIConstants
                .DOC_SOURCE_URL, documentation.getSourceUrl());
        APIUtil.createDocArtifactContent(genericArtifact, api.getId(), documentation);
        Assert.fail();
    } catch (APIManagementException ex) {
        Assert.assertTrue(ex.getMessage().contains("Failed to create doc artifact content from :"));
    }
}
 
Example #21
Source File: AbstractAPIManagerTestCase.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetAllApis() throws GovernanceException, APIManagementException {
    PowerMockito.mockStatic(APIUtil.class);
    APIIdentifier identifier = getAPIIdentifier(SAMPLE_API_NAME, API_PROVIDER, SAMPLE_API_VERSION);
    API api = new API(identifier);

    GenericArtifact[] genericArtifacts = new GenericArtifact[1];
    GenericArtifact genericArtifact = getGenericArtifact(SAMPLE_API_NAME, API_PROVIDER, SAMPLE_API_VERSION,
            "sample");
    genericArtifacts[0] = genericArtifact;
    Mockito.when(genericArtifactManager.getAllGenericArtifacts()).thenThrow(RegistryException.class)
            .thenReturn(genericArtifacts);
    AbstractAPIManager abstractAPIManager = new AbstractAPIManagerWrapper(genericArtifactManager);
    abstractAPIManager.tenantDomain = SAMPLE_TENANT_DOMAIN;
    try {
        abstractAPIManager.getAllAPIs(); //error scenario
        Assert.fail("Registry exception not thrown for error scenario");
    } catch (APIManagementException e) {
        Assert.assertTrue(e.getMessage().contains("Failed to get APIs from the registry"));
    }
    PowerMockito.when(APIUtil.getAPI((GenericArtifact)Mockito.any())).thenThrow(APIManagementException.class)
            .thenReturn(api);
    Assert.assertEquals(abstractAPIManager.getAllAPIs().size(),0);
    abstractAPIManager.tenantDomain = SAMPLE_TENANT_DOMAIN_1;
    List<API> apis = abstractAPIManager.getAllAPIs();
    Assert.assertNotNull(apis);
    Assert.assertEquals(apis.size(), 1);

}
 
Example #22
Source File: AbstractAPIManagerTestCase.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetDocumentation() throws APIManagementException, RegistryException {
    Registry registry = Mockito.mock(UserRegistry.class);
    AbstractAPIManager abstractAPIManager = new AbstractAPIManagerWrapper(genericArtifactManager, registry, null);
    APIIdentifier identifier = getAPIIdentifier(SAMPLE_API_NAME, API_PROVIDER, SAMPLE_API_VERSION);
    String documentationName = "doc1";
    String contentPath = APIConstants.API_LOCATION + RegistryConstants.PATH_SEPARATOR + identifier.getProviderName()
            + RegistryConstants.PATH_SEPARATOR + identifier.getApiName() + RegistryConstants.PATH_SEPARATOR
            + identifier.getVersion() + RegistryConstants.PATH_SEPARATOR + APIConstants.DOC_DIR
            + RegistryConstants.PATH_SEPARATOR + documentationName;
    GenericArtifact genericArtifact = getGenericArtifact(SAMPLE_API_NAME, API_PROVIDER, SAMPLE_API_VERSION,
            "sample");
    String docType = "other";
    genericArtifact.setAttribute(APIConstants.DOC_TYPE, docType);
    genericArtifact.setAttribute(APIConstants.DOC_SOURCE_TYPE, "URL");
    Resource resource = new ResourceImpl();
    resource.setUUID(SAMPLE_RESOURCE_ID);
    Mockito.when(registry.get(contentPath)).thenThrow(RegistryException.class).thenReturn(resource);
    Mockito.when(genericArtifactManager.getGenericArtifact(SAMPLE_RESOURCE_ID)).thenReturn(genericArtifact);
    try {
        abstractAPIManager.getDocumentation(identifier, DocumentationType.OTHER, documentationName);
        Assert.fail("Registry exception not thrown for error scenario");
    } catch (APIManagementException e) {
        Assert.assertTrue(e.getMessage().contains("Failed to get documentation details"));
    }
    Assert.assertTrue(
            abstractAPIManager.getDocumentation(identifier, DocumentationType.OTHER, documentationName).getId()
                    .equals(genericArtifact.getId()));
}
 
Example #23
Source File: AbstractAPIManagerTestCase.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetSubscriberAPIs() throws APIManagementException, RegistryException {
    Subscriber subscriber = new Subscriber("sub1");
    Application application = new Application("app1", subscriber);
    application.setId(1);
    SubscribedAPI subscribedAPI1 = new SubscribedAPI(subscriber,
            getAPIIdentifier(SAMPLE_API_NAME, API_PROVIDER, SAMPLE_API_VERSION));
    subscribedAPI1.setUUID(SAMPLE_RESOURCE_ID);
    SubscribedAPI subscribedAPI2 = new SubscribedAPI(subscriber, getAPIIdentifier("sample1", API_PROVIDER, "2.0.0"));
    Set<SubscribedAPI> subscribedAPIs = new HashSet<SubscribedAPI>();
    subscribedAPI1.setApplication(application);
    subscribedAPI2.setApplication(application);
    subscribedAPIs.add(subscribedAPI1);
    subscribedAPIs.add(subscribedAPI2);
    Mockito.when(apiMgtDAO.getSubscribedAPIs((Subscriber) Mockito.any(), Mockito.anyString()))
            .thenReturn(subscribedAPIs);
    UserRegistry registry = Mockito.mock(UserRegistry.class);
    AbstractAPIManager abstractAPIManager = new AbstractAPIManagerWrapper(genericArtifactManager, null, registry,
            null, apiMgtDAO);
    Resource resource = new ResourceImpl();
    resource.setUUID(SAMPLE_RESOURCE_ID);
    Mockito.when(registry.get(Mockito.anyString())).thenThrow(RegistryException.class).thenReturn(resource);
    try {
        abstractAPIManager.getSubscriberAPIs(subscriber);
        Assert.fail("Registry exception not thrown for error scenario");
    } catch (APIManagementException e) {
        Assert.assertTrue(e.getMessage().contains("Failed to get APIs for subscriber: "));
    }
    GenericArtifact artifact = getGenericArtifact(SAMPLE_API_NAME,API_PROVIDER,SAMPLE_API_VERSION,"sample_qname");
    Mockito.when(genericArtifactManager.getGenericArtifact(Mockito.anyString())).thenReturn(artifact);
    PowerMockito.mockStatic(APIUtil.class);
    PowerMockito.when(APIUtil.getAPI((GovernanceArtifact)Mockito.any(),(Registry)Mockito.any())).thenReturn(new API
            (getAPIIdentifier(SAMPLE_API_NAME, API_PROVIDER, SAMPLE_API_VERSION)));
    abstractAPIManager.tenantDomain = SAMPLE_TENANT_DOMAIN_1;
    Assert.assertEquals(abstractAPIManager.getSubscriberAPIs(subscriber).size(),1);

}
 
Example #24
Source File: AbstractAPIManagerTestCase.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
private GenericArtifact getGenericArtifact(String apiName, String provider, String version, String qName)
        throws GovernanceException {
    String id = UUID.randomUUID().toString();
    GenericArtifact genericArtifact = new GenericArtifactImpl(id, new QName(qName), "");
    genericArtifact.setAttribute(APIConstants.API_OVERVIEW_PROVIDER, provider);
    genericArtifact.setAttribute(APIConstants.API_OVERVIEW_NAME, apiName);
    genericArtifact.setAttribute(APIConstants.API_OVERVIEW_VERSION, version);
    return genericArtifact;
}
 
Example #25
Source File: EmailUserNameMigrationClient.java    From product-es with Apache License 2.0 5 votes vote down vote up
/**
 * This method replaces artifacts containing email username with ':' to '-at-'.
 * This will replace the storage path and resource content which contains overview_provider attribute with emailusername.
 *
 * @param artifacts artifacts of a particular rxt type. with overview-provider attribute in the storage path.
 * @param registry registry instance
 * @throws RegistryException
 * @throws javax.xml.stream.XMLStreamException
 */
private static void migrateArtifactsWithEmailUserName(GenericArtifact[] artifacts, Registry registry)
        throws RegistryException, XMLStreamException {
    for (GenericArtifact artifact : artifacts) {
        boolean isProviderMetadataUpdated = false;
        String relativePath = artifact.getPath();
        if (registry.resourceExists(relativePath)) {
            Resource resource = registry.get(relativePath);
            String metadataString = RegistryUtils.decodeBytes((byte[]) resource.getContent());
            OMElement metadataOM = AXIOMUtil.stringToOM(metadataString);
            OMElement overview = metadataOM.getFirstChildWithName(new QName(Constants.METADATA_NAMESPACE,
                                                                            Constants.OVERVIEW));
            OMElement providerElement = overview.getFirstChildWithName(new QName(Constants.METADATA_NAMESPACE,
                                                                                 Constants.PROVIDER));
            if (providerElement != null && providerElement.getText().contains(Constants.OLD_EMAIL_AT_SIGN)) {
                String oldProviderName = providerElement.getText();
                String newProviderName = oldProviderName.replace(Constants.OLD_EMAIL_AT_SIGN,
                                                                 Constants.NEW_EMAIL_AT_SIGN);
                providerElement.setText(newProviderName);
                resource.setContent(metadataOM.toStringWithConsume());
                isProviderMetadataUpdated = true;
            }
            String newPath = null;
            if (relativePath.contains(Constants.OLD_EMAIL_AT_SIGN)) {
                newPath = relativePath.replace(Constants.OLD_EMAIL_AT_SIGN,
                                               Constants.NEW_EMAIL_AT_SIGN);//TODO:replaceALL
                registry.move(relativePath, newPath);
                registry.put(newPath, resource);
            } else if (relativePath.contains(Constants.NEW_EMAIL_AT_SIGN)) {
                newPath = relativePath;
                if(isProviderMetadataUpdated==true) {
                    registry.put(newPath, resource);
                }
            }
        }
    }
}
 
Example #26
Source File: EmailUserNameMigrationClient.java    From product-es with Apache License 2.0 5 votes vote down vote up
/**
 * This method extracts the artifact types which contains '@{overview_provider}' in the storage path, and call the
 * migration method.
 * @param tenant The tenant object
 * @throws UserStoreException
 * @throws RegistryException
 * @throws XMLStreamException
 */
private void migrate(Tenant tenant)
        throws UserStoreException, RegistryException, XMLStreamException{

    int tenantId = tenant.getId();
    try {
        PrivilegedCarbonContext.startTenantFlow();
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenant.getDomain(), true);
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(tenantId);
        String adminName = ServiceHolder.getRealmService().getTenantUserRealm(tenantId).getRealmConfiguration()
                .getAdminUserName();
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(adminName);
        ServiceHolder.getTenantRegLoader().loadTenantRegistry(tenantId);
        Registry registry = ServiceHolder.getRegistryService().getGovernanceUserRegistry(adminName, tenantId);
        GovernanceUtils.loadGovernanceArtifacts((UserRegistry) registry);
        List<GovernanceArtifactConfiguration> configurations = GovernanceUtils.
                findGovernanceArtifactConfigurations(registry);
        for (GovernanceArtifactConfiguration governanceArtifactConfiguration : configurations) {
            String pathExpression = governanceArtifactConfiguration.getPathExpression();
            if (pathExpression.contains(Constants.OVERVIEW_PROVIDER) ||
                hasOverviewProviderElement(governanceArtifactConfiguration)) {
                String shortName = governanceArtifactConfiguration.getKey();
                GenericArtifactManager artifactManager = new GenericArtifactManager(registry, shortName);
                GenericArtifact[] artifacts = artifactManager.getAllGenericArtifacts();
                migrateArtifactsWithEmailUserName(artifacts, registry);
            }
        }
    } finally {
        PrivilegedCarbonContext.endTenantFlow();
    }

}
 
Example #27
Source File: UserAwareAPIProvider.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Override
protected API getAPI(GenericArtifact apiArtifact) throws APIManagementException {
    API api = APIUtil.getAPI(apiArtifact, registry);
    if (api != null) {
        APIUtil.updateAPIProductDependencies(api, registry);
        checkAccessControlPermission(api.getId());
    }
    return api;
}
 
Example #28
Source File: RegistryBasedLicenseManager.java    From carbon-device-mgt with Apache License 2.0 5 votes vote down vote up
private GenericArtifact getGenericArtifact(final String deviceType, final String languageCode)
        throws GovernanceException {
    GenericArtifact[] artifacts = artifactManager.findGenericArtifacts(new GenericArtifactFilter() {
        @Override
        public boolean matches(GenericArtifact artifact) throws GovernanceException {
            String attributeNameVal = artifact.getAttribute(
                    DeviceManagementConstants.LicenseProperties.NAME);
            String attributeLangVal = artifact.getAttribute(
                    DeviceManagementConstants.LicenseProperties.LANGUAGE);
            return (attributeNameVal != null && attributeLangVal != null && attributeNameVal.
                    equalsIgnoreCase(deviceType) && attributeLangVal.equalsIgnoreCase(languageCode));
        }
    });
    return (artifacts == null || artifacts.length == 0) ? null : artifacts[0];
}
 
Example #29
Source File: RegistryForumManager.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * Rates the given topic using registry rating,
 * @param topicId ID of the topic which should be rated.
 * @param rating User rate for the topic.
 * @param username Username
 * @param tenantDomain Tenant domain.
 * @return  Average rating.
 * @throws ForumException When the topic cannot be rated.
 */
@Override
public float rateTopic(String topicId, int rating, String username, String tenantDomain)throws ForumException {
    Registry registry;

    try {
        registry = getRegistry(username, tenantDomain);
        GenericArtifactManager artifactManager = getArtifactManager(registry, TOPIC_RXT_KEY);
        GenericArtifact genericArtifact = artifactManager.getGenericArtifact(topicId);
        registry.rateResource(genericArtifact.getPath(), rating);
        return registry.getAverageRating(genericArtifact.getPath());
    } catch (RegistryException e) {
        throw new ForumException("Unable to get Registry of User", e);
    }
}
 
Example #30
Source File: RegistryForumManager.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
private boolean isOwnerOfTopic(String username, GenericArtifact artifact){

        try {
            String owner = artifact.getAttribute(ForumConstants.OVERVIEW_TOPIC_OWNER);
            if(username == null){
                return false;
            }else{
                return username.equals(owner);
            }
        } catch (GovernanceException e) {
            log.error("Could not get the 'overview_owner' attribute of the artifact.", e);
            return false;
        }

    }