Java源码示例:org.wso2.carbon.governance.api.generic.GenericArtifactManager

示例1
/**
 * 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);
    }

}
 
示例2
/**
 * 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);
    }
}
 
示例3
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);
    }
}
 
示例4
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;
}
 
示例5
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);
    }
}
 
示例6
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);
    }
}
 
示例7
@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"));
}
 
示例8
@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));
}
 
示例9
@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));
}
 
示例10
@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"));
}
 
示例11
/**
 * 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());
}
 
示例12
/**
 * 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));
}
 
示例13
@Before
public void init() {
    System.setProperty(CARBON_HOME, "");
    privilegedCarbonContext = Mockito.mock(PrivilegedCarbonContext.class);
    PowerMockito.mockStatic(PrivilegedCarbonContext.class);
    PowerMockito.when(PrivilegedCarbonContext.getThreadLocalCarbonContext()).thenReturn(privilegedCarbonContext);
    PowerMockito.mockStatic(GovernanceUtils.class);
    paginationContext = Mockito.mock(PaginationContext.class);
    PowerMockito.mockStatic(PaginationContext.class);
    PowerMockito.when(PaginationContext.getInstance()).thenReturn(paginationContext);
    apiMgtDAO = Mockito.mock(ApiMgtDAO.class);
    registry = Mockito.mock(Registry.class);
    genericArtifactManager = Mockito.mock(GenericArtifactManager.class);
    registryService = Mockito.mock(RegistryService.class);
    tenantManager = Mockito.mock(TenantManager.class);
    graphQLSchemaDefinition = Mockito.mock(GraphQLSchemaDefinition.class);
    keyManager = Mockito.mock(KeyManager.class);
    PowerMockito.mockStatic(KeyManagerHolder.class);
    PowerMockito.when(KeyManagerHolder.getKeyManagerInstance("carbon.super")).thenReturn(keyManager);
}
 
示例14
/**
 * 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;
    }
}
 
示例15
/**
 * 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);
    }
}
 
示例16
private GenericArtifactManager getAPIGenericArtifactManager(APIIdentifier identifier, Registry registry)
        throws APIManagementException {

    String tenantDomain = getTenantDomain(identifier);
    GenericArtifactManager manager = genericArtifactCache.get(tenantDomain);
    if (manager != null) {
        return manager;
    }
    manager = getAPIGenericArtifactManagerFromUtil(registry, APIConstants.API_KEY);
    genericArtifactCache.put(tenantDomain, manager);
    return manager;
}
 
示例17
protected GenericArtifactManager getAPIGenericArtifactManager(Registry registryType, String keyType) throws
        APIManagementException {
    try {
        return new GenericArtifactManager(registryType, keyType);
    } catch (RegistryException e) {
        handleException("Error while retrieving generic artifact manager object",e);
    }
    return null;
}
 
示例18
public AbstractAPIManagerWrapper(GenericArtifactManager genericArtifactManager, RegistryService registryService,
        Registry registry, TenantManager tenantManager) throws APIManagementException {
    this.genericArtifactManager = genericArtifactManager;
    this.registry = registry;
    this.tenantManager = tenantManager;
    this.registryService = registryService;
}
 
示例19
public AbstractAPIManagerWrapper(GenericArtifactManager genericArtifactManager, RegistryService registryService,
        Registry registry, TenantManager tenantManager, ApiMgtDAO apiMgtDAO) throws APIManagementException {
    this.genericArtifactManager = genericArtifactManager;
    this.registry = registry;
    this.tenantManager = tenantManager;
    this.registryService = registryService;
    this.apiMgtDAO = apiMgtDAO;
}
 
示例20
@Before
public void init() throws UserStoreException, RegistryException {
    apiMgtDAO = Mockito.mock(ApiMgtDAO.class);
    userRealm = Mockito.mock(UserRealm.class);
    serviceReferenceHolder = Mockito.mock(ServiceReferenceHolder.class);
    realmService = Mockito.mock(RealmService.class);
    tenantManager = Mockito.mock(TenantManager.class);
    userStoreManager = Mockito.mock(UserStoreManager.class);
    keyManager = Mockito.mock(KeyManager.class);
    cacheInvalidator = Mockito.mock(CacheInvalidator.class);
    registryService = Mockito.mock(RegistryService.class);
    genericArtifactManager = Mockito.mock(GenericArtifactManager.class);
    registry = Mockito.mock(Registry.class);
    userRegistry = Mockito.mock(UserRegistry.class);
    authorizationManager = Mockito.mock(AuthorizationManager.class);
    PowerMockito.mockStatic(APIUtil.class);
    PowerMockito.mockStatic(ApplicationUtils.class);
    PowerMockito.mockStatic(ServiceReferenceHolder.class);
    PowerMockito.mockStatic(MultitenantUtils.class);
    PowerMockito.mockStatic(KeyManagerHolder.class);
    PowerMockito.mockStatic(CacheInvalidator.class);
    PowerMockito.mockStatic(RegistryUtils.class);
    PowerMockito.when(ServiceReferenceHolder.getInstance()).thenReturn(serviceReferenceHolder);
    PowerMockito.when(CacheInvalidator.getInstance()).thenReturn(cacheInvalidator);
    Mockito.when(serviceReferenceHolder.getRealmService()).thenReturn(realmService);
    Mockito.when(realmService.getTenantUserRealm(Mockito.anyInt())).thenReturn(userRealm);
    Mockito.when(realmService.getTenantManager()).thenReturn(tenantManager);
    Mockito.when(userRealm.getUserStoreManager()).thenReturn(userStoreManager);
    Mockito.when(serviceReferenceHolder.getRegistryService()).thenReturn(registryService);
    Mockito.when(registryService.getGovernanceSystemRegistry(Mockito.anyInt())).thenReturn(userRegistry);
    Mockito.when(userRealm.getAuthorizationManager()).thenReturn(authorizationManager);
    Mockito.when(KeyManagerHolder.getKeyManagerInstance(Mockito.anyString(),Mockito.anyString())).thenReturn(keyManager);
    PowerMockito.when(APIUtil.replaceSystemProperty(anyString())).thenAnswer((Answer<String>) invocation -> {
        Object[] args = invocation.getArguments();
        return (String) args[0];
    });
}
 
示例21
@Test
public void testGetAllPaginatedPublishedAPIs() 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.getAPI(artifact)).thenReturn(api);
    assertNotNull(apiConsumer.getAllPaginatedPublishedAPIs(MultitenantConstants
            .SUPER_TENANT_DOMAIN_NAME, 0, 10));
    assertNotNull(apiConsumer.getAllPaginatedPublishedAPIs(MultitenantConstants
            .SUPER_TENANT_DOMAIN_NAME, 0, 10));

    //artifact manager null path
    PowerMockito.when(APIUtil.getArtifactManager((UserRegistry)(Mockito.anyObject()), Mockito.anyString())).
            thenReturn(null);
    assertNotNull(apiConsumer.getAllPaginatedPublishedAPIs(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.getAllPaginatedPublishedAPIs(MultitenantConstants
            .SUPER_TENANT_DOMAIN_NAME, 0, 10));
}
 
示例22
@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));
}
 
示例23
@Test
public void testGetAllPaginatedAPIs() throws Exception {
    Registry userRegistry = Mockito.mock(Registry.class);
    APIConsumerImpl apiConsumer = new APIConsumerImplWrapper(userRegistry, apiMgtDAO);
    PowerMockito.mockStatic(GovernanceUtils.class);
    PowerMockito.doNothing().when(APIUtil.class, "loadTenantRegistry", Mockito.anyInt());
    PowerMockito.when(APIUtil.isAllowDisplayMultipleVersions()).thenReturn(false, true);
    UserRegistry userRegistry1 = Mockito.mock(UserRegistry.class);
    Mockito.when(registryService.getGovernanceUserRegistry(Mockito.anyString(), Mockito.anyInt())).
            thenReturn(userRegistry1);
    Mockito.when(registryService.getGovernanceSystemRegistry(Mockito.anyInt())).thenReturn(userRegistry1);
    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.findGenericArtifacts(Mockito.anyMap())).thenReturn(genericArtifacts);
    APIIdentifier apiId1 = new APIIdentifier("admin", "API1", "1.0.0");
    API api = new API(apiId1);
    Mockito.when(APIUtil.getAPI(artifact)).thenReturn(api);
    assertNotNull(apiConsumer.getAllPaginatedAPIs(MultitenantConstants
            .SUPER_TENANT_DOMAIN_NAME, 0, 10));
    assertNotNull(apiConsumer.getAllPaginatedAPIs(MultitenantConstants
            .SUPER_TENANT_DOMAIN_NAME, 0, 10));

    //artifact manager null path
    PowerMockito.when(APIUtil.getArtifactManager((UserRegistry)(Mockito.anyObject()), Mockito.anyString())).
            thenReturn(null);
    assertNotNull(apiConsumer.getAllPaginatedAPIs(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.getAllPaginatedAPIs(MultitenantConstants
            .SUPER_TENANT_DOMAIN_NAME, 0, 10));
}
 
示例24
/**
 * 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();
    }

}
 
示例25
@Override
public ForumSearchDTO<ForumTopicDTO> fetchForumTopics(int start, int count, String tenantDomain, String username) throws ForumException {

    Registry registry = getRegistry(username, tenantDomain);

    GenericArtifactManager artifactManager = getArtifactManager(registry, TOPIC_RXT_KEY);

    if(artifactManager == null){
        if(log.isDebugEnabled()){
            log.debug("Could not get artifact manager for topic.rxt, probably no topics found");
        }
        return null;
    }

    PaginationContext.init(start, count, "DESC", ForumConstants.OVERVIEW_TOPIC_TIMESTAMP, Integer.MAX_VALUE);

    try {

        Map<String, List<String>> listMap = new HashMap<String, List<String>>();
        listMap.put(ForumConstants.OVERVIEW_SUBJECT, new ArrayList<String>() {{
            add("*");
        }});

        //GenericArtifact[] genericArtifacts = artifactManager.getAllGenericArtifacts();
        GenericArtifact[] genericArtifacts = artifactManager.findGenericArtifacts(listMap);

        if(genericArtifacts == null || genericArtifacts.length == 0){
            if(log.isDebugEnabled()){
                log.debug("No Forum Topics Found");
            }
            return null;
        }

        ForumSearchDTO forumSearchDTO = new ForumSearchDTO();
        List<ForumTopicDTO> topics = new ArrayList<ForumTopicDTO>();
        ForumTopicDTO forumTopicDTO = null;
        for(GenericArtifact artifact : genericArtifacts){
            forumTopicDTO = createForumTopicDTOFromArtifact(artifact, registry);
            topics.add(forumTopicDTO);
        }
        forumSearchDTO.setPaginatedResults(topics);
        forumSearchDTO.setTotalResultCount(PaginationContext.getInstance().getLength());
        return forumSearchDTO;
    } catch (GovernanceException e) {
        log.error("Error finding forum topics " + e.getMessage());
        throw new ForumException("Error finding forum topics", e);
    } finally {
        PaginationContext.destroy();
    }
}
 
示例26
@Override
public ForumTopicDTO fetchForumTopicWithReplies(String topicId, int start, int count, String username, String tenantDomain)
        throws ForumException{

    Registry registry = getRegistry(username, tenantDomain);

    GenericArtifactManager topicArtifactManager = getArtifactManager(registry, TOPIC_RXT_KEY);
    GenericArtifactManager replyArtifactManager = getArtifactManager(registry, REPLY_RXT_KEY);

    if(topicArtifactManager == null){
        if(log.isDebugEnabled()){
            log.debug("Could not get artifact manager for topic.rxt, probably no topics found");
        }
        return null;
    }

    final String replyTopicId = topicId;

    Map<String, List<String>> listMap = new HashMap<String, List<String>>();
    listMap.put(ForumConstants.OVERVIEW_REPLY_TOPIC_ID, new ArrayList<String>() {{
        add(replyTopicId);
    }});

    ForumTopicDTO topicDTO = null;
    PaginationContext.init(start, count, "DESC", ForumConstants.OVERVIEW_REPLY_TIMESTAMP, Integer.MAX_VALUE);

    try {
        GenericArtifact topicArtifact = topicArtifactManager.getGenericArtifact(topicId);

        if(topicArtifact == null){
            log.info("Could not find topic with id " + topicId);
            return null;
        }

        topicDTO = createForumTopicDTOFromArtifact(topicArtifact, registry);

        // Set ratings of the topic.
        // NOTE : Taking this operation out from 'createForumTopicDTOFromArtifact' for performance's sake
        topicDTO.setUserRating(registry.getRating(topicArtifact.getPath(), username));
        topicDTO.setAverageRating(registry.getAverageRating(topicArtifact.getPath()));

        final String searchValue = topicId;

        GenericArtifact[] replyArtifacts = replyArtifactManager.findGenericArtifacts(listMap);

        if (replyArtifacts == null || replyArtifacts.length == 0) {
            if (log.isDebugEnabled()) {
                log.debug("No Replies Found for topic " + topicDTO.getSubject());
            }
            return topicDTO;
        }

        List<ForumReplyDTO> replies = new ArrayList<ForumReplyDTO>();
        for(GenericArtifact replyArtifact : replyArtifacts){
            ForumReplyDTO replyDTO = createReplyDtoFromArtifact(replyArtifact, registry);
            replies.add(replyDTO);
        }
        topicDTO.setReplies(replies);
        return topicDTO;
    } catch (RegistryException e) {
        log.error("Error while getting artifacts for topic " + topicId + " " + e.getMessage());
        throw new ForumException("Error while getting artifacts for topic " + topicId);
    } finally {
        PaginationContext.destroy();
    }
}
 
示例27
@Override
    public ForumSearchDTO<ForumTopicDTO> searchTopicsBySubject(int start, int count, String searchString, String user, String tenantDomain) throws ForumException{

        //final String regex = "(?i)[\\w.|-]*" + searchString.trim() + "[\\w.|-]*";
        final String regex = "*" + searchString.trim() + "*";
        //final Pattern pattern = Pattern.compile(regex);

        Map<String, List<String>> listMap = new HashMap<String, List<String>>();
        listMap.put(ForumConstants.OVERVIEW_SUBJECT, new ArrayList<String>() {{
            add(regex);
        }});

        Registry registry = getRegistry(user, tenantDomain);

//        try {
//            GovernanceUtils.loadGovernanceArtifacts((UserRegistry)registry);
//        } catch (RegistryException e) {
//            e.printStackTrace();
//        }

        PaginationContext.init(start, count, "DESC", ForumConstants.OVERVIEW_TOPIC_TIMESTAMP, Integer.MAX_VALUE);

        GenericArtifactManager artifactManager = getArtifactManager(registry, TOPIC_RXT_KEY);

        if(artifactManager == null){
            if(log.isDebugEnabled()){
                log.debug("Could not get artifact manager for topic.rxt, probably no topics found");
            }
            return null;
        }

        try {
           /* GenericArtifact[] genericArtifacts = artifactManager.findGenericArtifacts(new GenericArtifactFilter() {
                @Override
                public boolean matches(GenericArtifact artifact) throws GovernanceException {
                    Matcher matcher = pattern.matcher(artifact.getAttribute(ForumConstants.OVERVIEW_SUBJECT));
                    return matcher.find();
                }
            });*/

            GenericArtifact[] genericArtifacts = artifactManager.findGenericArtifacts(listMap);
            if(genericArtifacts == null || genericArtifacts.length == 0){
                if(log.isDebugEnabled()){
                    log.debug("No Forum Topics Found");
                }
                return null;
            }

            List<ForumTopicDTO> topics = new ArrayList<ForumTopicDTO>();
            ForumTopicDTO forumTopicDTO = null;
            for(GenericArtifact artifact : genericArtifacts){
                forumTopicDTO = createForumTopicDTOFromArtifact(artifact, registry);
                topics.add(forumTopicDTO);
            }

            ForumSearchDTO<ForumTopicDTO> forumSearchDTO = new ForumSearchDTO<ForumTopicDTO>();
            forumSearchDTO.setPaginatedResults(topics);
            forumSearchDTO.setTotalResultCount(PaginationContext.getInstance().getLength());

            return forumSearchDTO;
        } catch (GovernanceException e) {
            log.error("Error finding forum topics " + e.getMessage());
            throw new ForumException("Error finding forum topics", e);
        } finally {
            PaginationContext.destroy();
        }
    }
 
示例28
@Override
public ForumSearchDTO<ForumTopicDTO> searchTopicsBySubjectForResourceId(int start, int count, String searchString,
                                                                        final String resourceIdentifier,
                                                                        String user, String tenantDomain)
                                                                                            throws ForumException {

    final String regex = "*" + searchString.trim() + "*";

    Map<String, List<String>> listMap = new HashMap<String, List<String>>();
    listMap.put(ForumConstants.OVERVIEW_SUBJECT, new ArrayList<String>() {
        {
            add(regex);
        }
    });
    listMap.put(ForumConstants.OVERVIEW_RESOURCE_IDENTIFIER, new ArrayList<String>() {
        {
            add(resourceIdentifier.replace("@", "-AT-").replace(":","\\:"));
        }
    });

    Registry registry = getRegistry(user, tenantDomain);

    PaginationContext.init(start, count, "DESC", ForumConstants.OVERVIEW_TOPIC_TIMESTAMP, Integer.MAX_VALUE);

    GenericArtifactManager artifactManager = getArtifactManager(registry, TOPIC_RXT_KEY);

    if (artifactManager == null) {
        if (log.isDebugEnabled()) {
            log.debug("Could not get artifact manager for topic.rxt, probably no topics found");
        }
        return null;
    }

    try {
        
        GenericArtifact[] genericArtifacts = artifactManager.findGenericArtifacts(listMap);
        if (genericArtifacts == null || genericArtifacts.length == 0) {
            if (log.isDebugEnabled()) {
                log.debug("No Forum Topics Found");
            }
            return null;
        }

        List<ForumTopicDTO> topics = new ArrayList<ForumTopicDTO>();
        ForumTopicDTO forumTopicDTO = null;
        for (GenericArtifact artifact : genericArtifacts) {
            forumTopicDTO = createForumTopicDTOFromArtifact(artifact, registry);
            topics.add(forumTopicDTO);
        }

        ForumSearchDTO<ForumTopicDTO> forumSearchDTO = new ForumSearchDTO<ForumTopicDTO>();
        forumSearchDTO.setPaginatedResults(topics);
        forumSearchDTO.setTotalResultCount(PaginationContext.getInstance().getLength());

        return forumSearchDTO;
    } catch (GovernanceException e) {
        log.error("Error finding forum topics " + e.getMessage());
        throw new ForumException("Error finding forum topics", e);
    } finally {
        PaginationContext.destroy();
    }
}
 
示例29
public ForumSearchDTO<ForumTopicDTO> getTopicsByResourceId(int start, int count, final String resourceIdentifier,
                                                           String user, String tenantDomain) throws ForumException{

    Map<String, List<String>> listMap = new HashMap<String, List<String>>();
    listMap.put(ForumConstants.OVERVIEW_RESOURCE_IDENTIFIER, new ArrayList<String>() {{
        add(resourceIdentifier.replace("@", "-AT-").replace(":","\\:"));
    }});

    Registry registry = getRegistry(user, tenantDomain);

    PaginationContext.init(start, count, "DESC", ForumConstants.OVERVIEW_TOPIC_TIMESTAMP, Integer.MAX_VALUE);

    GenericArtifactManager artifactManager = getArtifactManager(registry, TOPIC_RXT_KEY);

    if(artifactManager == null){
        if(log.isDebugEnabled()){
            log.debug("Could not get artifact manager for topic.rxt, probably no topics found");
        }
        return null;
    }

    try {
        GenericArtifact[] genericArtifacts = artifactManager.findGenericArtifacts(listMap);
        if(genericArtifacts == null || genericArtifacts.length == 0){
            if(log.isDebugEnabled()){
                log.debug("No Forum Topics Found for identifier " + resourceIdentifier);
            }
            return null;
        }

        List<ForumTopicDTO> topics = new ArrayList<ForumTopicDTO>();
        ForumTopicDTO forumTopicDTO = null;
        for(GenericArtifact artifact : genericArtifacts){
            forumTopicDTO = createForumTopicDTOFromArtifact(artifact, registry);
            topics.add(forumTopicDTO);
        }

        ForumSearchDTO<ForumTopicDTO> forumSearchDTO = new ForumSearchDTO<ForumTopicDTO>();
        forumSearchDTO.setPaginatedResults(topics);
        forumSearchDTO.setTotalResultCount(PaginationContext.getInstance().getLength());

        return forumSearchDTO;
    } catch (GovernanceException e) {
        log.error("Error finding forum topics " + e.getMessage());
        throw new ForumException("Error finding forum topics", e);
    } finally {
        PaginationContext.destroy();
    }
}
 
示例30
public List<Documentation> getAllDocumentation(Identifier id) throws APIManagementException {
    List<Documentation> documentationList = new ArrayList<Documentation>();
    String resourcePath = StringUtils.EMPTY;
    String docArtifactKeyType = StringUtils.EMPTY;
    if (id instanceof APIIdentifier) {
        resourcePath = APIUtil.getAPIPath((APIIdentifier) id);
    } else if (id instanceof APIProductIdentifier) {
        resourcePath = APIUtil.getAPIProductPath((APIProductIdentifier) id);
    }
    docArtifactKeyType = APIConstants.DOCUMENTATION_KEY;

    try {
        Association[] docAssociations = registry.getAssociations(resourcePath,
                APIConstants.DOCUMENTATION_ASSOCIATION);
        if (docAssociations == null) {
            return documentationList;
        }
        for (Association association : docAssociations) {
            String docPath = association.getDestinationPath();

            Resource docResource = registry.get(docPath);
            GenericArtifactManager artifactManager = getAPIGenericArtifactManager(registry,
                    docArtifactKeyType);
            GenericArtifact docArtifact = artifactManager.getGenericArtifact(docResource.getUUID());
            Documentation doc = APIUtil.getDocumentation(docArtifact);
            Date contentLastModifiedDate;
            Date docLastModifiedDate = docResource.getLastModified();
            if (Documentation.DocumentSourceType.INLINE.equals(doc.getSourceType()) || Documentation.DocumentSourceType.MARKDOWN.equals(doc.getSourceType())) {
                String contentPath = StringUtils.EMPTY;
                if (id instanceof APIIdentifier) {
                    contentPath = APIUtil.getAPIDocContentPath((APIIdentifier) id, doc.getName());
                } else if (id instanceof APIProductIdentifier) {
                    contentPath = APIUtil.getProductDocContentPath((APIProductIdentifier) id, doc.getName());
                }

                contentLastModifiedDate = registry.get(contentPath).getLastModified();
                doc.setLastUpdated((contentLastModifiedDate.after(docLastModifiedDate) ?
                        contentLastModifiedDate : docLastModifiedDate));
            } else {
                doc.setLastUpdated(docLastModifiedDate);
            }
            documentationList.add(doc);
        }

    } catch (RegistryException e) {
        String msg = "Failed to get documentations for api/product " + id.getName();
        throw new APIManagementException(msg, e);
    }
    return documentationList;
}