org.wso2.carbon.context.RegistryType Java Examples

The following examples show how to use org.wso2.carbon.context.RegistryType. 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: StratosApiV41Utils.java    From attic-stratos with Apache License 2.0 6 votes vote down vote up
private static void clearMetadata(String applicationId) throws RestAPIException {

        PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
        ctx.setTenantId(MultitenantConstants.SUPER_TENANT_ID);
        ctx.setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);

        String resourcePath = METADATA_REG_PATH + applicationId;
        Registry registry = (UserRegistry) PrivilegedCarbonContext.getThreadLocalCarbonContext()
                .getRegistry(RegistryType.SYSTEM_GOVERNANCE);
        try {
            registry.beginTransaction();
            if (registry.resourceExists(resourcePath)) {
                registry.delete(resourcePath);
                log.info(String.format("Application metadata removed: [application-id] %s", applicationId));
            }
            registry.commitTransaction();
        } catch (RegistryException e) {
            try {
                registry.rollbackTransaction();
            } catch (RegistryException e1) {
                log.error("Could not rollback transaction", e1);
            }
            throw new RestAPIException(
                    String.format("Application metadata removed: [application-id] %s", applicationId), e);
        }
    }
 
Example #2
Source File: ApplicationMgtUtil.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
/**
 * Delete the resource
 *
 * @param applicationName
 * @throws IdentityApplicationManagementException
 */
public static void deletePermissions(String applicationName) throws IdentityApplicationManagementException {

    String applicationNode = getApplicationPermissionPath() + PATH_CONSTANT + applicationName;
    Registry tenantGovReg = CarbonContext.getThreadLocalCarbonContext().getRegistry(
            RegistryType.USER_GOVERNANCE);

    try {
        boolean exist = tenantGovReg.resourceExists(applicationNode);

        if (exist) {
            tenantGovReg.delete(applicationNode);
        }

    } catch (RegistryException e) {
        throw new IdentityApplicationManagementException("Error while storing permissions", e);
    }
}
 
Example #3
Source File: IdPInitSSOAuthnRequestProcessor.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the configured service provider configurations. The
 * configurations are taken from the user registry or from the
 * sso-idp-config.xml configuration file. In Stratos deployment the
 * configurations are read from the sso-idp-config.xml file.
 *
 * @param authnReqDTO
 * @return
 * @throws IdentityException
 */
private SAMLSSOServiceProviderDO getServiceProviderConfig(SAMLSSOAuthnReqDTO authnReqDTO)
        throws IdentityException {
    try {
        SSOServiceProviderConfigManager stratosIdpConfigManager = SSOServiceProviderConfigManager
                .getInstance();
        SAMLSSOServiceProviderDO ssoIdpConfigs = stratosIdpConfigManager
                .getServiceProvider(authnReqDTO.getIssuer());
        if (ssoIdpConfigs == null) {
            IdentityPersistenceManager persistenceManager = IdentityPersistenceManager
                    .getPersistanceManager();
            Registry registry = (Registry) PrivilegedCarbonContext.getThreadLocalCarbonContext().getRegistry(RegistryType.SYSTEM_CONFIGURATION);
            ssoIdpConfigs = persistenceManager.getServiceProvider(registry,
                    authnReqDTO.getIssuer());
            authnReqDTO.setStratosDeployment(false); // not stratos
        } else {
            authnReqDTO.setStratosDeployment(true); // stratos deployment
        }
        return ssoIdpConfigs;
    } catch (Exception e) {
        throw IdentityException.error("Error while reading Service Provider configurations", e);
    }
}
 
Example #4
Source File: ApplicationMgtUtil.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
/**
 * Rename the registry path node name for a deleted Service provider role.
 *
 * @param oldName
 * @param newName
 * @throws IdentityApplicationManagementException
 */
public static void renameAppPermissionPathNode(String oldName, String newName)
        throws IdentityApplicationManagementException {

    List<ApplicationPermission> loadPermissions = loadPermissions(oldName);
    String newApplicationNode = ApplicationMgtUtil.getApplicationPermissionPath() + PATH_CONSTANT + oldName;
    Registry tenantGovReg = CarbonContext.getThreadLocalCarbonContext().getRegistry(
            RegistryType.USER_GOVERNANCE);
    //creating new application node
    try {
        for (ApplicationPermission applicationPermission : loadPermissions) {
            tenantGovReg.delete(newApplicationNode + PATH_CONSTANT + applicationPermission.getValue());
        }
        tenantGovReg.delete(newApplicationNode);
        Collection permissionNode = tenantGovReg.newCollection();
        permissionNode.setProperty("name", newName);
        newApplicationNode = ApplicationMgtUtil.getApplicationPermissionPath() + PATH_CONSTANT + newName;
        ApplicationMgtUtil.applicationNode = newApplicationNode;
        tenantGovReg.put(newApplicationNode, permissionNode);
        addPermission(loadPermissions.toArray(new ApplicationPermission[loadPermissions.size()]), tenantGovReg);
    } catch (RegistryException e) {
        throw new IdentityApplicationManagementException("Error while renaming permission node "
                + oldName + "to " + newName, e);
    }
}
 
Example #5
Source File: SPInitSSOAuthnRequestProcessor.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the configured service provider configurations. The
 * configurations are taken from the user registry or from the
 * sso-idp-config.xml configuration file. In Stratos deployment the
 * configurations are read from the sso-idp-config.xml file.
 *
 * @param authnReqDTO
 * @return
 * @throws IdentityException
 */
private SAMLSSOServiceProviderDO getServiceProviderConfig(SAMLSSOAuthnReqDTO authnReqDTO)
        throws IdentityException {
    try {
        SSOServiceProviderConfigManager stratosIdpConfigManager = SSOServiceProviderConfigManager
                .getInstance();
        SAMLSSOServiceProviderDO ssoIdpConfigs = stratosIdpConfigManager
                .getServiceProvider(authnReqDTO.getIssuer());
        if (ssoIdpConfigs == null) {
            IdentityTenantUtil.initializeRegistry(PrivilegedCarbonContext.getThreadLocalCarbonContext()
                    .getTenantId(), PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain());
            IdentityPersistenceManager persistenceManager = IdentityPersistenceManager.getPersistanceManager();
            Registry registry = (Registry) PrivilegedCarbonContext.getThreadLocalCarbonContext().getRegistry
                    (RegistryType.SYSTEM_CONFIGURATION);
            ssoIdpConfigs = persistenceManager.getServiceProvider(registry, authnReqDTO.getIssuer());
            authnReqDTO.setStratosDeployment(false); // not stratos
        } else {
            authnReqDTO.setStratosDeployment(true); // stratos deployment
        }
        return ssoIdpConfigs;
    } catch (Exception e) {
        throw IdentityException.error("Error while reading Service Provider configurations", e);
    }
}
 
Example #6
Source File: RegistryBasedResourceLoader.java    From carbon-device-mgt with Apache License 2.0 6 votes vote down vote up
@Override
public InputStream getResourceStream(String name) throws ResourceNotFoundException {
    try {
        Registry registry =
                CarbonContext.getThreadLocalCarbonContext().getRegistry(RegistryType.SYSTEM_CONFIGURATION);
        if (registry == null) {
            throw new IllegalStateException("No valid registry instance is attached to the current carbon context");
        }
        if (!registry.resourceExists(EMAIL_CONFIG_BASE_LOCATION + "/" + name)) {
            throw new ResourceNotFoundException("Resource '" + name + "' does not exist");
        }
        org.wso2.carbon.registry.api.Resource resource =
                registry.get(EMAIL_CONFIG_BASE_LOCATION + "/" + name);
        resource.setMediaType("text/plain");
        return resource.getContentStream();
    } catch (RegistryException e) {
        throw new ResourceNotFoundException("Error occurred while retrieving resource", e);
    }
}
 
Example #7
Source File: APIManagerComponentPermissionsTest.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Before
public void setup() throws Exception {
    PowerMockito.mockStatic(CarbonContext.class);
    PowerMockito.mockStatic(APIUtil.class);
    CarbonContext carbonContext = Mockito.mock(CarbonContext.class);
    realm = Mockito.mock(UserRealm.class);
    componentContext = Mockito.mock(ComponentContext.class);
    registry = Mockito.mock(Registry.class);

    Mockito.when(carbonContext.getRegistry(RegistryType.USER_GOVERNANCE)).thenReturn(registry);
    Mockito.when(carbonContext.getUsername()).thenReturn(USER_NAME);
    Mockito.when(carbonContext.getUserRealm()).thenReturn(realm);
    PowerMockito.when(CarbonContext.getThreadLocalCarbonContext()).thenReturn(carbonContext);
    PowerMockito.when(APIUtil.class, "loadTenantExternalStoreConfig",
            MultitenantConstants.SUPER_TENANT_ID).thenThrow(IndexOutOfBoundsException.class);
}
 
Example #8
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 #9
Source File: ApplicationMgtUtil.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
/**
 * Delete the resource
 *
 * @param applicationName
 * @throws IdentityApplicationManagementException
 */
public static void deletePermissions(String applicationName) throws IdentityApplicationManagementException {

    String applicationNode = getApplicationPermissionPath() + PATH_CONSTANT + applicationName;
    Registry tenantGovReg = CarbonContext.getThreadLocalCarbonContext().getRegistry(
            RegistryType.USER_GOVERNANCE);

    try {
        boolean exist = tenantGovReg.resourceExists(applicationNode);

        if (exist) {
            tenantGovReg.delete(applicationNode);
        }

    } catch (RegistryException e) {
        throw new IdentityApplicationManagementException("Error while storing permissions", e);
    }
}
 
Example #10
Source File: MessageSender.java    From carbon-commons with Apache License 2.0 6 votes vote down vote up
private ServiceClient initServiceClient(String epr, int notificationType,
                                        AxisConfiguration axisConf) throws Exception {

    ConfigurationContext cfgCtx = ConfigHolder.getInstance().getClientConfigurationContext();
    ServiceClient serviceClient = new ServiceClient(cfgCtx, null);
    serviceClient.setTargetEPR(new EndpointReference(epr));
    if (notificationType == DiscoveryConstants.NOTIFICATION_TYPE_HELLO) {
        serviceClient.getOptions().setAction(DiscoveryConstants.WS_DISCOVERY_HELLO_ACTION);
    } else {
        serviceClient.getOptions().setAction(DiscoveryConstants.WS_DISCOVERY_BYE_ACTION);
    }

    serviceClient.engageModule("addressing");

    Registry registry = (Registry)PrivilegedCarbonContext.getThreadLocalCarbonContext().getRegistry(
            RegistryType.SYSTEM_CONFIGURATION);
    Policy policy = DiscoveryMgtUtils.getClientSecurityPolicy(registry);
    if (policy != null) {
        serviceClient.engageModule("rampart");
        serviceClient.getOptions().setProperty(
                DiscoveryConstants.KEY_RAMPART_POLICY, policy);
    }

    return serviceClient;
}
 
Example #11
Source File: ApplicationMgtUtil.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
/**
 * Rename the registry path node name for a deleted Service provider role.
 *
 * @param oldName
 * @param newName
 * @throws IdentityApplicationManagementException
 */
public static void renameAppPermissionPathNode(String oldName, String newName)
        throws IdentityApplicationManagementException {

    List<ApplicationPermission> loadPermissions = loadPermissions(oldName);
    String newApplicationNode = ApplicationMgtUtil.getApplicationPermissionPath() + PATH_CONSTANT + oldName;
    Registry tenantGovReg = CarbonContext.getThreadLocalCarbonContext().getRegistry(
            RegistryType.USER_GOVERNANCE);
    //creating new application node
    try {
        for (ApplicationPermission applicationPermission : loadPermissions) {
            tenantGovReg.delete(newApplicationNode + PATH_CONSTANT + applicationPermission.getValue());
        }
        tenantGovReg.delete(newApplicationNode);
        Collection permissionNode = tenantGovReg.newCollection();
        permissionNode.setProperty("name", newName);
        newApplicationNode = ApplicationMgtUtil.getApplicationPermissionPath() + PATH_CONSTANT + newName;
        String applicationNode = newApplicationNode;
        tenantGovReg.put(newApplicationNode, permissionNode);
        addPermission(applicationNode, loadPermissions.toArray(new ApplicationPermission[loadPermissions.size()]),
                tenantGovReg);
    } catch (RegistryException e) {
        throw new IdentityApplicationManagementException("Error while renaming permission node "
                + oldName + "to " + newName, e);
    }
}
 
Example #12
Source File: DiscoveryMgtUtils.java    From carbon-commons with Apache License 2.0 5 votes vote down vote up
/**
 * Get the URL of the remote WS-Discovery proxy. This method first attempts to get the URL
 * from the AxisConfiguration. If discovery is not enabled, it will attempt to retrieve the
 * URL from the configuration registry.
 *
 * @param axisConfig AxisConfiguration instance
 * @return URL of the proxy or null
 * @throws RegistryException on error
 */
public static String getDiscoveryProxyURL(AxisConfiguration axisConfig) throws RegistryException {
    Parameter parameter = getDiscoveryParam(axisConfig);
    if (parameter != null) {
        return parameter.getValue().toString();
    }

    Registry registry = PrivilegedCarbonContext.getThreadLocalCarbonContext().
            getRegistry(RegistryType.SYSTEM_CONFIGURATION);
    return getDiscoveryProxyURL(registry);
}
 
Example #13
Source File: DiscoveryMgtUtils.java    From carbon-commons with Apache License 2.0 5 votes vote down vote up
/**
 * Check whether service discovery is enabled in the configuration. This method first checks
 * whether the DiscoveryConstants.DISCOVERY_PROXY parameter is set in the given AxisConfiguration.
 * If not it checks whether service discovery status is set to 'true' in the configuration
 * registry. If discovery is enabled in the registry configuration, this method will also
 * add the corresponding parameter to AxisConfiguration.
 *
 * @param axisConfig AxisConfiguration
 * @return service discovery status
 * @throws RegistryException if an error occurs while accessing the registry
 */
public static boolean isServiceDiscoveryEnabled(AxisConfiguration axisConfig) throws RegistryException {
    Parameter parameter = getDiscoveryParam(axisConfig);
    if (parameter != null) {
        return true;
    }

    String path = DISCOVERY_CONFIG_ROOT + DISCOVERY_PUBLISHER_CONFIG;

    Registry registry = PrivilegedCarbonContext.getThreadLocalCarbonContext().
            getRegistry(RegistryType.SYSTEM_CONFIGURATION);
    if (registry.resourceExists(path)) {
        Resource publisherConfig = registry.get(path);
        String status = publisherConfig.getProperty(DISCOVERY_PUBLISHER_STATUS);
        publisherConfig.discard();
        boolean enabled = JavaUtils.isTrueExplicitly(status);

        if (enabled) {
            String discoveryProxyURL = getDiscoveryProxyURL(registry);
            try {
                Parameter discoveryProxyParam =
                        ParameterUtil.createParameter(DiscoveryConstants.DISCOVERY_PROXY,
                                                      discoveryProxyURL);
                axisConfig.addParameter(discoveryProxyParam);
            } catch (AxisFault axisFault) {
                axisFault.printStackTrace();  //TODO
            }
        }
        return enabled;
    }

    return false;
}
 
Example #14
Source File: MessageSender.java    From carbon-commons with Apache License 2.0 5 votes vote down vote up
private String getServiceID(Config config, AxisService service) throws Exception {

        String uniqueID = config.getUniqueId();
        if (uniqueID == null) {
            // Get the unique id from the registry.
            // Use the service to get hold of the Carbon context of the tenant
            // to which the service belongs
            Registry registry = (Registry) PrivilegedCarbonContext.getThreadLocalCarbonContext().
                    getRegistry(RegistryType.SYSTEM_CONFIGURATION);
            uniqueID = DiscoveryMgtUtils.getExistingServiceIdOrUpdate(getNameForService(service),
                    UIDGenerator.generateURNString(), registry);
        }
        return uniqueID;
    }
 
Example #15
Source File: APIManagerComponentImagePermissionTest.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() throws Exception {
    PowerMockito.mockStatic(ServiceReferenceHolder.class);
    PowerMockito.mockStatic(APIUtil.class);
    PowerMockito.mockStatic(CarbonContext.class);
    PowerMockito.mockStatic(RegistryUtils.class);
    PowerMockito.mockStatic(APIMgtDBUtil.class);
    authManager = Mockito.mock(AuthorizationManager.class);
    serviceReferenceHolder = Mockito.mock(ServiceReferenceHolder.class);
    realmService = Mockito.mock(RealmService.class);
    componentContext = Mockito.mock(ComponentContext.class);
    BundleContext bundleContext = Mockito.mock(BundleContext.class);
    UserRealm userRealm = Mockito.mock(UserRealm.class);
    Registry registry = Mockito.mock(Registry.class);
    CarbonContext carbonContext = Mockito.mock(CarbonContext.class);
    APIManagerConfiguration configuration = Mockito.mock(APIManagerConfiguration.class);

    Mockito.when(componentContext.getBundleContext()).thenReturn(bundleContext);
    Mockito.when(realmService.getTenantUserRealm(MultitenantConstants.SUPER_TENANT_ID)).thenReturn(userRealm);
    Mockito.when(serviceReferenceHolder.getRealmService()).thenReturn(realmService);
    Mockito.when(userRealm.getAuthorizationManager()).thenReturn(authManager);
    Mockito.when(registry.resourceExists(Mockito.anyString())).thenReturn(true);
    Mockito.when(carbonContext.getRegistry(RegistryType.USER_GOVERNANCE)).thenReturn(registry);
    Mockito.doNothing().when(configuration).load(Mockito.anyString());
    Mockito.when(configuration.getFirstProperty(Mockito.anyString())).thenReturn("");
    PowerMockito.when(ServiceReferenceHolder.getInstance()).thenReturn(serviceReferenceHolder);
    PowerMockito.when(APIUtil.getMountedPath(null, "")).thenReturn("");
    PowerMockito.when(RegistryUtils.getAbsolutePath(null, null)).thenReturn("");
    PowerMockito.when(CarbonContext.getThreadLocalCarbonContext()).thenReturn(carbonContext);
    PowerMockito.when(APIUtil.getMountedPath(Mockito.any(RegistryContext.class), Mockito.anyString()))
            .thenReturn("");
    PowerMockito.doThrow(new IndexOutOfBoundsException()).when(APIMgtDBUtil.class, "initialize");
    PowerMockito.whenNew(APIManagerConfiguration.class).withAnyArguments().thenReturn(configuration);
}
 
Example #16
Source File: SelfSignupUtilTestCase.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetSelfSignupConfigFromRegistryTenant() throws Exception {
    System.setProperty(CARBON_HOME, "");
    PrivilegedCarbonContext privilegedCarbonContext = Mockito.mock(PrivilegedCarbonContext.class);
    PowerMockito.mockStatic(PrivilegedCarbonContext.class);
    PowerMockito.when(PrivilegedCarbonContext.getThreadLocalCarbonContext()).thenReturn(privilegedCarbonContext);
    Mockito.when(privilegedCarbonContext.getTenantDomain()).thenReturn("foo.com");
    Mockito.when(privilegedCarbonContext.getRegistry(RegistryType.SYSTEM_GOVERNANCE)).thenReturn(registry);

    PowerMockito.mockStatic(ServiceReferenceHolder.class);
    ServiceReferenceHolder serviceReferenceHolder = Mockito.mock(ServiceReferenceHolder.class);
    PowerMockito.when(ServiceReferenceHolder.getInstance()).thenReturn(serviceReferenceHolder);
    RealmService realmService = Mockito.mock(RealmService.class);
    Mockito.when(serviceReferenceHolder.getRealmService()).thenReturn(realmService);
    TenantManager tenantManager = Mockito.mock(TenantManager.class);
    Mockito.when(realmService.getTenantManager()).thenReturn(tenantManager);
    Mockito.when(tenantManager.getTenantId("foo.com")).thenReturn(4444);

    PowerMockito.mockStatic(APIUtil.class);
    Mockito.when(registry.resourceExists(APIConstants.SELF_SIGN_UP_CONFIG_LOCATION)).thenReturn(true);
    Resource resource = Mockito.mock(Resource.class);
    Mockito.when(resource.getContent()).thenReturn("wsdl".getBytes());
    Mockito.when(registry.get(APIConstants.SELF_SIGN_UP_CONFIG_LOCATION)).thenReturn(resource);
    OMElement omElement = Mockito.mock(OMElement.class);
    Mockito.when(omElement.getFirstChildWithName(Matchers.any(QName.class))).thenReturn(omElement);
    PowerMockito.mockStatic(AXIOMUtil.class);
    Mockito.when(omElement.getChildrenWithLocalName(APIConstants.SELF_SIGN_UP_REG_ROLE_ELEM)).thenReturn(Mockito.mock(Iterator.class));
    PowerMockito.when(AXIOMUtil.stringToOM("wsdl")).thenReturn(omElement);
    PowerMockito.mockStatic(PasswordResolverFactory.class);
    PasswordResolver passwordResolver = Mockito.mock(PasswordResolver.class);
    PowerMockito.when(PasswordResolverFactory.getInstance()).thenReturn(passwordResolver);
    UserRegistrationConfigDTO userRegistrationConfigDTO = SelfSignUpUtil.getSignupConfiguration("bar.com");
    Assert.assertNotNull(userRegistrationConfigDTO);
    PowerMockito.verifyStatic(PrivilegedCarbonContext.class);
    PrivilegedCarbonContext.endTenantFlow();
}
 
Example #17
Source File: SelfSignupUtilTestCase.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetSelfSignupConfigFromRegistry() throws Exception {

    System.setProperty(CARBON_HOME, "");
    PrivilegedCarbonContext privilegedCarbonContext = Mockito.mock(PrivilegedCarbonContext.class);
    PowerMockito.mockStatic(PrivilegedCarbonContext.class);
    PowerMockito.when(PrivilegedCarbonContext.getThreadLocalCarbonContext()).thenReturn(privilegedCarbonContext);
    Mockito.when(privilegedCarbonContext.getTenantDomain()).thenReturn("foo.com");
    Mockito.when(privilegedCarbonContext.getRegistry(RegistryType.SYSTEM_GOVERNANCE)).thenReturn(registry);

    PowerMockito.mockStatic(ServiceReferenceHolder.class);
    ServiceReferenceHolder serviceReferenceHolder = Mockito.mock(ServiceReferenceHolder.class);
    PowerMockito.when(ServiceReferenceHolder.getInstance()).thenReturn(serviceReferenceHolder);
    RealmService realmService = Mockito.mock(RealmService.class);
    Mockito.when(serviceReferenceHolder.getRealmService()).thenReturn(realmService);
    TenantManager tenantManager = Mockito.mock(TenantManager.class);
    Mockito.when(realmService.getTenantManager()).thenReturn(tenantManager);
    Mockito.when(tenantManager.getTenantId("foo.com")).thenReturn(4444);

    PowerMockito.mockStatic(APIUtil.class);

    Mockito.when(registry.resourceExists(APIConstants.SELF_SIGN_UP_CONFIG_LOCATION)).thenReturn(true);
    Resource resource = Mockito.mock(Resource.class);
    Mockito.when(resource.getContent()).thenReturn("wsdl".getBytes());
    Mockito.when(registry.get(APIConstants.SELF_SIGN_UP_CONFIG_LOCATION)).thenReturn(resource);
    OMElement omElement = Mockito.mock(OMElement.class);
    Mockito.when(omElement.getFirstChildWithName(Matchers.any(QName.class))).thenReturn(omElement);
    PowerMockito.mockStatic(AXIOMUtil.class);
    Mockito.when(omElement.getChildrenWithLocalName(APIConstants.SELF_SIGN_UP_REG_ROLE_ELEM)).thenReturn(Mockito.mock(Iterator.class));
    PowerMockito.when(AXIOMUtil.stringToOM("wsdl")).thenReturn(omElement);
    PowerMockito.mockStatic(PasswordResolverFactory.class);
    PasswordResolver passwordResolver = Mockito.mock(PasswordResolver.class);
    PowerMockito.when(PasswordResolverFactory.getInstance()).thenReturn(passwordResolver);
    UserRegistrationConfigDTO userRegistrationConfigDTO = SelfSignUpUtil.getSignupConfiguration("foo.com");

    Assert.assertNotNull(userRegistrationConfigDTO);
}
 
Example #18
Source File: UserAdmin.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
public void deleteUser(String userName) throws UserAdminException {


        try {
            getUserAdminProxy().deleteUser(userName,
                    CarbonContext.getThreadLocalCarbonContext().getRegistry(RegistryType.USER_CONFIGURATION));
        } catch (UserAdminException e) {
            throw e;
        }

    }
 
Example #19
Source File: SAMLApplicationDAOImpl.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
@Override
public void removeServiceProviderConfiguration(String issuer) throws IdentityApplicationManagementException {
    try {
        IdentityPersistenceManager persistenceManager = IdentityPersistenceManager.getPersistanceManager();
        Registry configSystemRegistry = (Registry) PrivilegedCarbonContext.getThreadLocalCarbonContext().
                getRegistry(RegistryType.SYSTEM_CONFIGURATION);
        persistenceManager.removeServiceProvider(configSystemRegistry, issuer);
    } catch (IdentityException e) {
        log.error("Erro while deleting the issuer", e);
        throw new IdentityApplicationManagementException("Error while deleting SAML issuer " + e.getMessage());
    }
}
 
Example #20
Source File: RegistryPersistenceManager.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
@Override
public void persistConfig(String policyEditorType, String xmlConfig) throws PolicyEditorException {

    super.persistConfig(policyEditorType, xmlConfig);

    Registry registry = CarbonContext.getThreadLocalCarbonContext().getRegistry(RegistryType.SYSTEM_GOVERNANCE);
    try {
        Resource resource = registry.newResource();
        resource.setContent(xmlConfig);
        String path = null;
        if (EntitlementConstants.PolicyEditor.BASIC.equals(policyEditorType)) {
            path = EntitlementConstants.ENTITLEMENT_POLICY_BASIC_EDITOR_CONFIG_FILE_REGISTRY_PATH;
        } else if (EntitlementConstants.PolicyEditor.STANDARD.equals(policyEditorType)) {
            path = EntitlementConstants.ENTITLEMENT_POLICY_STANDARD_EDITOR_CONFIG_FILE_REGISTRY_PATH;
        } else if (EntitlementConstants.PolicyEditor.RBAC.equals(policyEditorType)) {
            path = EntitlementConstants.ENTITLEMENT_POLICY_RBAC_EDITOR_CONFIG_FILE_REGISTRY_PATH;
        } else if (EntitlementConstants.PolicyEditor.SET.equals(policyEditorType)) {
            path = EntitlementConstants.ENTITLEMENT_POLICY_SET_EDITOR_CONFIG_FILE_REGISTRY_PATH;
        } else {
            //default
            path = EntitlementConstants.ENTITLEMENT_POLICY_BASIC_EDITOR_CONFIG_FILE_REGISTRY_PATH;
        }
        registry.put(path, resource);
    } catch (RegistryException e) {
        throw new PolicyEditorException("Error while persisting policy editor config");
    }
}
 
Example #21
Source File: RegistryPersistenceManager.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
@Override
public void persistConfig(String policyEditorType, String xmlConfig) throws PolicyEditorException {

    super.persistConfig(policyEditorType, xmlConfig);

    Registry registry = CarbonContext.getThreadLocalCarbonContext().getRegistry(RegistryType.SYSTEM_GOVERNANCE);
    try {
        Resource resource = registry.newResource();
        resource.setContent(xmlConfig);
        String path = null;
        if (EntitlementConstants.PolicyEditor.BASIC.equals(policyEditorType)) {
            path = EntitlementConstants.ENTITLEMENT_POLICY_BASIC_EDITOR_CONFIG_FILE_REGISTRY_PATH;
        } else if (EntitlementConstants.PolicyEditor.STANDARD.equals(policyEditorType)) {
            path = EntitlementConstants.ENTITLEMENT_POLICY_STANDARD_EDITOR_CONFIG_FILE_REGISTRY_PATH;
        } else if (EntitlementConstants.PolicyEditor.RBAC.equals(policyEditorType)) {
            path = EntitlementConstants.ENTITLEMENT_POLICY_RBAC_EDITOR_CONFIG_FILE_REGISTRY_PATH;
        } else if (EntitlementConstants.PolicyEditor.SET.equals(policyEditorType)) {
            path = EntitlementConstants.ENTITLEMENT_POLICY_SET_EDITOR_CONFIG_FILE_REGISTRY_PATH;
        } else {
            //default
            path = EntitlementConstants.ENTITLEMENT_POLICY_BASIC_EDITOR_CONFIG_FILE_REGISTRY_PATH;
        }
        registry.put(path, resource);
    } catch (RegistryException e) {
        throw new PolicyEditorException("Error while persisting policy editor config");
    }
}
 
Example #22
Source File: CarbonBasedTestListener.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
/**
 * Creates the regostry service if not available.
 *
 * @param realClass
 * @return
 * @throws RegistryException
 */
private RegistryService createRegistryService(Class realClass, int tenantID, String tenantDomain) throws
        RegistryException {

    if (registryService != null) {
        return registryService;
    }

    try {
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain);
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(tenantID);

        RegistryContext registryContext = RegistryContext.getBaseInstance(IdentityTenantUtil.getRealmService());
        DataSource dataSource = MockInitialContextFactory
                .initializeDatasource(REG_DB_JNDI_NAME, realClass, new String[]{REG_DB_SQL_FILE});
        registryContext.setDataAccessManager(new JDBCDataAccessManager(dataSource));
        registryService = new EmbeddedRegistryService(registryContext);

        OSGiDataHolder.getInstance().setRegistryService(registryService);
        CarbonCoreDataHolder.getInstance().setRegistryService(registryService);
        PrivilegedCarbonContext.getThreadLocalCarbonContext()
                .setRegistry(RegistryType.USER_GOVERNANCE, registryService.getRegistry());

        return registryService;
    } catch (TestCreationException e) {
        log.error("Could not load registry data", e);
        throw new RegistryException("Could not load registry data", e);
    }
}
 
Example #23
Source File: SAMLApplicationDAOImpl.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
@Override
public void removeServiceProviderConfiguration(String issuer) throws IdentityApplicationManagementException {
    try {
        IdentityPersistenceManager persistenceManager = IdentityPersistenceManager.getPersistanceManager();
        Registry configSystemRegistry = (Registry) PrivilegedCarbonContext.getThreadLocalCarbonContext().
                getRegistry(RegistryType.SYSTEM_CONFIGURATION);
        persistenceManager.removeServiceProvider(configSystemRegistry, issuer);
    } catch (IdentityException e) {
        log.error("Erro while deleting the issuer", e);
        throw new IdentityApplicationManagementException("Error while deleting SAML issuer " + e.getMessage());
    }
}
 
Example #24
Source File: UserAdmin.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
public void deleteUser(String userName) throws UserAdminException {


        try {
            getUserAdminProxy().deleteUser(userName,
                    CarbonContext.getThreadLocalCarbonContext().getRegistry(RegistryType.USER_CONFIGURATION));
        } catch (UserAdminException e) {
            throw e;
        }

    }
 
Example #25
Source File: RegistryBasedLicenseManager.java    From carbon-device-mgt with Apache License 2.0 5 votes vote down vote up
public RegistryBasedLicenseManager() {
    Registry registry = CarbonContext.getThreadLocalCarbonContext().getRegistry(RegistryType.SYSTEM_GOVERNANCE);
    if (registry == null) {
        throw new IllegalArgumentException("Registry instance retrieved is null. Hence, " +
                "'Registry based license manager cannot be initialized'");
    }
    try {
        this.artifactManager = GenericArtifactManagerFactory.getTenantAwareGovernanceArtifactManager(registry);
    } catch (LicenseManagementException e) {
        throw new IllegalStateException("Failed to initialize generic artifact manager bound to " +
                "Registry based license manager", e);
    }
}
 
Example #26
Source File: IdentityPassiveSTSServiceComponent.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
public static Registry getGovernanceSystemRegistry() throws RegistryException {
    return (Registry) CarbonContext.getThreadLocalCarbonContext().getRegistry(
            RegistryType.SYSTEM_GOVERNANCE);
}
 
Example #27
Source File: TenantServiceCreatorTestCase.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
@Test
public void testCreatedConfigurationContext() throws Exception {
    TenantServiceCreator tenantServiceCreator = new TenantServiceCreator();
    ConfigurationContext configurationContext = Mockito.mock(ConfigurationContext.class);
    // Failed to create Tenant's synapse sequences Error
    PowerMockito.mockStatic(Cache.class);
    Cache cache = Mockito.mock(Cache.class);
    PowerMockito.mockStatic(ServiceReferenceHolder.class);
    PowerMockito.mockStatic(APIManagerConfigurationService.class);
    PowerMockito.mockStatic(CacheProvider.class);
    ServiceReferenceHolder serviceReferenceHolder = Mockito.mock(ServiceReferenceHolder.class);
    final APIManagerConfiguration apiManagerConfiguration = Mockito.mock(APIManagerConfiguration.class);
    PowerMockito.when(ServiceReferenceHolder.getInstance()).thenReturn(serviceReferenceHolder);
    APIManagerConfigurationService apiManagerConfigurationService =
            Mockito.mock(APIManagerConfigurationService.class);
    PowerMockito.when(serviceReferenceHolder.getAPIManagerConfigurationService()).
            thenReturn(apiManagerConfigurationService);
    PowerMockito.when(apiManagerConfigurationService.getAPIManagerConfiguration()).
            thenReturn(apiManagerConfiguration);
    CacheProvider cacheProvider = Mockito.mock(CacheProvider.class);
    PowerMockito.when(cacheProvider.getDefaultCacheTimeout()).thenReturn((long) 900);

    Mockito.when(CacheProvider.getGatewayKeyCache()).thenReturn(cache);
    Mockito.when(CacheProvider.getResourceCache()).thenReturn(cache);
    Mockito.when(CacheProvider.getGatewayTokenCache()).thenReturn(cache);
    Mockito.when(CacheProvider.getInvalidTokenCache()).thenReturn(cache);
    tenantServiceCreator.createdConfigurationContext(configurationContext);

    PowerMockito.mockStatic(PrivilegedCarbonContext.class);
    PowerMockito.mockStatic(FileUtils.class);
    PrivilegedCarbonContext privilegedCarbonContext = Mockito.mock(PrivilegedCarbonContext.class);
    Mockito.when(privilegedCarbonContext.getTenantDomain()).thenReturn("abc.com");
    AxisConfiguration axisConfiguration = Mockito.mock(AxisConfiguration.class);
    Mockito.when(configurationContext.getAxisConfiguration()).thenReturn(axisConfiguration);
    PowerMockito.when(PrivilegedCarbonContext.getThreadLocalCarbonContext()).thenReturn(privilegedCarbonContext);
    URL url = new URL("http", "localhost", 5000, "/fle/");
    Mockito.when(axisConfiguration.getRepository()).thenReturn(url);
    File tenantAxis2Repo = Mockito.mock(File.class);
    File synapseConfigsDir = Mockito.mock(File.class);

    //Couldn't create the synapse-config root on the file system error is logged.
    tenantServiceCreator.createdConfigurationContext(configurationContext);


    PowerMockito.whenNew(File.class).withArguments("/file/").thenReturn(tenantAxis2Repo);
    PowerMockito.whenNew(File.class).withAnyArguments()
            .thenReturn(synapseConfigsDir);
    Mockito.when(synapseConfigsDir.mkdir()).thenReturn(true);
    String synapseConfigsDirLocation = "/file/synapse-confgs";
    Mockito.when(synapseConfigsDir.getAbsolutePath()).thenReturn(synapseConfigsDirLocation);
    Mockito.doNothing().when(axisConfiguration).addParameter(SynapseConstants.Axis2Param.SYNAPSE_CONFIG_LOCATION,
            synapseConfigsDirLocation);
    UserRegistry userRegistry = Mockito.mock(UserRegistry.class);
    ConfigurationManager configurationManager = Mockito.mock(ConfigurationManager.class);
    Mockito.when(privilegedCarbonContext.getRegistry(RegistryType.SYSTEM_CONFIGURATION)).thenReturn(userRegistry);
    PowerMockito.whenNew(ConfigurationManager.class).withArguments(userRegistry, configurationContext)
            .thenReturn(configurationManager);
    ConfigurationTracker tracker = Mockito.mock(ConfigurationTracker.class);
    Mockito.when(configurationManager.getTracker()).thenReturn(tracker);

    Mockito.when(tracker.getCurrentConfigurationName()).thenReturn("config-name");
    Mockito.when(synapseConfigsDir.exists()).thenReturn(false, false, false, true);

    copyFile("/repository/resources/apim-synapse-config/main.xml",
            "/file/synapse-confgs" + File.separator + "sequences" + File.separator + "main.xml");

    copyFile("/repository/resources/apim-synapse-config/fault.xml",
            "/file/synapse-confgs" + File.separator + "sequences" + File.separator + "falut.xml");

    copyFile("/repository/resources/apim-synapse-config/_auth_failure_handler_.xml",
            "/file/synapse-confgs" + File.separator + "sequences" + File.separator + "_auth_failure_handler_.xml");

    copyFile("/repository/resources/apim-synapse-config/_resource_mismatch_handler_.xml",
            "/file/synapse-confgs" + File.separator + "sequences" + File.separator + "_resource_mismatch_handler_.xml");

    copyFile("/repository/resources/apim-synapse-config/_throttle_out_handler_.xml",
            "/file/synapse-confgs" + File.separator + "sequences" + File.separator + "_throttle_out_handler_.xml");

    copyFile("/repository/resources/apim-synapse-config/_sandbox_key_error_.xml",
            "/file/synapse-confgs" + File.separator + "sequences" + File.separator + "_sandbox_key_error_.xml");

    copyFile("/repository/resources/apim-synapse-config/_production_key_error_.xml",
            "/file/synapse-confgs" + File.separator + "sequences" + File.separator + "_production_key_error_.xml");

    copyFile("/repository/resources/apim-synapse-config/_cors_request_handler_.xml",
            "/file/synapse-confgs" + File.separator + "sequences" + File.separator + "_cors_request_handler_.xml");
    copyFile("/repository/resources/apim-synapse-config/_threat_fault.xml",
            "/file/synapse-confgs" + File.separator + "sequences" + File.separator + "_threat_fault.xml");
    // test IOException Error while copying API manager specific synapse sequences
    tenantServiceCreator.createdConfigurationContext(configurationContext);
}
 
Example #28
Source File: APIManagerComponent.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
protected Registry getRegistry() {
    return CarbonContext.getThreadLocalCarbonContext().getRegistry(RegistryType.USER_GOVERNANCE);
}
 
Example #29
Source File: ApplicationMgtUtil.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
/**
 * Updates the permissions of the application
 *
 * @param applicationName
 * @param permissions
 * @throws IdentityApplicationManagementException
 */
public static void updatePermissions(String applicationName, ApplicationPermission[] permissions)
        throws IdentityApplicationManagementException {

    applicationNode = getApplicationPermissionPath() + PATH_CONSTANT + applicationName;

    Registry tenantGovReg = CarbonContext.getThreadLocalCarbonContext().getRegistry(
            RegistryType.USER_GOVERNANCE);

    try {

        boolean exist = tenantGovReg.resourceExists(applicationNode);
        if (!exist) {
            Collection appRootNode = tenantGovReg.newCollection();
            appRootNode.setProperty("name", applicationName);
            tenantGovReg.put(applicationNode, appRootNode);
        }

        Collection appNodeCollec = (Collection) tenantGovReg.get(applicationNode);
        String[] childern = appNodeCollec.getChildren();

        // new permissions are null. deleting all permissions case
        if ((childern != null && childern.length > 0)
                && (permissions == null || permissions.length == 0)) { // there are permissions
            tenantGovReg.delete(applicationNode);
        }

        if (ArrayUtils.isEmpty(permissions)) {
            return;
        }

        // no permission exist for the application, create new
        if (childern == null || appNodeCollec.getChildCount() < 1) {

            addPermission(permissions, tenantGovReg);

        } else { // there are permission
            List<ApplicationPermission> loadPermissions = loadPermissions(applicationName);
            for (ApplicationPermission applicationPermission : loadPermissions) {
                tenantGovReg.delete(applicationNode + PATH_CONSTANT + applicationPermission.getValue());
            }
            addPermission(permissions, tenantGovReg);
        }

    } catch (RegistryException e) {
        throw new IdentityApplicationManagementException("Error while storing permissions", e);
    }

}
 
Example #30
Source File: RoleManagementServiceImpl.java    From carbon-device-mgt with Apache License 2.0 4 votes vote down vote up
/**
 * When presented with role and a set of permissions, if given role has permission to
 * perform mobile app management, said role will be given rights mobile app collection in the
 * governance registry.
 *
 * @param role
 * @param permissions
 * @return state of role update Operation
 */
private boolean authorizeRoleForAppmgt(String role, String[] permissions) {
    String permissionString =
            "ra^true:rd^false:wa^true:wd^false:da^true:dd^false:aa^true:ad^false";
    String resourcePath = "/_system/governance/mobileapps/";
    boolean appmPermAvailable = false;

    if (permissions != null) {
        for (int i = 0; i < permissions.length; i++)
            switch (permissions[i]) {
                case "/permission/admin/manage/mobileapp":
                    appmPermAvailable = true;
                    break;
                case "/permission/admin/manage/mobileapp/create":
                    appmPermAvailable = true;
                    break;
                case "/permission/admin/manage/mobileapp/publish":
                    appmPermAvailable = true;
                    break;
            }
    }

    if (appmPermAvailable) {
        try {
            Registry registry = CarbonContext.getThreadLocalCarbonContext().
                    getRegistry(RegistryType.SYSTEM_GOVERNANCE);
            ChangeRolePermissionsUtil.changeRolePermissions((UserRegistry) registry,
                    resourcePath, role + ":" + permissionString);

            return true;
        } catch (Exception e) {
            String msg = "Error while retrieving user registry in order to update permissions "
                    + "for resource : " + resourcePath;
            log.error(msg, e);
            return false;
        }
    } else {
        if (log.isDebugEnabled()) {
            log.debug("Mobile App Management permissions not selected, therefore role : " +
                    role + " not given permission for registry collection : " + resourcePath);
        }
        return false;
    }
}