org.wso2.carbon.registry.core.RegistryConstants Java Examples

The following examples show how to use org.wso2.carbon.registry.core.RegistryConstants. 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: AbstractAPIManager.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
public String addResourceFile(Identifier identifier, String resourcePath, ResourceFile resourceFile) throws APIManagementException {
    try {
        Resource thumb = registry.newResource();
        thumb.setContentStream(resourceFile.getContent());
        thumb.setMediaType(resourceFile.getContentType());
        registry.put(resourcePath, thumb);
        if (MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equalsIgnoreCase(tenantDomain)) {
            return RegistryConstants.PATH_SEPARATOR + "registry"
                    + RegistryConstants.PATH_SEPARATOR + "resource"
                    + RegistryConstants.PATH_SEPARATOR + "_system"
                    + RegistryConstants.PATH_SEPARATOR + "governance"
                    + resourcePath;
        } else {
            return "/t/" + tenantDomain + RegistryConstants.PATH_SEPARATOR + "registry"
                    + RegistryConstants.PATH_SEPARATOR + "resource"
                    + RegistryConstants.PATH_SEPARATOR + "_system"
                    + RegistryConstants.PATH_SEPARATOR + "governance"
                    + resourcePath;
        }
    } catch (RegistryException e) {
        String msg = "Error while adding the resource to the registry";
        throw new APIManagementException(msg, e);
    }
}
 
Example #2
Source File: Utils.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
/**
 * gets no of verified user challenges
 *
 * @param userDTO bean class that contains user and tenant Information
 * @return no of verified challenges
 * @throws IdentityException if fails
 */
public static int getVerifiedChallenges(UserDTO userDTO) throws IdentityException {

    int noOfChallenges = 0;

    try {
        UserRegistry registry = IdentityMgtServiceComponent.getRegistryService().
                getConfigSystemRegistry(MultitenantConstants.SUPER_TENANT_ID);
        String identityKeyMgtPath = IdentityMgtConstants.IDENTITY_MANAGEMENT_CHALLENGES +
                RegistryConstants.PATH_SEPARATOR + userDTO.getUserId() +
                RegistryConstants.PATH_SEPARATOR + userDTO.getUserId();

        Resource resource;
        if (registry.resourceExists(identityKeyMgtPath)) {
            resource = registry.get(identityKeyMgtPath);
            String property = resource.getProperty(IdentityMgtConstants.VERIFIED_CHALLENGES);
            if (property != null) {
                return Integer.parseInt(property);
            }
        }
    } catch (RegistryException e) {
        log.error("Error while processing userKey", e);
    }

    return noOfChallenges;
}
 
Example #3
Source File: CloudServicesUtil.java    From carbon-commons with Apache License 2.0 6 votes vote down vote up
public static boolean isCloudServiceActive(String cloudServiceName,
                                           int tenantId, UserRegistry govRegistry)
                                                                                  throws Exception {
    // The cloud manager is always active
    if (StratosConstants.CLOUD_MANAGER_SERVICE.equals(cloudServiceName)) {
        return true;
    }

    String cloudServiceInfoPath = StratosConstants.CLOUD_SERVICE_INFO_STORE_PATH +
                                  RegistryConstants.PATH_SEPARATOR + tenantId +
                                  RegistryConstants.PATH_SEPARATOR + cloudServiceName;
    Resource cloudServiceInfoResource;
    if (govRegistry.resourceExists(cloudServiceInfoPath)) {
        cloudServiceInfoResource = govRegistry.get(cloudServiceInfoPath);
        String isActiveStr =
                             cloudServiceInfoResource.getProperty(
                                                     StratosConstants.CLOUD_SERVICE_IS_ACTIVE_PROP_KEY);
        return "true".equals(isActiveStr);
    }
    return false;
}
 
Example #4
Source File: RegistryCacheInvalidationServiceTestCase.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Test
public void testInvalidateCacheWhenRegistryUnmountedAndCached() throws APIManagementException {

    List<RemoteConfiguration> remoteConfigurationList = new ArrayList<RemoteConfiguration>();
    Mockito.when(registryContext.getRemoteInstances()).thenReturn(remoteConfigurationList);
    DataBaseConfiguration dbConfiguration = Mockito.mock(DataBaseConfiguration.class);
    Mockito.when(registryContext.getDefaultDataBaseConfiguration()).thenReturn(dbConfiguration);
    PowerMockito.when(RegistryUtils.getResourceCache(RegistryConstants.REGISTRY_CACHE_BACKED_ID)).thenReturn(cache);
    Mockito.when(dbConfiguration.getUserName()).thenReturn("[email protected]");
    Mockito.when(dbConfiguration.getDbUrl()).thenReturn("xyz.com/db");
    RegistryCacheKey registryCacheKey = Mockito.mock(RegistryCacheKey.class);
    PowerMockito.when(RegistryUtils.buildRegistryCacheKey("[email protected]/db", 6543, path)).thenReturn(registryCacheKey);
    Mockito.when(cache.containsKey(registryCacheKey)).thenReturn(true);

    RegistryCacheInvalidationService registryCacheInvalidationService = new RegistryCacheInvalidationService();
    registryCacheInvalidationService.invalidateCache(path,tenantDomain);
    Mockito.verify(cache, Mockito.times(1)).remove(Matchers.any());
}
 
Example #5
Source File: CommonUtil.java    From attic-stratos with Apache License 2.0 6 votes vote down vote up
/**
 * validates domain from the successkey
 *
 * @param governanceSystemRegistry - The governance system registry
 * @param domain                   - tenant domain
 * @param successKey               - successkey
 * @return true, if successfully validated
 * @throws RegistryException, if validation failed
 */
public static boolean validateDomainFromSuccessKey(UserRegistry governanceSystemRegistry,
                                                   String domain, String successKey)
        throws RegistryException {
    String domainValidatorInfoPath =
            StratosConstants.DOMAIN_VALIDATOR_INFO_PATH + RegistryConstants.PATH_SEPARATOR +
                    domain + RegistryConstants.PATH_SEPARATOR +
                    StratosConstants.VALIDATION_KEY_RESOURCE_NAME;
    if (governanceSystemRegistry.resourceExists(domainValidatorInfoPath)) {
        Resource resource = governanceSystemRegistry.get(domainValidatorInfoPath);
        String actualSuccessKey = resource.getProperty("successKey");
        if (actualSuccessKey != null && successKey != null &&
                actualSuccessKey.trim().equals(successKey.trim())) {
            // the domain is correct
            return true;
        }
    }
    return false;
}
 
Example #6
Source File: PolicyPublisher.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
public void deleteSubscriber(String subscriberId) throws EntitlementException {

        String subscriberPath;

        if (subscriberId == null) {
            log.error("Subscriber Id can not be null");
            throw new EntitlementException("Subscriber Id can not be null");
        }

        if (EntitlementConstants.PDP_SUBSCRIBER_ID.equals(subscriberId.trim())) {
            log.error("Can not delete PDP publisher");
            throw new EntitlementException("Can not delete PDP publisher");
        }

        try {
            subscriberPath = PDPConstants.ENTITLEMENT_POLICY_PUBLISHER +
                    RegistryConstants.PATH_SEPARATOR + subscriberId;

            if (registry.resourceExists(subscriberPath)) {
                registry.delete(subscriberPath);
            }
        } catch (RegistryException e) {
            log.error("Error while deleting subscriber details", e);
            throw new EntitlementException("Error while deleting subscriber details", e);
        }
    }
 
Example #7
Source File: PolicyPublisher.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
public PublisherDataHolder retrieveSubscriber(String id, boolean returnSecrets) throws EntitlementException {

        try {
            if (registry.resourceExists(PDPConstants.ENTITLEMENT_POLICY_PUBLISHER +
                    RegistryConstants.PATH_SEPARATOR + id)) {
                Resource resource = registry.get(PDPConstants.ENTITLEMENT_POLICY_PUBLISHER +
                        RegistryConstants.PATH_SEPARATOR + id);

                return new PublisherDataHolder(resource, returnSecrets);
            }
        } catch (RegistryException e) {
            log.error("Error while retrieving subscriber detail of id : " + id, e);
            throw new EntitlementException("Error while retrieving subscriber detail of id : " + id, e);
        }

        throw new EntitlementException("No Subscriber is defined for given Id");
    }
 
Example #8
Source File: OAuthConsumerDAO.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
/**
 * Returns oAuth consumer secret for a give consumer key.
 *
 * @param consumerKey consumer key
 * @return oAuth consumer secret
 * @throws IdentityException if error occurs while obtaining the consumer secret
 */
public String getOAuthConsumerSecret(String consumerKey) throws IdentityException {
    String path = null;
    Resource resource = null;

    if (log.isDebugEnabled()) {
        log.debug("Retreiving user for OAuth consumer key  " + consumerKey);
    }

    try {
        path = RegistryConstants.PROFILES_PATH + consumerKey;
        if (registry.resourceExists(path)) {
            resource = registry.get(path);
            return resource.getProperty(IdentityRegistryResources.OAUTH_CONSUMER_PATH);
        } else {
            return null;
        }
    } catch (RegistryException e) {
        log.error("Error while retreiving user for OAuth consumer key  " + consumerKey, e);
        throw IdentityException.error("Error while retreiving user for OAuth consumer key  "
                + consumerKey, e);
    }
}
 
Example #9
Source File: CloudServicesUtil.java    From attic-stratos with Apache License 2.0 6 votes vote down vote up
public static boolean isCloudServiceActive(String cloudServiceName,
                                           int tenantId, UserRegistry govRegistry)
        throws Exception {
    // The cloud manager is always active
    if (StratosConstants.CLOUD_MANAGER_SERVICE.equals(cloudServiceName)) {
        return true;
    }

    String cloudServiceInfoPath = StratosConstants.CLOUD_SERVICE_INFO_STORE_PATH +
            RegistryConstants.PATH_SEPARATOR + tenantId +
            RegistryConstants.PATH_SEPARATOR + cloudServiceName;
    Resource cloudServiceInfoResource;
    if (govRegistry.resourceExists(cloudServiceInfoPath)) {
        cloudServiceInfoResource = govRegistry.get(cloudServiceInfoPath);
        String isActiveStr =
                cloudServiceInfoResource.getProperty(
                        StratosConstants.CLOUD_SERVICE_IS_ACTIVE_PROP_KEY);
        return "true".equals(isActiveStr);
    }
    return false;
}
 
Example #10
Source File: ApplicationManagementServiceImpl.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
private void updateApplicationPermissions(ServiceProvider updatedApp, String updatedAppName, String storedAppName)
        throws RegistryException, IdentityApplicationManagementException {

    String applicationNode = ApplicationMgtUtil.getApplicationPermissionPath() + RegistryConstants
            .PATH_SEPARATOR + storedAppName;
    org.wso2.carbon.registry.api.Registry tenantGovReg = CarbonContext.getThreadLocalCarbonContext()
            .getRegistry(RegistryType.USER_GOVERNANCE);

    boolean exist = tenantGovReg.resourceExists(applicationNode);
    if (exist && !StringUtils.equals(storedAppName, updatedAppName)) {
        ApplicationMgtUtil.renameAppPermissionPathNode(storedAppName, updatedAppName);
    }

    if (updatedApp.getPermissionAndRoleConfig() != null &&
            ArrayUtils.isNotEmpty(updatedApp.getPermissionAndRoleConfig().getPermissions())) {
        ApplicationMgtUtil.updatePermissions(updatedAppName,
                updatedApp.getPermissionAndRoleConfig().getPermissions());
    }
}
 
Example #11
Source File: CommonUtil.java    From carbon-commons with Apache License 2.0 6 votes vote down vote up
/**
 * validates domain from the successkey
 *
 * @param governanceSystemRegistry - The governance system registry
 * @param domain                   - tenant domain
 * @param successKey               - successkey
 * @return true, if successfully validated
 * @throws RegistryException, if validation failed
 */
public static boolean validateDomainFromSuccessKey(UserRegistry governanceSystemRegistry,
                                                   String domain, String successKey)
        throws RegistryException {
    String domainValidatorInfoPath =
            StratosConstants.DOMAIN_VALIDATOR_INFO_PATH + RegistryConstants.PATH_SEPARATOR +
            domain + RegistryConstants.PATH_SEPARATOR +
            StratosConstants.VALIDATION_KEY_RESOURCE_NAME;
    if (governanceSystemRegistry.resourceExists(domainValidatorInfoPath)) {
        Resource resource = governanceSystemRegistry.get(domainValidatorInfoPath);
        String actualSuccessKey = resource.getProperty("successKey");
        if (actualSuccessKey != null && successKey != null &&
            actualSuccessKey.trim().equals(successKey.trim())) {
            // the domain is correct
            return true;
        }
    }
    return false;
}
 
Example #12
Source File: PolicyPublisher.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
public void deleteSubscriber(String subscriberId) throws EntitlementException {

        String subscriberPath;

        if (subscriberId == null) {
            log.error("Subscriber Id can not be null");
            throw new EntitlementException("Subscriber Id can not be null");
        }

        if (EntitlementConstants.PDP_SUBSCRIBER_ID.equals(subscriberId.trim())) {
            log.error("Can not delete PDP publisher");
            throw new EntitlementException("Can not delete PDP publisher");
        }

        try {
            subscriberPath = PDPConstants.ENTITLEMENT_POLICY_PUBLISHER +
                    RegistryConstants.PATH_SEPARATOR + subscriberId;

            if (registry.resourceExists(subscriberPath)) {
                registry.delete(subscriberPath);
            }
        } catch (RegistryException e) {
            log.error("Error while deleting subscriber details", e);
            throw new EntitlementException("Error while deleting subscriber details", e);
        }
    }
 
Example #13
Source File: PolicyPublisher.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
public PublisherDataHolder retrieveSubscriber(String id, boolean returnSecrets) throws EntitlementException {

        try {
            if (registry.resourceExists(PDPConstants.ENTITLEMENT_POLICY_PUBLISHER +
                    RegistryConstants.PATH_SEPARATOR + id)) {
                Resource resource = registry.get(PDPConstants.ENTITLEMENT_POLICY_PUBLISHER +
                        RegistryConstants.PATH_SEPARATOR + id);

                return new PublisherDataHolder(resource, returnSecrets);
            }
        } catch (RegistryException e) {
            log.error("Error while retrieving subscriber detail of id : " + id, e);
            throw new EntitlementException("Error while retrieving subscriber detail of id : " + id, e);
        }

        throw new EntitlementException("No Subscriber is defined for given Id");
    }
 
Example #14
Source File: AbstractAPIManagerTestCase.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Test
public void testIsAPIProductAvailable() throws RegistryException, APIManagementException {
    APIProductIdentifier apiProductIdentifier = getAPIProductIdentifier(SAMPLE_API_NAME, API_PROVIDER, SAMPLE_API_VERSION);
    String path =
            APIConstants.API_ROOT_LOCATION + RegistryConstants.PATH_SEPARATOR + apiProductIdentifier.getProviderName()
                    + RegistryConstants.PATH_SEPARATOR + apiProductIdentifier.getName()
                    + RegistryConstants.PATH_SEPARATOR + apiProductIdentifier.getVersion();
    Mockito.when(registry.resourceExists(path)).thenThrow(RegistryException.class).thenReturn(true);
    AbstractAPIManager abstractAPIManager = new AbstractAPIManagerWrapper(registry);
    try {
        abstractAPIManager.isAPIProductAvailable(apiProductIdentifier);
        Assert.fail("Exception not thrown for error scenario");
    } catch (APIManagementException e) {
        Assert.assertTrue(e.getMessage().contains("Failed to check availability of API Product"));
    }
    Assert.assertTrue(abstractAPIManager.isAPIProductAvailable(apiProductIdentifier));
}
 
Example #15
Source File: AbstractAPIManagerTestCase.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Test
public void testIsAPIAvailable() throws RegistryException, APIManagementException {
    APIIdentifier apiIdentifier = getAPIIdentifier(SAMPLE_API_NAME, API_PROVIDER, SAMPLE_API_VERSION);
    String path =
            APIConstants.API_ROOT_LOCATION + RegistryConstants.PATH_SEPARATOR + apiIdentifier.getProviderName()
                    + RegistryConstants.PATH_SEPARATOR + apiIdentifier.getApiName()
                    + RegistryConstants.PATH_SEPARATOR + apiIdentifier.getVersion();
    Mockito.when(registry.resourceExists(path)).thenThrow(RegistryException.class).thenReturn(true);
    AbstractAPIManager abstractAPIManager = new AbstractAPIManagerWrapper(registry);
    try {
        abstractAPIManager.isAPIAvailable(apiIdentifier);
        Assert.fail("Exception not thrown for error scenario");
    } catch (APIManagementException e) {
        Assert.assertTrue(e.getMessage().contains("Failed to check availability of api"));
    }
    Assert.assertTrue(abstractAPIManager.isAPIAvailable(apiIdentifier));
}
 
Example #16
Source File: AbstractAPIManager.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
public Set<String> getAPIVersions(String providerName, String apiName)
        throws APIManagementException {

    Set<String> versionSet = new HashSet<String>();
    String apiPath = APIConstants.API_LOCATION + RegistryConstants.PATH_SEPARATOR +
            providerName + RegistryConstants.PATH_SEPARATOR + apiName;
    try {
        Resource resource = registry.get(apiPath);
        if (resource instanceof Collection) {
            Collection collection = (Collection) resource;
            String[] versionPaths = collection.getChildren();
            if (versionPaths == null || versionPaths.length == 0) {
                return versionSet;
            }
            for (String path : versionPaths) {
                versionSet.add(path.substring(apiPath.length() + 1));
            }
        } else {
            throw new APIManagementException("API version must be a collection " + apiName);
        }
    } catch (RegistryException e) {
        String msg = "Failed to get versions for API: " + apiName;
        throw new APIManagementException(msg, e);
    }
    return versionSet;
}
 
Example #17
Source File: AbstractAPIManager.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * get the thumbnailLastUpdatedTime for a thumbnail for a given api
 *
 * @param apiIdentifier
 * @return
 * @throws APIManagementException
 */
@Override
public String getThumbnailLastUpdatedTime(APIIdentifier apiIdentifier) throws APIManagementException {
    String artifactPath = APIConstants.API_IMAGE_LOCATION + RegistryConstants.PATH_SEPARATOR +
            apiIdentifier.getProviderName() + RegistryConstants.PATH_SEPARATOR +
            apiIdentifier.getApiName() + RegistryConstants.PATH_SEPARATOR + apiIdentifier.getVersion();

    String thumbPath = artifactPath + RegistryConstants.PATH_SEPARATOR + APIConstants.API_ICON_IMAGE;
    try {
        if (registry.resourceExists(thumbPath)) {
            Resource res = registry.get(thumbPath);
            Date lastModifiedTime = res.getLastModified();
            return lastModifiedTime == null ? String.valueOf(res.getCreatedTime().getTime()) : String.valueOf(lastModifiedTime.getTime());
        }
    } catch (RegistryException e) {
        String msg = "Error while loading API icon from the registry";
        throw new APIManagementException(msg, e);
    }
    return null;

}
 
Example #18
Source File: APIUtilTest.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Test
public void testIsPerAPISequenceResourceMissing() throws Exception {
    APIIdentifier apiIdentifier = Mockito.mock(APIIdentifier.class);

    ServiceReferenceHolder serviceReferenceHolder = Mockito.mock(ServiceReferenceHolder.class);
    RegistryService registryService = Mockito.mock(RegistryService.class);
    UserRegistry registry = Mockito.mock(UserRegistry.class);

    String artifactPath = APIConstants.API_ROOT_LOCATION + RegistryConstants.PATH_SEPARATOR +
            apiIdentifier.getProviderName() + RegistryConstants.PATH_SEPARATOR +
            apiIdentifier.getApiName() + RegistryConstants.PATH_SEPARATOR + apiIdentifier.getVersion();
    String path = artifactPath + RegistryConstants.PATH_SEPARATOR + "in" + RegistryConstants.PATH_SEPARATOR;

    PowerMockito.mockStatic(ServiceReferenceHolder.class);
    Mockito.when(ServiceReferenceHolder.getInstance()).thenReturn(serviceReferenceHolder);
    Mockito.when(serviceReferenceHolder.getRegistryService()).thenReturn(registryService);
    Mockito.when(registryService.getGovernanceSystemRegistry(eq(1))).thenReturn(registry);
    Mockito.when(registry.resourceExists(eq(path))).thenReturn(false);

    boolean isPerAPiSequence = APIUtil.isPerAPISequence("sample", 1, apiIdentifier, "in");

    Assert.assertFalse(isPerAPiSequence);
}
 
Example #19
Source File: RegistryCacheInvalidationClient.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * Invalidates the registry cache for tiers.xml of given tenant domain
 * @param tenantDomain
 * @throws APIManagementException
 */
public void clearTiersResourceCache(String tenantDomain) throws APIManagementException {
    String cookie;

    // Clear Gateway Cache
    try {
        String gatewayServerURL;
        for (Map.Entry<String, Environment> entry : environments.entrySet()) {
            Environment environment = entry.getValue();
            gatewayServerURL = environment.getServerURL();
            cookie = login(gatewayServerURL, environment.getUserName(), environment.getPassword());
            clearCache(RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH 
                       + APIConstants.API_TIER_LOCATION, tenantDomain, gatewayServerURL, cookie);                
        }
    } catch (AxisFault axisFault) {
        log.error("Error while initializing the OAuth admin service stub in Store for tenant : " + tenantDomain,
                  axisFault);
    } catch (RemoteException e) {
        log.error("Error while invalidating the tiers.xml cache in gateway for tenant : " + tenantDomain, e);
    }
    
}
 
Example #20
Source File: APIUtilTest.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Test
public void testIsPerAPISequenceSequenceMissing() throws Exception {
    APIIdentifier apiIdentifier = Mockito.mock(APIIdentifier.class);

    ServiceReferenceHolder serviceReferenceHolder = Mockito.mock(ServiceReferenceHolder.class);
    RegistryService registryService = Mockito.mock(RegistryService.class);
    UserRegistry registry = Mockito.mock(UserRegistry.class);

    String artifactPath = APIConstants.API_ROOT_LOCATION + RegistryConstants.PATH_SEPARATOR +
            apiIdentifier.getProviderName() + RegistryConstants.PATH_SEPARATOR +
            apiIdentifier.getApiName() + RegistryConstants.PATH_SEPARATOR + apiIdentifier.getVersion();
    String path = artifactPath + RegistryConstants.PATH_SEPARATOR + "in" + RegistryConstants.PATH_SEPARATOR;

    PowerMockito.mockStatic(ServiceReferenceHolder.class);
    Mockito.when(ServiceReferenceHolder.getInstance()).thenReturn(serviceReferenceHolder);
    Mockito.when(serviceReferenceHolder.getRegistryService()).thenReturn(registryService);
    Mockito.when(registryService.getGovernanceSystemRegistry(eq(1))).thenReturn(registry);
    Mockito.when(registry.resourceExists(eq(path))).thenReturn(true);
    Mockito.when(registry.get(eq(path))).thenReturn(null);

    boolean isPerAPiSequence = APIUtil.isPerAPISequence("sample", 1, apiIdentifier, "in");

    Assert.assertFalse(isPerAPiSequence);
}
 
Example #21
Source File: RegistryClient.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
public void copyRegistryResourceFromRemoteToLocal(String path) throws OnPremiseGatewayException {
    log.info("Synchronizing the registry resource "+ path);
    String govRegistryPath = RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH + path;
    try {
        if (remoteRegistry.resourceExists(govRegistryPath)) {
            Resource resource = remoteRegistry.get(govRegistryPath);
            governanceRegistry.put(path, resource);
            log.info("Successfully copied the registry resource: "+path);
        } else {
            log.warn("Registry resource at path:" + path + " does not exists.");
        }
    } catch (RegistryException e) {
        String errorMsg = "Failed to copy registry resource at path:" + path + " to local server.";
        log.error(errorMsg, e);
        throw new OnPremiseGatewayException(errorMsg, e);
    }
}
 
Example #22
Source File: GovernanceRegistrySyncClient.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
public void copyRegistryResourceFromRemoteToLocal(String path) throws OnPremiseGatewayException {
    log.info("Synchronizing the registry resource " + path);
    String govRegistryPath = RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH + path;
    try {
        if (remoteRegistry.resourceExists(govRegistryPath)) {
            Resource resource = remoteRegistry.get(govRegistryPath);
            governanceRegistry.put(path, resource);
            log.info("Successfully copied the registry resource: " + path);
        } else {
            log.warn("Registry resource at path:" + path + " does not exists.");
        }
    } catch (RegistryException e) {
        String errorMsg = "Failed to copy registry resource at path:" + path + " to local server.";
        log.error(errorMsg, e);
        throw new OnPremiseGatewayException(errorMsg, e);
    }
}
 
Example #23
Source File: Utils.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
/**
 * gets no of verified user challenges
 *
 * @param userDTO bean class that contains user and tenant Information
 * @return no of verified challenges
 * @throws IdentityException if fails
 */
public static int getVerifiedChallenges(UserDTO userDTO) throws IdentityException {

    int noOfChallenges = 0;

    try {
        UserRegistry registry = IdentityMgtServiceComponent.getRegistryService().
                getConfigSystemRegistry(MultitenantConstants.SUPER_TENANT_ID);
        String identityKeyMgtPath = IdentityMgtConstants.IDENTITY_MANAGEMENT_CHALLENGES +
                RegistryConstants.PATH_SEPARATOR + userDTO.getUserId() +
                RegistryConstants.PATH_SEPARATOR + userDTO.getUserId();

        Resource resource;
        if (registry.resourceExists(identityKeyMgtPath)) {
            resource = registry.get(identityKeyMgtPath);
            String property = resource.getProperty(IdentityMgtConstants.VERIFIED_CHALLENGES);
            if (property != null) {
                return Integer.parseInt(property);
            }
        }
    } catch (RegistryException e) {
        log.error("Error while processing userKey", e);
    }

    return noOfChallenges;
}
 
Example #24
Source File: OAuthConsumerDAO.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
/**
 * @param ppid
 * @return
 * @throws IdentityException
 */
public String getOAuthConsumerSecret(String consumerKey) throws IdentityException {
    String path = null;
    Resource resource = null;

    if (log.isDebugEnabled()) {
        log.debug("Retreiving user for OAuth consumer key  " + consumerKey);
    }

    try {
        path = RegistryConstants.PROFILES_PATH + consumerKey;
        if (registry.resourceExists(path)) {
            resource = registry.get(path);
            return resource.getProperty(IdentityRegistryResources.OAUTH_CONSUMER_PATH);
        } else {
            return null;
        }
    } catch (RegistryException e) {
        log.error("Error while retreiving user for OAuth consumer key  " + consumerKey, e);
        throw IdentityException.error("Error while retreiving user for OAuth consumer key  "
                + consumerKey, e);
    }
}
 
Example #25
Source File: AbstractAPIManagerTestCase.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Test
public void testIsDocumentationExist() throws APIManagementException, RegistryException {
    AbstractAPIManager abstractAPIManager = new AbstractAPIManagerWrapper(registry);
    APIIdentifier identifier = getAPIIdentifier(SAMPLE_API_NAME, API_PROVIDER, SAMPLE_API_VERSION);
    String docName = "sampleDoc";
    String docPath =
            APIConstants.API_ROOT_LOCATION + RegistryConstants.PATH_SEPARATOR + identifier.getProviderName()
                    + RegistryConstants.PATH_SEPARATOR + identifier.getApiName() + RegistryConstants.PATH_SEPARATOR
                    + identifier.getVersion() + RegistryConstants.PATH_SEPARATOR + APIConstants.DOC_DIR
                    + RegistryConstants.PATH_SEPARATOR + docName;
    Mockito.when(registry.resourceExists(docPath)).thenThrow(RegistryException.class).thenReturn(true);
    try {
        abstractAPIManager.isDocumentationExist(identifier, docName);
        Assert.fail("Registry exception not thrown for error scenario");
    } catch (APIManagementException e) {
        Assert.assertTrue(e.getMessage().contains("Failed to check existence of the document"));
    }
    Assert.assertTrue(abstractAPIManager.isDocumentationExist(identifier, docName));
}
 
Example #26
Source File: APIUtilTest.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Test
public void testIsPerAPISequence() throws Exception {
    APIIdentifier apiIdentifier = Mockito.mock(APIIdentifier.class);

    ServiceReferenceHolder serviceReferenceHolder = Mockito.mock(ServiceReferenceHolder.class);
    RegistryService registryService = Mockito.mock(RegistryService.class);
    UserRegistry registry = Mockito.mock(UserRegistry.class);

    String artifactPath = APIConstants.API_ROOT_LOCATION + RegistryConstants.PATH_SEPARATOR +
            apiIdentifier.getProviderName() + RegistryConstants.PATH_SEPARATOR +
            apiIdentifier.getApiName() + RegistryConstants.PATH_SEPARATOR + apiIdentifier.getVersion();
    String path = artifactPath + RegistryConstants.PATH_SEPARATOR + "in" + RegistryConstants.PATH_SEPARATOR;

    PowerMockito.mockStatic(ServiceReferenceHolder.class);
    Mockito.when(ServiceReferenceHolder.getInstance()).thenReturn(serviceReferenceHolder);
    Mockito.when(serviceReferenceHolder.getRegistryService()).thenReturn(registryService);
    Mockito.when(registryService.getGovernanceSystemRegistry(eq(1))).thenReturn(registry);
    Mockito.when(registry.resourceExists(eq(path))).thenReturn(true);

    Collection collection = Mockito.mock(Collection.class);
    Mockito.when(registry.get(eq(path))).thenReturn(collection);

    String[] childPaths = {"test"};
    Mockito.when(collection.getChildren()).thenReturn(childPaths);

    InputStream sampleSequence = new FileInputStream(Thread.currentThread().getContextClassLoader().
                    getResource("sampleSequence.xml").getFile());
    Resource resource = Mockito.mock(Resource.class);
    Mockito.when(registry.get(eq("test"))).thenReturn(resource);
    Mockito.when(resource.getContentStream()).thenReturn(sampleSequence);

    boolean isPerAPiSequence = APIUtil.isPerAPISequence("sample", 1, apiIdentifier, "in");

    Assert.assertTrue(isPerAPiSequence);
}
 
Example #27
Source File: AbstractAPIManager.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * Returns Registry resource matching given mediation policy identifier
 *
 * @param identifier API identifier
 * @param uuid         mediation policy identifier
 * @param resourcePath registry path to the API resource
 * @return Registry resource matches given identifier or null
 * @throws APIManagementException If fails to get the resource matching given identifier
 */
@Override
public Resource getApiSpecificMediationResourceFromUuid(Identifier identifier, String uuid, String resourcePath)
        throws APIManagementException {
    try {
        Resource resource = registry.get(resourcePath);
        if (resource instanceof Collection) {
            Collection typeCollection = (Collection) resource;
            String[] typeArray = typeCollection.getChildren();
            for (String type : typeArray) {
                //Check for mediation policy resource
                if ((type.equalsIgnoreCase(resourcePath + RegistryConstants.PATH_SEPARATOR +
                        APIConstants.API_CUSTOM_SEQUENCE_TYPE_IN)) ||
                        (type.equalsIgnoreCase(resourcePath + RegistryConstants.PATH_SEPARATOR +
                                APIConstants.API_CUSTOM_SEQUENCE_TYPE_OUT)) ||
                        (type.equalsIgnoreCase(resourcePath + RegistryConstants.PATH_SEPARATOR +
                                APIConstants.API_CUSTOM_SEQUENCE_TYPE_FAULT))) {
                    Resource sequenceType = registry.get(type);
                    //sequenceType eg: in / out /fault
                    if (sequenceType instanceof Collection) {
                        String[] mediationPolicyArr = ((Collection) sequenceType).getChildren();
                        for (String mediationPolicy : mediationPolicyArr) {
                            Resource mediationResource = registry.get(mediationPolicy);
                            String resourceId = mediationResource.getUUID();
                            if (resourceId.equalsIgnoreCase(uuid)) {
                                return mediationResource;
                            }
                        }
                    }
                }
            }
        }
    } catch (RegistryException e) {
        String msg = "Error while obtaining registry objects";
        throw new APIManagementException(msg, e);
    }
    return null;
}
 
Example #28
Source File: RegistrySubscriptionManager.java    From carbon-commons with Apache License 2.0 5 votes vote down vote up
/**
 * Calculates the JMS subscription stored path for a WSSubscription using subscription id and
 * the topic name.
 *
 * @param subscriptionID the subscription ID
 * @param topicName      the topic name
 * @return the JMS subscription resource path for a subscription
 */
private String getJMSSubResourcePath(String subscriptionID, String topicName) {
    String resourcePath = this.topicStoragePath;

    // first convert the . to /
    topicName = topicName.replaceAll("\\.", RegistryConstants.PATH_SEPARATOR);

    if (!topicName.startsWith(RegistryConstants.PATH_SEPARATOR)) {
        resourcePath = resourcePath + RegistryConstants.PATH_SEPARATOR;
    }

    // this topic name can have # and * marks if the user wants to subscribes to the
    // child topics as well. but we consider the topic here as the topic name just before any
    // special character.
    // eg. if topic name is myTopic/*/* then topic name is myTopic
    if (topicName.indexOf(STAR_WILDCARD) > -1) {
        topicName = topicName.substring(0, topicName.indexOf(STAR_WILDCARD));
    } else if (topicName.indexOf(HASH_WILDCARD) > -1) {
        topicName = topicName.substring(0, topicName.indexOf(HASH_WILDCARD));
    }

    resourcePath = resourcePath + topicName;

    if (!resourcePath.endsWith(RegistryConstants.PATH_SEPARATOR)) {
        resourcePath = resourcePath + RegistryConstants.PATH_SEPARATOR;
    }
    resourcePath = resourcePath +
                   (EventBrokerConstants.EB_CONF_JMS_SUBSCRIPTION_COLLECTION_NAME +
                    RegistryConstants.PATH_SEPARATOR + subscriptionID);
    return resourcePath;
}
 
Example #29
Source File: RegistrySubscriptionManager.java    From carbon-commons with Apache License 2.0 5 votes vote down vote up
/**
 * Calculates the resource stored path using subscription id and the topic name.
 *
 * @param subscriptionID the subscription ID
 * @param topicName      topic name
 * @return the resource path
 */
private String getResourcePath(String subscriptionID, String topicName) {
    String resourcePath = this.topicStoragePath;

    // first convert the . to /
    topicName = topicName.replaceAll("\\.", RegistryConstants.PATH_SEPARATOR);

    if (!topicName.startsWith(RegistryConstants.PATH_SEPARATOR)) {
        resourcePath = resourcePath + RegistryConstants.PATH_SEPARATOR;
    }

    // this topic name can have # and * marks if the user wants to subscribes to the
    // child topics as well. but we consider the topic here as the topic name just before any
    // special character.
    // eg. if topic name is myTopic/*/* then topic name is myTopic
    if (topicName.indexOf(STAR_WILDCARD) > -1) {
        topicName = topicName.substring(0, topicName.indexOf(STAR_WILDCARD));
    } else {
        if (topicName.indexOf(HASH_WILDCARD) > -1) {
            topicName = topicName.substring(0, topicName.indexOf(HASH_WILDCARD));
        }
    }

    resourcePath = resourcePath + topicName;

    if (!resourcePath.endsWith(RegistryConstants.PATH_SEPARATOR)) {
        resourcePath = resourcePath + RegistryConstants.PATH_SEPARATOR;
    }

    resourcePath = resourcePath + EventBrokerConstants.EB_CONF_WS_SUBSCRIPTION_COLLECTION_NAME +
                   RegistryConstants.PATH_SEPARATOR + subscriptionID;
    return resourcePath;
}
 
Example #30
Source File: APIUtilTest.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetMediationSequenceUuidCustomSequence() throws Exception {
    APIIdentifier apiIdentifier = Mockito.mock(APIIdentifier.class);

    ServiceReferenceHolder serviceReferenceHolder = Mockito.mock(ServiceReferenceHolder.class);
    RegistryService registryService = Mockito.mock(RegistryService.class);
    UserRegistry registry = Mockito.mock(UserRegistry.class);

    PowerMockito.mockStatic(ServiceReferenceHolder.class);
    Mockito.when(ServiceReferenceHolder.getInstance()).thenReturn(serviceReferenceHolder);
    Mockito.when(serviceReferenceHolder.getRegistryService()).thenReturn(registryService);
    Mockito.when(registryService.getGovernanceSystemRegistry(eq(1))).thenReturn(registry);

    Collection collection = Mockito.mock(Collection.class);
    String artifactPath = APIConstants.API_ROOT_LOCATION + RegistryConstants.PATH_SEPARATOR +
            apiIdentifier.getProviderName() + RegistryConstants.PATH_SEPARATOR +
            apiIdentifier.getApiName() + RegistryConstants.PATH_SEPARATOR + apiIdentifier.getVersion();
    String path = artifactPath + RegistryConstants.PATH_SEPARATOR + "custom" + RegistryConstants.PATH_SEPARATOR;

    Mockito.when(registry.get(eq(path))).thenReturn(collection);

    String[] childPaths = {"test"};
    Mockito.when(collection.getChildren()).thenReturn(childPaths);

    String expectedUUID = UUID.randomUUID().toString();

    InputStream sampleSequence = new FileInputStream(Thread.currentThread().getContextClassLoader().
            getResource("sampleSequence.xml").getFile());

    Resource resource = Mockito.mock(Resource.class);
    Mockito.when(registry.get(eq("test"))).thenReturn(resource);
    Mockito.when(resource.getContentStream()).thenReturn(sampleSequence);
    Mockito.when(resource.getUUID()).thenReturn(expectedUUID);


    String actualUUID = APIUtil.getMediationSequenceUuid("sample", 1, "custom", apiIdentifier);

    Assert.assertEquals(expectedUUID, actualUUID);
    sampleSequence.close();
}