org.wso2.carbon.context.CarbonContext Java Examples

The following examples show how to use org.wso2.carbon.context.CarbonContext. 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: UserStoreCountUtils.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
public static boolean isUserStoreEnabled(String domain) throws UserStoreCounterException {

        RealmConfiguration realmConfiguration;
        boolean isEnabled = false;
        try {
            realmConfiguration = CarbonContext.getThreadLocalCarbonContext().getUserRealm().getRealmConfiguration();

            do {
                String userStoreDomain = realmConfiguration.
                        getUserStoreProperty(UserCoreConstants.RealmConfig.PROPERTY_DOMAIN_NAME);

                if (domain.equals(userStoreDomain)) {
                    isEnabled = !Boolean.valueOf(realmConfiguration.getUserStoreProperty(UserCoreConstants.RealmConfig.
                            USER_STORE_DISABLED));
                    break;
                }
                realmConfiguration = realmConfiguration.getSecondaryRealmConfig();
            } while (realmConfiguration != null);

        } catch (UserStoreException e) {
            throw new UserStoreCounterException("Error occurred while getting Secondary Realm Configuration", e);
        }
        return isEnabled;
    }
 
Example #2
Source File: StratosApiV41Utils.java    From attic-stratos with Apache License 2.0 6 votes vote down vote up
/**
 * Get Tenant UserStoreManager
 *
 * @return UserStoreManager
 * @throws UserManagerException
 */
private static UserStoreManager getTenantUserStoreManager() throws UserManagerException {

    CarbonContext carbonContext = CarbonContext.getThreadLocalCarbonContext();
    UserRealm userRealm;
    UserStoreManager userStoreManager;

    try {
        userRealm = carbonContext.getUserRealm();
        userStoreManager = userRealm.getUserStoreManager();

    } catch (UserStoreException e) {
        String msg = "Error in retrieving UserStore Manager";
        log.error(msg, e);
        throw new UserManagerException(msg, e);
    }

    return userStoreManager;
}
 
Example #3
Source File: JsGraphBuilder.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
/**
 * Loads the required function library from the database.
 *
 * @param functionLibraryName functionLibraryName
 * @return functionLibraryScript
 * @throws FunctionLibraryManagementException
 */
public String loadLocalLibrary(String functionLibraryName) throws FunctionLibraryManagementException {

    FunctionLibraryManagementService functionLibMgtService = FrameworkServiceComponent.
            getFunctionLibraryManagementService();
    FunctionLibrary functionLibrary;
    String libraryScript = null;

    functionLibrary = functionLibMgtService.getFunctionLibrary(functionLibraryName,
            CarbonContext.getThreadLocalCarbonContext().getTenantDomain());

    if (functionLibrary != null) {
        libraryScript = functionLibrary.getFunctionLibraryScript();
    } else {
        log.error("No function library available with " + functionLibraryName + "name.");
    }
    return libraryScript;
}
 
Example #4
Source File: UserStoreManagerService.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
public int getTenantIdofUser(String username) throws UserStoreException {

        if (Util.isSuperTenant()) {
            return getUserStoreManager().getTenantId(username);
        } else {
            StringBuilder stringBuilder
                    = new StringBuilder(AUTH_FAIL);
            stringBuilder.append(CarbonContext.getThreadLocalCarbonContext().getTenantDomain()).append(" tenant id - ")
                    .append(CarbonContext.getThreadLocalCarbonContext().getTenantId()).append(" user - ")
                    .append(CarbonContext.getThreadLocalCarbonContext().getUsername());
            log.warn(stringBuilder.toString());

            throw new UserStoreException("Access Denied");
        }

    }
 
Example #5
Source File: DeviceManagementServiceImplTest.java    From carbon-device-mgt with Apache License 2.0 6 votes vote down vote up
@Test(description = "Testing get devices when unable to retrieve devices")
public void testGetDeviceServerErrorWhenGettingDeviceList() throws DeviceManagementException {
    PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
            .toReturn(this.deviceManagementProviderService);
    PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceAccessAuthorizationService"))
            .toReturn(this.deviceAccessAuthorizationService);
    PowerMockito.stub(PowerMockito.method(MultitenantUtils.class, "getTenantAwareUsername"))
            .toReturn(TENANT_AWARE_USERNAME);
    PowerMockito.stub(PowerMockito.method(CarbonContext.class, "getThreadLocalCarbonContext"))
            .toReturn(Mockito.mock(CarbonContext.class, Mockito.RETURNS_MOCKS));
    Mockito.when(this.deviceManagementProviderService
            .getAllDevices(Mockito.any(PaginationRequest.class), Mockito.anyBoolean()))
            .thenThrow(new DeviceManagementException());

    Response response = this.deviceManagementService
            .getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP,
                    DEFAULT_STATUS, 1, null, null, false, 10, 5);
    Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
    Mockito.reset(this.deviceManagementProviderService);
}
 
Example #6
Source File: FederatedAssociationManagerImpl.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
@Override
public String getUserForFederatedAssociation(String tenantDomain, String idpName, String federatedUserId)
        throws FederatedAssociationManagerException {

    int tenantId = getValidatedTenantIdFromDomain(tenantDomain);
    try {
        return UserProfileMgtDAO.getInstance().getUserAssociatedFor(tenantId, idpName, federatedUserId);
    } catch (UserProfileException e) {
        if (log.isDebugEnabled()) {
            String msg = "Error while retrieving user associated for federated IdP: " + idpName + ", with " +
                    "federation identifier: " + federatedUserId + ", in tenant: "
                    + CarbonContext.getThreadLocalCarbonContext().getTenantDomain();
            log.debug(msg);
        }
        throw handleFederatedAssociationManagerServerException(ERROR_WHILE_GETTING_USER_FOR_FEDERATED_ASSOCIATION,
                e, true);
    }
}
 
Example #7
Source File: IdPMgtValidationListener.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
@Override
public boolean doPreDeleteIdP(String idPName, String tenantDomain) throws IdentityProviderManagementException {

    if (StringUtils.isEmpty(idPName)) {
        throw new IllegalArgumentException("Invalid argument: Identity Provider Name value is empty");
    }

    String loggedInTenant = CarbonContext.getThreadLocalCarbonContext().getTenantDomain();

    if (IdentityApplicationConstants.RESIDENT_IDP_RESERVED_NAME.equals(idPName)) {
        if (StringUtils.equals(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME, tenantDomain)) {
            throw new IdentityProviderManagementException("Cannot delete Resident Identity Provider of Super " +
                    "Tenant");
        } else if (MultitenantConstants.SUPER_TENANT_DOMAIN_NAME != loggedInTenant) {
            throw new IdentityProviderManagementException("Tenant user of " + loggedInTenant + " cannot delete " +
                    "Resident Identity Provider of tenant " + tenantDomain);
        } else {
            log.warn("Deleting Resident Identity Provider for tenant " + tenantDomain);
        }
    }

    return true;
}
 
Example #8
Source File: WorkflowManagementUtil.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
/**
 * Create a internal role in workflow domain with same name as workflow.
 *
 * @param workflowName Workflow name
 * @throws WorkflowException
 */
public static void createAppRole(String workflowName) throws WorkflowException {
    String roleName = createWorkflowRoleName(workflowName);
    String qualifiedUsername = CarbonContext.getThreadLocalCarbonContext().getUsername();
    String[] user = {qualifiedUsername};

    try {
        if (log.isDebugEnabled()) {
            log.debug("Creating workflow role : " + roleName + " and assign the user : "
                    + Arrays.toString(user) + " to that role");
        }
        CarbonContext.getThreadLocalCarbonContext().getUserRealm().getUserStoreManager()
                .addRole(roleName, user, null);
    } catch (UserStoreException e) {
        throw new WorkflowException("Error while creating role", e);
    }

}
 
Example #9
Source File: PolicyPublishExecutor.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
/**
 * Helper method
 *
 * @param verificationCode verificationCode as String
 * @param subscriberIds    Array of subscriberIds
 */
private void persistVerificationCode(String verificationCode, String[] subscriberIds) {

    Registry registry = EntitlementServiceComponent.
            getGovernanceRegistry(CarbonContext.getThreadLocalCarbonContext().getTenantId());
    try {
        org.wso2.carbon.registry.api.Resource resource = registry.newResource();
        resource.setProperty("subscriberIds", Arrays.asList(subscriberIds));
        resource.setProperty("policyIds", Arrays.asList(policyIds));
        resource.setProperty("action", action);
        resource.setProperty("version", version);
        resource.setProperty("order", Integer.toString(order));
        registry.put(PDPConstants.ENTITLEMENT_POLICY_PUBLISHER_VERIFICATION + verificationCode,
                resource);
    } catch (org.wso2.carbon.registry.api.RegistryException e) {
        log.error("Error while persisting verification code", e);
    }

}
 
Example #10
Source File: IdentityProviderManagementService.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
/**
 * Adds an Identity Provider to the logged-in tenant
 *
 * @param identityProvider <code>IdentityProvider</code> new Identity Provider information
 * @throws IdentityProviderManagementException Error when adding Identity Provider
 */
public void addIdP(IdentityProvider identityProvider) throws IdentityProviderManagementException {
    // The following check is applicable only for the IdPs added from UI/Service call and should not be
    // applicable for IdPs added from file. hence the check is moved from listener to the service
    if (identityProvider != null && identityProvider.getIdentityProviderName() != null &&
            identityProvider.getIdentityProviderName().startsWith(IdPManagementConstants.SHARED_IDP_PREFIX)) {
        throw new IdentityProviderManagementException("Identity provider name cannot have " +
                IdPManagementConstants.SHARED_IDP_PREFIX + " as prefix.");
    }
    String tenantDomain = "";
    try {
        tenantDomain = CarbonContext.getThreadLocalCarbonContext().getTenantDomain();
        IdentityProviderManager.getInstance().addIdP(identityProvider, tenantDomain);
    } catch (IdentityProviderManagementException idpException) {
        log.error("Error while adding Identity provider in tenantDomain : " + tenantDomain, idpException);
        throw idpException;
    }
}
 
Example #11
Source File: UserStoreManagerService.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
public String[][] getProperties(Tenant tenant) throws UserStoreException {
    // TODO This method should only called by super tenant
    // Logic is not implemented yet

    if (!Util.isSuperTenant()) {
        StringBuilder stringBuilder
                = new StringBuilder(AUTH_FAIL);
        stringBuilder.append(CarbonContext.getThreadLocalCarbonContext().getTenantDomain()).append(" tenant id - ")
                .append(CarbonContext.getThreadLocalCarbonContext().getTenantId()).append(" user - ")
                .append(CarbonContext.getThreadLocalCarbonContext().getUsername());
        log.warn(stringBuilder.toString());

        throw new UserStoreException("Access Denied");
    }

    // TODO implement the logic
    return new String[0][0];
}
 
Example #12
Source File: DeviceManagementServiceImplTest.java    From carbon-device-mgt with Apache License 2.0 6 votes vote down vote up
@Test(description = "Testing get devices when user is unauthorized.")
public void testGetDevicesWhenUserIsUnauthorized() throws Exception {
    PowerMockito.spy(MultitenantUtils.class);
    PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
            .toReturn(this.deviceManagementProviderService);
    PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceAccessAuthorizationService"))
            .toReturn(this.deviceAccessAuthorizationService);
    PowerMockito.stub(PowerMockito.method(CarbonContext.class, "getThreadLocalCarbonContext"))
            .toReturn(Mockito.mock(CarbonContext.class, Mockito.RETURNS_MOCKS));
    PowerMockito.doReturn(TENANT_AWARE_USERNAME)
            .when(MultitenantUtils.class, "getTenantAwareUsername", DEFAULT_USERNAME);
    PowerMockito.doReturn("[email protected]").when(MultitenantUtils.class, "getTenantAwareUsername", "newuser");
    Mockito.when(this.deviceAccessAuthorizationService.isDeviceAdminUser()).thenReturn(false);

    Response response = this.deviceManagementService
            .getDevices(null, TEST_DEVICE_TYPE, "newuser", null, DEFAULT_ROLE, DEFAULT_OWNERSHIP, DEFAULT_STATUS, 1,
                    null, null, 10, 5);
    Assert.assertEquals(response.getStatus(), Response.Status.UNAUTHORIZED.getStatusCode());
    Mockito.reset(this.deviceAccessAuthorizationService);
}
 
Example #13
Source File: WorkflowManagementAdminService.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
/**
 * List workflows
 *
 * @return
 * @throws WorkflowException
 */
public WorkflowWizard[] listWorkflows() throws WorkflowException {

    List<WorkflowWizard> workflowWizards = new ArrayList<>();
    List<Workflow> workflowBeans = null;
    int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
    try {
        workflowBeans = WorkflowServiceDataHolder.getInstance().getWorkflowService().listWorkflows(tenantId);
        for (Workflow workflow : workflowBeans) {
            WorkflowWizard workflowTmp = getWorkflow(workflow);
            workflowWizards.add(workflowTmp);
        }
    } catch (InternalWorkflowException e) {
        log.error("Server error when listing workflows", e);
        throw new WorkflowException("Server error occurred when listing workflows");
    }
    return workflowWizards.toArray(new WorkflowWizard[workflowWizards.size()]);
}
 
Example #14
Source File: PolicySearchCache.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
/**
 * Invalidate {@link PolicySearchCache}. It will send the cluster message to clean the {@link PolicySearchCache}
 * in all the nodes.
 */
public void invalidateCache() {

    int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();

    if (log.isDebugEnabled()) {
        log.debug("Trigger invalidate policy search cache to tenant :  " + IdentityTenantUtil.getTenantDomain(tenantId));
    }

    // Update local policy search cache of this node.
    clearCache();

    // Send out a cluster message to notify other nodes.
    if (isClusteringEnabled()) {
        sendClusterMessage(new PolicySearchCacheInvalidationClusteringMessage(tenantId), true);
    } else {
        if (log.isDebugEnabled()) {
            log.debug("Clustering not enabled. Not sending cluster message to other nodes.");
        }
    }
}
 
Example #15
Source File: WorkflowManagementUtil.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
/**
 * Update name of workflow role
 *
 * @param oldWorkflowName Previous role name
 * @param newWorkflowName New role name
 * @throws WorkflowException
 */
public static void updateWorkflowRoleName(String oldWorkflowName, String newWorkflowName) throws
        WorkflowException {
    String oldRoleName = createWorkflowRoleName(oldWorkflowName);
    String newRoleName = createWorkflowRoleName(newWorkflowName);
    try {
        if (log.isDebugEnabled()) {
            log.debug("Updating workflow role : " + oldRoleName);
        }
        CarbonContext.getThreadLocalCarbonContext().getUserRealm().getUserStoreManager()
                .updateRoleName(oldRoleName, newRoleName);
    } catch (UserStoreException e) {
        throw new WorkflowException("Error while updating workflow role name.", e);
    }

}
 
Example #16
Source File: DeviceManagementServiceImplTest.java    From carbon-device-mgt with Apache License 2.0 5 votes vote down vote up
@Test(description = "Testing get devices with correct request when unable to get devices.")
public void testGetDeviceTypesByUserException() throws DeviceManagementException {
    PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
            .toReturn(this.deviceManagementProviderService);
    PowerMockito.stub(PowerMockito.method(CarbonContext.class, "getThreadLocalCarbonContext"))
            .toReturn(Mockito.mock(CarbonContext.class, Mockito.RETURNS_MOCKS));
    Mockito.when(this.deviceManagementProviderService.getDevicesOfUser(Mockito.any(PaginationRequest.class)))
            .thenThrow(new DeviceManagementException());

    Response response = this.deviceManagementService.getDeviceByUser(true, 10, 5);
    Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
}
 
Example #17
Source File: DecisionCache.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
/**
 * Clear all decision cache
 */
public void clearCache() {
    if (log.isDebugEnabled()) {
        String tenantDomain = CarbonContext.getThreadLocalCarbonContext().getTenantDomain();
        int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
        log.debug("DecisionCache clear all cache from the cluster");
    }
    clear();
}
 
Example #18
Source File: SessionContextCache.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
/**
 * Check whether the given session context is valid according to remember me session timeout restrictions.
 *
 * @param key        SessionContextCacheKey
 * @param cacheEntry SessionContextCacheEntry
 * @return true if the session context is valid as per remember me session configs; false otherwise
 */
private boolean isValidRememberMeSession(SessionContextCacheKey key, SessionContextCacheEntry cacheEntry) {
    String contextId = key.getContextId();

    if (cacheEntry == null) {
        return false;
    }

    if (!cacheEntry.getContext().isRememberMe()) {
        return false;
    }

    String tenantDomain = CarbonContext.getThreadLocalCarbonContext().getTenantDomain();
    long rememberMeSessionTimeOut = TimeUnit.SECONDS.toMillis(IdPManagementUtil.getRememberMeTimeout(tenantDomain));

    long currentTime = System.currentTimeMillis();
    long lastAccessedTime = cacheEntry.getAccessedTime();

    if (log.isDebugEnabled()) {
        log.debug("Context ID : " + contextId + " :: rememberMeSessionTimeOut : " + rememberMeSessionTimeOut
                + ", currentTime : " + currentTime + ", lastAccessedTime : " + lastAccessedTime);
    }

    if (currentTime - lastAccessedTime > rememberMeSessionTimeOut) {
        if (log.isDebugEnabled()) {
            log.debug("Context ID : " + contextId + " :: Remember me session expiry");
        }
        return false;
    }

    return true;
}
 
Example #19
Source File: StratosApiV41.java    From attic-stratos with Apache License 2.0 5 votes vote down vote up
/**
 * Removes the application sign up.
 *
 * @param applicationId the application id
 * @return 200 if specified application sign up is removed
 * @throws RestAPIException the rest api exception
 */
@DELETE
@Path("/applications/{applicationId}/signup")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/admin/stratos/applicationSignUps/manage")
public Response removeApplicationSignUp(@PathParam("applicationId") String applicationId) throws RestAPIException {
    StratosApiV41Utils
            .removeApplicationSignUp(applicationId, CarbonContext.getThreadLocalCarbonContext().getTenantId());
    return Response.ok().entity(new ResponseMessageBean(ResponseMessageBean.SUCCESS,
            String.format("Application sign up removed successfully: [application] %s", applicationId))).build();
}
 
Example #20
Source File: IdentityProviderManagementService.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
public String getResidentIDPMetadata() throws IdentityProviderManagementException {

        try {
            String tenantDomain = CarbonContext.getThreadLocalCarbonContext().getTenantDomain();
            return IdentityProviderManager.getInstance().getResidentIDPMetadata(tenantDomain);
        } catch (IdentityProviderManagementException idpException) {
            log.error("Error while retrieving IDP metadata", idpException);
            throw idpException;
        }
    }
 
Example #21
Source File: IdentityProviderManagementService.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
/**
 * Updated resident Identity provider for the logged-in tenant
 *
 * @param identityProvider <code>IdentityProvider</code>
 * @throws IdentityProviderManagementException Error when getting Resident Identity Provider
 */
public void updateResidentIdP(IdentityProvider identityProvider)
        throws IdentityProviderManagementException {
    String tenantDomain = "";
    try {
        tenantDomain = CarbonContext.getThreadLocalCarbonContext().getTenantDomain();
        IdentityProviderManager.getInstance().updateResidentIdP(identityProvider, tenantDomain);
    } catch (IdentityProviderManagementException idpException) {
        log.error("Error while updating ResidentIdP in tenantDomain : " + tenantDomain, idpException);
        throw idpException;
    }
}
 
Example #22
Source File: KeyStoreAdminServiceImpl.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
@Override
public void deleteStore(String keyStoreName) throws SecurityConfigException {
    KeyStoreAdmin admin = new KeyStoreAdmin(CarbonContext.getThreadLocalCarbonContext().getTenantId(),
            getGovernanceSystemRegistry());
    admin.deleteStore(keyStoreName);

}
 
Example #23
Source File: CacheBackedApplicationDAO.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
public void deleteApplication(String applicationName) throws IdentityApplicationManagementException {

        String tenantDomain = CarbonContext.getThreadLocalCarbonContext().getTenantDomain();
        ServiceProvider serviceProvider = getApplication(applicationName, tenantDomain);
        clearAllAppCache(serviceProvider, tenantDomain);
        appDAO.deleteApplication(applicationName);
    }
 
Example #24
Source File: KeyStoreAdminServiceImpl.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
@Override
public KeyStoreData getKeystoreInfo(String keyStoreName) throws SecurityConfigException {
    KeyStoreAdmin admin = new KeyStoreAdmin(CarbonContext.getThreadLocalCarbonContext().getTenantId(),
            getGovernanceSystemRegistry());
    return admin.getKeystoreInfo(keyStoreName);

}
 
Example #25
Source File: PolicyEditorEngine.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
/**
 * Get a PolicyEditorEngine instance for that tenant. This method will return an
 * PolicyEditorEngine instance if exists, or creates a new one
 *
 * @return EntitlementEngine instance for that tenant
 */
public static PolicyEditorEngine getInstance() {

    int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
    if (!policyEditorEngine.containsKey(Integer.toString(tenantId))) {
        synchronized (lock) {
            if (!policyEditorEngine.containsKey(Integer.toString(tenantId))) {
                policyEditorEngine.put(Integer.toString(tenantId), new PolicyEditorEngine(tenantId));
            }
        }
    }
    return policyEditorEngine.get(Integer.toString(tenantId));
}
 
Example #26
Source File: UserMgtAuditLogger.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
private String getUser() {
    String user = CarbonContext.getThreadLocalCarbonContext().getUsername();
    if (user != null) {
        user = user + "@" + CarbonContext.getThreadLocalCarbonContext().getTenantDomain();
    } else {
        user = CarbonConstants.REGISTRY_SYSTEM_USERNAME;
    }
    return user;
}
 
Example #27
Source File: SecondaryUserStoreConfigurationUtil.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
/**
 * Trigger the listeners before userstore domain delete
 * @param domainName user store domain name
 * @throws UserStoreException throws when an error occured when triggering listeners.
 */
public static void triggerListnersOnUserStorePreDelete(String domainName) throws UserStoreException {

    List<UserStoreConfigListener> userStoreConfigListeners = UserStoreConfigListenersHolder.getInstance()
            .getUserStoreConfigListeners();
    for (UserStoreConfigListener userStoreConfigListener : userStoreConfigListeners) {
        userStoreConfigListener.onUserStorePreDelete(CarbonContext.getThreadLocalCarbonContext().getTenantId
                (), domainName);
    }
}
 
Example #28
Source File: DeviceManagementServiceImplTest.java    From carbon-device-mgt with Apache License 2.0 5 votes vote down vote up
@Test(description = "Testing get devices with correct request when unable to get devices.")
public void testGetDeviceTypesByUserException() throws DeviceManagementException {
    PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
            .toReturn(this.deviceManagementProviderService);
    PowerMockito.stub(PowerMockito.method(CarbonContext.class, "getThreadLocalCarbonContext"))
            .toReturn(Mockito.mock(CarbonContext.class, Mockito.RETURNS_MOCKS));
    Mockito.when(this.deviceManagementProviderService.getDevicesOfUser(Mockito.any(PaginationRequest.class)))
            .thenThrow(new DeviceManagementException());

    Response response = this.deviceManagementService.getDeviceByUser(true, 10, 5);
    Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
}
 
Example #29
Source File: ApplicationManagementAdminService.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
/**
 * Delete Application
 *
 * @param applicationName Application name
 * @throws org.wso2.carbon.identity.application.common.IdentityApplicationManagementException
 */
public void deleteApplication(String applicationName)
        throws IdentityApplicationManagementException {

    if (!ApplicationMgtUtil.isUserAuthorized(applicationName, getUsername())) {
        log.warn("Illegal Access! User " + CarbonContext.getThreadLocalCarbonContext().getUsername() +
                " does not have access to the application " + applicationName);
        throw new IdentityApplicationManagementException("User not authorized");
    }
    applicationMgtService = ApplicationManagementService.getInstance();
    applicationMgtService.deleteApplication(applicationName, getTenantDomain(), getUsername());
}
 
Example #30
Source File: IdentityProviderDAOImpl.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
@Override
/**
 *
 */
public List<IdentityProvider> getAllIdentityProviders()
        throws IdentityApplicationManagementException {

    IdentityProviderManager idpManager = IdentityProviderManager.getInstance();

    List<IdentityProvider> idps;
    try {
        idps = idpManager
                .getIdPs(CarbonContext.getThreadLocalCarbonContext().getTenantDomain());
    } catch (IdentityProviderManagementException e) {
        throw new IdentityApplicationManagementException("Error when retrieving all identity providers in " +
                CarbonContext.getThreadLocalCarbonContext().getTenantDomain() +" tenant domain.", e);
    }

    List<IdentityProvider> federatedIdentityProviders = new ArrayList<IdentityProvider>();

    if (idps != null && !idps.isEmpty()) {
        for (IdentityProvider idp : idps) {
            federatedIdentityProviders.add(getIdentityProvider(idp.getIdentityProviderName()));
        }
    }

    return federatedIdentityProviders;
}