org.wso2.carbon.governance.api.generic.GenericArtifactManager Java Examples

The following examples show how to use org.wso2.carbon.governance.api.generic.GenericArtifactManager. 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 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 #2
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 #3
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 #4
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 #5
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 #6
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 #7
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 #8
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 #9
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 #10
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 #11
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 #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: AbstractAPIManagerTestCase.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #14
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 #15
Source File: APIConsumerImplTest.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@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];
    });
}
 
Example #16
Source File: APIConsumerImplTest.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@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));
}
 
Example #17
Source File: AbstractAPIManagerWrapper.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example #18
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 #19
Source File: APIConsumerImplTest.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@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));
}
 
Example #20
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 #21
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 #22
Source File: AbstractAPIManager.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example #23
Source File: AbstractAPIManager.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example #24
Source File: AbstractAPIManagerWrapper.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
public AbstractAPIManagerWrapper(GenericArtifactManager genericArtifactManager, RegistryService registryService,
        Registry registry, TenantManager tenantManager) throws APIManagementException {
    this.genericArtifactManager = genericArtifactManager;
    this.registry = registry;
    this.tenantManager = tenantManager;
    this.registryService = registryService;
}
 
Example #25
Source File: APIConsumerImplTest.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
@Test
public void testGetAllPaginatedAPIsByStatusSet() throws Exception {
    Registry userRegistry = Mockito.mock(Registry.class);
    APIConsumerImpl apiConsumer = new APIConsumerImplWrapper(userRegistry, apiMgtDAO);
    PowerMockito.mockStatic(GovernanceUtils.class);
    APIManagerConfiguration apiManagerConfiguration = Mockito.mock(APIManagerConfiguration.class);
    APIManagerConfigurationService apiManagerConfigurationService = Mockito.
            mock(APIManagerConfigurationService.class);
    Mockito.when(serviceReferenceHolder.getAPIManagerConfigurationService()).thenReturn(apiManagerConfigurationService);
    Mockito.when(apiManagerConfigurationService.getAPIManagerConfiguration()).thenReturn(apiManagerConfiguration);
    Mockito.when(apiManagerConfiguration.getFirstProperty(Mockito.anyString())).thenReturn("10", "20");

    PowerMockito.doNothing().when(APIUtil.class, "loadTenantRegistry", Mockito.anyInt());
    GenericArtifactManager artifactManager = Mockito.mock(GenericArtifactManager.class);
    PowerMockito.when(APIUtil.isAllowDisplayMultipleVersions()).thenReturn(false, true);
    PowerMockito.when(APIUtil.getArtifactManager((UserRegistry)(Mockito.anyObject()), Mockito.anyString())).
            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);
    String artifactPath = "artifact/path";
    PowerMockito.when(GovernanceUtils.getArtifactPath(userRegistry, artifact.getId())).
            thenReturn(artifactPath);
    Tag tag = new Tag();
    Tag[] tags = new Tag[]{tag};
    Mockito.when(userRegistry.getTags(artifactPath)).thenReturn(tags);
    assertNotNull(apiConsumer.getAllPaginatedAPIsByStatus(MultitenantConstants
            .SUPER_TENANT_DOMAIN_NAME, 0, 10, new String[]{"testStatus"}, false));
    assertNotNull(apiConsumer.getAllPaginatedAPIsByStatus(MultitenantConstants
            .SUPER_TENANT_DOMAIN_NAME, 0, 10, new String[]{"testStatus"}, true));

    //artifact manager null path
    PowerMockito.when(APIUtil.getArtifactManager((UserRegistry)(Mockito.anyObject()), Mockito.anyString())).
            thenReturn(null);
    assertNotNull(apiConsumer.getAllPaginatedAPIsByStatus(MultitenantConstants
            .SUPER_TENANT_DOMAIN_NAME, 0, 10, new String[]{"testStatus"}, true));

    //generic artifact null path
    PowerMockito.when(APIUtil.getArtifactManager((UserRegistry)(Mockito.anyObject()), Mockito.anyString())).
            thenReturn(artifactManager);
    Mockito.when(GovernanceUtils.findGovernanceArtifacts(Mockito.anyString(),(UserRegistry)Mockito.anyObject(),
            Mockito.anyString())).thenReturn(null);
    assertNotNull(apiConsumer.getAllPaginatedAPIsByStatus(MultitenantConstants
            .SUPER_TENANT_DOMAIN_NAME, 0, 10, new String[]{"testStatus"}, true));
}
 
Example #26
Source File: RegistryForumManager.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
@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();
    }
}
 
Example #27
Source File: RegistryForumManager.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
@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();
        }
    }
 
Example #28
Source File: UserAwareAPIProviderTest.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
@Before
public void init() throws Exception {
    System.setProperty("carbon.home", "");
    apiIdentifier = new APIIdentifier("admin_identifier1_v1.0");
    PowerMockito.mockStatic(ApiMgtDAO.class);
    PowerMockito.mockStatic(ServiceReferenceHolder.class);
    PowerMockito.mockStatic(APIUtil.class);
    PowerMockito.mockStatic(RegistryUtils.class);
    PowerMockito.mockStatic(PrivilegedCarbonContext.class);
    ApiMgtDAO apiMgtDAO = Mockito.mock(ApiMgtDAO.class);
    ServiceReferenceHolder serviceReferenceHolder = Mockito.mock(ServiceReferenceHolder.class);
    TenantManager tenantManager = Mockito.mock(TenantManager.class);
    RealmService realmService = Mockito.mock(RealmService.class);
    RegistryService registryService = Mockito.mock(RegistryService.class);
    userRegistry = Mockito.mock(UserRegistry.class);
    GenericArtifactManager artifactManager = Mockito.mock(GenericArtifactManager.class);
    APIManagerConfigurationService apiManagerConfigurationService = Mockito
            .mock(APIManagerConfigurationService.class);
    APIManagerConfiguration apiManagerConfiguration = Mockito.mock(APIManagerConfiguration.class);
    resource = Mockito.mock(Resource.class, Mockito.CALLS_REAL_METHODS);
    Mockito.doReturn(apiManagerConfiguration).when(apiManagerConfigurationService).getAPIManagerConfiguration();
    Mockito.doReturn(APIConstants.API_GATEWAY_TYPE_SYNAPSE).when(apiManagerConfiguration)
            .getFirstProperty(APIConstants.API_GATEWAY_TYPE);
    Mockito.doReturn("true").when(apiManagerConfiguration)
            .getFirstProperty(APIConstants.API_PUBLISHER_ENABLE_ACCESS_CONTROL_LEVELS);
    Mockito.doReturn(userRegistry).when(registryService)
            .getGovernanceUserRegistry(Mockito.anyString(), Mockito.anyInt());
    Mockito.doReturn(userRegistry).when(registryService).getConfigSystemRegistry(Mockito.anyInt());
    Mockito.doReturn(userRegistry).when(registryService).getConfigSystemRegistry();
    Mockito.doReturn(resource).when(userRegistry).newResource();
    Mockito.doReturn(null).when(userRegistry).getUserRealm();
    PowerMockito.when(ApiMgtDAO.getInstance()).thenReturn(apiMgtDAO);
    PowerMockito.when(ServiceReferenceHolder.getInstance()).thenReturn(serviceReferenceHolder);
    PowerMockito.when(APIUtil.getAPIPath(Mockito.any(APIIdentifier.class))).thenReturn("test");
    PowerMockito.when(APIUtil.getArtifactManager(Mockito.any(Registry.class), Mockito.anyString()))
            .thenReturn(artifactManager);
    PowerMockito.doNothing().when(ServiceReferenceHolder.class, "setUserRealm", Mockito.any());
    PowerMockito.doNothing().when(APIUtil.class, "loadTenantRegistry", Mockito.anyInt());
    PowerMockito.when(APIUtil.replaceEmailDomainBack(apiIdentifier.getProviderName())).
            thenReturn(apiIdentifier.getProviderName());
    Mockito.doReturn(realmService).when(serviceReferenceHolder).getRealmService();
    Mockito.doReturn(tenantManager).when(realmService).getTenantManager();
    Mockito.doReturn(registryService).when(serviceReferenceHolder).getRegistryService();
    Mockito.doReturn(apiManagerConfigurationService).when(serviceReferenceHolder)
            .getAPIManagerConfigurationService();
    PowerMockito.when(APIUtil.compareRoleList(Mockito.any(String[].class), Mockito.anyString()))
            .thenCallRealMethod();
    ConfigurationContextService configurationContextService = TestUtils.initConfigurationContextService(true);
    PowerMockito.when(ServiceReferenceHolder.getContextService()).thenReturn(configurationContextService);
    userAwareAPIProvider = new UserAwareAPIProvider(ADMIN_ROLE_NAME);
    PrivilegedCarbonContext prcontext = Mockito.mock(PrivilegedCarbonContext.class);
    PowerMockito.when(PrivilegedCarbonContext.getThreadLocalCarbonContext()).thenReturn(prcontext);
}
 
Example #29
Source File: RegistryForumManager.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
@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();
    }
}
 
Example #30
Source File: RegistryForumManager.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
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();
    }
}