org.wso2.carbon.identity.base.IdentityRuntimeException Java Examples

The following examples show how to use org.wso2.carbon.identity.base.IdentityRuntimeException. 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: ConfigurationFacade.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
private String buildUrl(String defaultContext, Supplier<String> getValueFromFileBasedConfig) {

        if (IdentityTenantUtil.isTenantQualifiedUrlsEnabled()) {
            try {
                return ServiceURLBuilder.create().addPath(defaultContext).build().getAbsolutePublicURL();
            } catch (URLBuilderException e) {
                throw new IdentityRuntimeException(
                        "Error while building tenant qualified url for context: " + defaultContext, e);
            }
        } else {
            String urlFromFileBasedConfig = getValueFromFileBasedConfig.get();
            if (StringUtils.isNotBlank(urlFromFileBasedConfig)) {
                // If the file based URL is set, then we have to return the file based URL.
                return urlFromFileBasedConfig;
            } else {
                return defaultContext;
            }
        }
    }
 
Example #2
Source File: IdentityEventServiceComponent.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
@Reference(
         name = "event.handler", 
         service = org.wso2.carbon.identity.event.handler.AbstractEventHandler.class, 
         cardinality = ReferenceCardinality.MULTIPLE, 
         policy = ReferencePolicy.DYNAMIC, 
         unbind = "unRegisterEventHandler")
protected void registerEventHandler(AbstractEventHandler eventHandler) {
    String handlerName = eventHandler.getName();
    try {
        eventHandler.init(IdentityEventConfigBuilder.getInstance().getModuleConfigurations(handlerName));
    } catch (IdentityEventException | IdentityRuntimeException e) {
        log.warn("Properties for " + handlerName + " is not configured. This event handler will not be activated");
    }
    eventHandlerList.add(eventHandler);
    MessageHandlerComparator messageHandlerComparator = new MessageHandlerComparator(null);
    Collections.sort(eventHandlerList, messageHandlerComparator);
}
 
Example #3
Source File: AbstractEventHandler.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
public boolean canHandle(MessageContext messageContext) throws IdentityRuntimeException {

        Event event = ((IdentityEventMessageContext) messageContext).getEvent();
        String eventName = event.getEventName();

        List<Subscription> subscriptionList = null;
        if (configs != null) {
            subscriptionList = configs.getSubscriptions();
        } else {
            return false;
        }
        if (subscriptionList != null) {
            for (Subscription subscription : subscriptionList) {
                if (subscription.getSubscriptionName().equals(eventName)) {
                    return true;
                }
            }
        }

        return false;
    }
 
Example #4
Source File: ResourceSearchBean.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
/**
 * This method allow mapping of {@link PrimitiveCondition}.
 *
 * @param primitiveCondition Primitive search expression to be mapped.
 */
public PrimitiveCondition mapPrimitiveCondition(PrimitiveCondition primitiveCondition)
        throws PrimitiveConditionValidationException {

    // Map tenant domain to tenant id
    if (primitiveCondition.getProperty().equals(RESOURCE_SEARCH_BEAN_FIELD_TENANT_DOMAIN)) {
        try {
            primitiveCondition.setValue(IdentityTenantUtil.getTenantId(
                    (String) primitiveCondition.getValue()
            ));
        } catch (IdentityRuntimeException e) {
            if (log.isDebugEnabled()) {
                log.debug(
                        "Error while retrieving tenant id for the tenant domain: "
                                + primitiveCondition.getValue() + ".", e
                );
            }
            throw new PrimitiveConditionValidationException(
                    "Unable to retrieve the tenant for the " + RESOURCE_SEARCH_BEAN_FIELD_TENANT_DOMAIN + ": "
                            + primitiveCondition.getValue()
            );
        }
        primitiveCondition.setProperty(RESOURCE_SEARCH_BEAN_FIELD_TENANT_ID);
    }
    return primitiveCondition;
}
 
Example #5
Source File: IdentityTenantUtil.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
/**
 * Get the tenant id of the given user.
 *
 * @param username Username
 * @return Tenant Id of domain user belongs to.
 * @throws IdentityRuntimeException Error when getting the tenant Id from tenant domain
 */
public static int getTenantIdOfUser(String username) throws IdentityRuntimeException {

    int tenantId = MultitenantConstants.INVALID_TENANT_ID;
    String domainName = MultitenantUtils.getTenantDomain(username);
    if (domainName != null) {
        try {
            TenantManager tenantManager = IdentityTenantUtil.getRealmService().getTenantManager();
            tenantId = tenantManager.getTenantId(domainName);
        } catch (UserStoreException e) {
            String errorMsg = "Error when getting the tenant id from the tenant domain : " + domainName;
            throw IdentityRuntimeException.error(errorMsg, e);
        }
    }
    if(tenantId == MultitenantConstants.INVALID_TENANT_ID){
        throw IdentityRuntimeException.error("Invalid tenant domain of user " + username);
    } else {
        return tenantId;
    }
}
 
Example #6
Source File: IdentityTenantUtil.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
public static String getTenantDomain(int tenantId) throws IdentityRuntimeException {

        String tenantDomain = null;
        try {
            tenantDomain = realmService.getTenantManager().getDomain(tenantId);
        } catch (UserStoreException e) {
            // Ideally user.core should be throwing an unchecked exception, in which case no need to wrap at this
            // level once more without adding any valuable contextual information. Because we don't have exception
            // enrichment properly implemented, we are appending the error message from the UserStoreException to the
            // new message
            throw IdentityRuntimeException.error("Error occurred while retrieving tenantDomain for tenantId: " +
                    tenantId + e.getMessage(), e);
        }
        if (tenantDomain == null) {
            throw IdentityRuntimeException.error("Can not find the tenant domain for the tenant id " + tenantId);
        } else {
            return tenantDomain;
        }

    }
 
Example #7
Source File: IdentityTenantUtil.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
public static int getTenantId(String tenantDomain) throws IdentityRuntimeException {

        int tenantId = MultitenantConstants.INVALID_TENANT_ID;
        try {
            if (realmService != null) {
                tenantId = realmService.getTenantManager().getTenantId(tenantDomain);
            }
        } catch (UserStoreException e) {
            // Ideally user.core should be throwing an unchecked exception, in which case no need to wrap at this
            // level once more without adding any valuable contextual information. Because we don't have exception
            // enrichment properly implemented, we are appending the error message from the UserStoreException to the
            // new message
            throw IdentityRuntimeException.error("Error occurred while retrieving tenantId for tenantDomain: " +
                    tenantDomain + e.getMessage(), e);
        }
        if(tenantId == MultitenantConstants.INVALID_TENANT_ID){
            throw IdentityRuntimeException.error("Invalid tenant domain " + tenantDomain);
        } else {
            return tenantId;
        }

    }
 
Example #8
Source File: IdentityUtil.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
public static String buildFragmentUrl(String baseUrl, Map<String, String[]> parameterMap) throws
        UnsupportedEncodingException {


    if (StringUtils.isBlank(baseUrl)) {
        throw IdentityRuntimeException.error("Base URL is blank: " + baseUrl);
    } else if (baseUrl.contains("?")) {
        throw IdentityRuntimeException.error("Fragment URL cannot contain \'?\': " + baseUrl);
    }
    StringBuilder queryString = new StringBuilder(baseUrl);
    if (queryString.indexOf("#") < 0) {
        queryString.append("#");
    }
    queryString.append(buildQueryComponent(parameterMap));
    return queryString.toString();
}
 
Example #9
Source File: IdentityUtil.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
public static String buildQueryUrl(String baseUrl, Map<String, String[]> parameterMap) throws
        UnsupportedEncodingException {


    if (StringUtils.isBlank(baseUrl)) {
        throw IdentityRuntimeException.error("Base URL is blank: " + baseUrl);
    } else if (baseUrl.contains("#")) {
        throw IdentityRuntimeException.error("Query URL cannot contain \'#\': " + baseUrl);
    }
    StringBuilder queryString = new StringBuilder(baseUrl);

    if (parameterMap != null && parameterMap.size() > 0) {
        if(queryString.indexOf("?") < 0) {
            queryString.append("?");
        } else {
            queryString.append("&");
        }
        queryString.append(buildQueryComponent(parameterMap));
    }

    return queryString.toString();
}
 
Example #10
Source File: IdentityTenantUtil.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
public static int getTenantId(String tenantDomain) throws IdentityRuntimeException {

        int tenantId = MultitenantConstants.INVALID_TENANT_ID;
        try {
            tenantId = realmService.getTenantManager().getTenantId(tenantDomain);
        } catch (UserStoreException e) {
            // Ideally user.core should be throwing an unchecked exception, in which case no need to wrap at this
            // level once more without adding any valuable contextual information. Because we don't have exception
            // enrichment properly implemented, we are appending the error message from the UserStoreException to the
            // new message
            throw IdentityRuntimeException.error("Error occurred while retrieving tenantId for tenantDomain: " +
                    tenantDomain + e.getMessage(), e);
        }
        if(tenantId == MultitenantConstants.INVALID_TENANT_ID){
            throw IdentityRuntimeException.error("Invalid tenant domain " + tenantDomain);
        } else {
            return tenantId;
        }

    }
 
Example #11
Source File: IdentityTenantUtil.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
public static String getTenantDomain(int tenantId) throws IdentityRuntimeException {

        String tenantDomain = null;
        try {
            tenantDomain = realmService.getTenantManager().getDomain(tenantId);
        } catch (UserStoreException e) {
            // Ideally user.core should be throwing an unchecked exception, in which case no need to wrap at this
            // level once more without adding any valuable contextual information. Because we don't have exception
            // enrichment properly implemented, we are appending the error message from the UserStoreException to the
            // new message
            throw IdentityRuntimeException.error("Error occurred while retrieving tenantDomain for tenantId: " +
                    tenantId + e.getMessage(), e);
        }
        if(tenantDomain == null){
            throw IdentityRuntimeException.error("Invalid tenant domain " + tenantDomain);
        } else {
            return tenantDomain;
        }

    }
 
Example #12
Source File: IdentityTenantUtil.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
/**
 * Get the tenant id of the given user.
 *
 * @param username Username
 * @return Tenant Id of domain user belongs to.
 * @throws IdentityRuntimeException Error when getting the tenant Id from tenant domain
 */
public static int getTenantIdOfUser(String username) throws IdentityRuntimeException {

    int tenantId = MultitenantConstants.INVALID_TENANT_ID;
    String domainName = MultitenantUtils.getTenantDomain(username);
    if (domainName != null) {
        try {
            TenantManager tenantManager = IdentityTenantUtil.getRealmService().getTenantManager();
            tenantId = tenantManager.getTenantId(domainName);
        } catch (UserStoreException e) {
            String errorMsg = "Error when getting the tenant id from the tenant domain : " + domainName;
            throw IdentityRuntimeException.error(errorMsg, e);
        }
    }
    if(tenantId == MultitenantConstants.INVALID_TENANT_ID){
        throw IdentityRuntimeException.error("Invalid tenant domain of user " + username);
    } else {
        return tenantId;
    }
}
 
Example #13
Source File: AuthenticationContext.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
/**
 * Add authentication params to the message context parameters Map.
 *
 * @param authenticatorParams Map of authenticator and params.
 */
public void addAuthenticatorParams(Map<String, Map<String, String>> authenticatorParams) {

    if (MapUtils.isEmpty(authenticatorParams)) {
        return;
    }
    Object runtimeParamsObj = getParameter(FrameworkConstants.RUNTIME_PARAMS);
    if (runtimeParamsObj == null) {
        addParameter(FrameworkConstants.RUNTIME_PARAMS, authenticatorParams);
        return;
    }
    if (runtimeParamsObj instanceof Map) {
        Map<String, Map<String, String>> runtimeParams = (Map<String, Map<String, String>>) runtimeParamsObj;
        for (Map.Entry<String, Map<String, String>> params : authenticatorParams.entrySet()) {
            if (runtimeParams.get(params.getKey()) != null) {
                runtimeParams.get(params.getKey()).putAll(params.getValue());
            } else {
                runtimeParams.put(params.getKey(), params.getValue());
            }
        }
    } else {
        throw IdentityRuntimeException.error("There is already a object set with RUNTIME_PARAMS key in the " +
                "message context.");
    }
}
 
Example #14
Source File: RegistryResourceMgtServiceImpl.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
@Override
public void putIdentityResource(Resource identityResource,
                                String path,
                                String tenantDomain) throws IdentityRuntimeException {
    startTenantFlow(tenantDomain);
    try {
        Registry registry = getRegistryForTenant(tenantDomain);
        registry.put(path, identityResource);
        if (log.isDebugEnabled()) {
            log.debug(String.format(MSG_RESOURCE_PERSIST, path, tenantDomain));
        }
    } catch (RegistryException e) {
        String errorMsg = String.format(ERROR_PERSIST_RESOURCE, tenantDomain, path);
        throw IdentityRuntimeException.error(errorMsg, e);
    } finally {
        PrivilegedCarbonContext.endTenantFlow();
    }
}
 
Example #15
Source File: RegistryResourceMgtServiceImpl.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
@Override
public Resource getIdentityResource(String path,
                                    String tenantDomain) throws IdentityRuntimeException {
    startTenantFlow(tenantDomain);
    try {
        Registry registry = getRegistryForTenant(tenantDomain);
        Resource resource = null;

        if (registry.resourceExists(path)) {
            resource = registry.get(path);
        }
        return resource;
    } catch (RegistryException e) {
        String errorMsg = String.format(ERROR_GET_RESOURCE, path, tenantDomain);
        throw IdentityRuntimeException.error(errorMsg, e);
    } finally {
        PrivilegedCarbonContext.endTenantFlow();
    }
}
 
Example #16
Source File: SAMLSSOConfigServiceClient.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
public String[] getDigestAlgorithmURIs() throws IdentityRuntimeException {
    String[] digestAlgorithms;
    try {
        digestAlgorithms = stub.getDigestAlgorithmURIs();
    } catch (RemoteException e) {
        throw IdentityRuntimeException.error(e.getMessage(), e);
    }
    return digestAlgorithms;
}
 
Example #17
Source File: AbstractEventHandler.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
@Override
public void init(InitConfig configuration) throws IdentityRuntimeException {
    if (configuration instanceof ModuleConfiguration) {
        this.configs = (ModuleConfiguration) configuration;
    } else {
        throw new IdentityRuntimeException("Initial configuration error");
    }
}
 
Example #18
Source File: SessionDataStore.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
/**
 * Removes the records related to expired sessions from DB.
 */
private void removeExpiredSessionData(String sqlQuery) {

    if (log.isDebugEnabled()) {
        log.debug("DB query for removing expired data: " + sqlQuery);
    }
    long currentTime = FrameworkUtils.getCurrentStandardNano();
    try (Connection connection = IdentityDatabaseUtil.getDBConnection(true)) {
        boolean deleteCompleted = false;
        int totalDeletedEntries = 0;
        while (!deleteCompleted) {
            try (PreparedStatement statement = connection.prepareStatement(sqlQuery)) {
                statement.setLong(1, currentTime);
                int noOfDeletedRecords = statement.executeUpdate();
                deleteCompleted = noOfDeletedRecords < deleteChunkSize;
                totalDeletedEntries += noOfDeletedRecords;
                // Commit the chunk deletion.
                IdentityDatabaseUtil.commitTransaction(connection);
                if (log.isDebugEnabled()) {
                    log.debug(String.format("Removed %d expired session records.", noOfDeletedRecords));
                }
            }
        }
        if (log.isDebugEnabled()) {
            log.debug(String.format("Deleted total of %d entries", totalDeletedEntries));
        }
    } catch (SQLException | IdentityRuntimeException e) {
        log.error("Error while removing session data from the database for nano time: " + currentTime, e);
    }
}
 
Example #19
Source File: IdentityEventConfigBuilder.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
/**
 * Load properties file and set Module properties
 *
 */
private IdentityEventConfigBuilder() {

    try {
        notificationMgtConfigProperties = loadProperties();
    } catch (IdentityEventException e) {
        throw new IdentityRuntimeException("Failed to initialize IdentityEventConfigBuilder.", e);
    }

    setThreadPoolSize();
    resolveSecrets();
    moduleConfiguration = new HashMap<>();
    build();
}
 
Example #20
Source File: ConsentDeletionUserEventHandler.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
/**
 * Consent search limit is configurable and the config is read from identity-event.properties file.
 *
 * @param configuration
 * @throws IdentityRuntimeException
 */
@Override
public void init(InitConfig configuration) throws IdentityRuntimeException {

    super.init(configuration);
    String receiptSearchLimit = this.configs.getModuleProperties().getProperty(SEARCH_LIMIT_PROPERTY);
    try {
        this.consentSearchLimit = Integer.parseInt(receiptSearchLimit);
    } catch (NumberFormatException e) {
        log.error("Configured receipt.search.limit cannot be parsed as an integer. " +
                "Hence using default value: " + consentSearchLimit);
    }
}
 
Example #21
Source File: IdentityManagementEndpointUtil.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the end user portal url.
 *
 * @param userPortalUrl configured user portal url
 * @return configured url or the default url if configured url is empty
 */
public static final String getUserPortalUrl(String userPortalUrl) {

    if (StringUtils.isNotBlank(userPortalUrl)) {
        return userPortalUrl;
    }
    try {
        return ServiceURLBuilder.create().addPath(IdentityManagementEndpointConstants.USER_PORTAL_URL).build()
                .getAbsolutePublicURL();
    } catch (URLBuilderException e) {
        throw new IdentityRuntimeException(
                "Error while building url for context: " + IdentityManagementEndpointConstants.USER_PORTAL_URL);
    }
}
 
Example #22
Source File: MessageContext.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
public void addParameters(Map<T1,T2> parameters){
    for (Map.Entry<T1,T2> parameter : parameters.entrySet()) {
        if(this.parameters.containsKey(parameter.getKey())) {
            throw IdentityRuntimeException.error("Parameters map trying to override existing key " + parameter.getKey());
        }
        parameters.put(parameter.getKey(), parameter.getValue());
    }
}
 
Example #23
Source File: MessageContext.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
public void addParameter(T1 key, T2 value){
    if(this.parameters.containsKey(key)) {
        throw IdentityRuntimeException.error("Parameters map trying to override existing key " +
                key);
    }
    parameters.put(key, value);
}
 
Example #24
Source File: RegistryResourceMgtServiceImpl.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
@Override
public Resource getIdentityResource(String path,
                                    String tenantDomain,
                                    String locale) throws IdentityRuntimeException {
    path = getRegistryPath(path, locale);
    return getIdentityResource(path, tenantDomain);
}
 
Example #25
Source File: RegistryResourceMgtServiceImpl.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
@Override
public void putIdentityResource(Resource identityResource,
                                String path,
                                String tenantDomain,
                                String locale) throws IdentityRuntimeException {
    path = getRegistryPath(path, locale);
    putIdentityResource(identityResource, path, tenantDomain);
}
 
Example #26
Source File: RegistryResourceMgtServiceImpl.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
@Override
public void addIdentityResource(Resource identityResource,
                                String path,
                                String tenantDomain,
                                String locale) throws IdentityRuntimeException {
    path = getRegistryPath(path, locale);
    addIdentityResource(identityResource, path, tenantDomain);
}
 
Example #27
Source File: IdentityDatabaseUtil.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
/**
 * Get a database connection instance for the User DB
 *
 * @return Database Connection
 * @throws IdentityRuntimeException Error when getting a database connection to Identity database
 */
public static Connection getUserDBConnection() throws IdentityRuntimeException {
    Connection connection;
    try {
        connection = UmPersistenceManager.getInstance().getDataSource().getConnection();
    } catch (SQLException e) {
        throw IdentityRuntimeException.error("Database error. Could not get a connection", e);
    }
    return connection;
}
 
Example #28
Source File: AbstractEventHandlerTest.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
@Test (expectedExceptions = {IdentityRuntimeException.class})
public void testInitException() {

    InitConfig configuration = new InitConfig();
    TestEventHandler testEventHandler = new TestEventHandler();
    testEventHandler.init(configuration);

    Assert.assertEquals(testEventHandler.configs,configuration);
}
 
Example #29
Source File: JDBCPersistenceManager.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
/**
 * Returns an database connection for Identity data source.
 *
 * @return Database connection
 * @throws IdentityException Exception occurred when getting the data source.
 */
public Connection getDBConnection() throws IdentityRuntimeException {
    try {
        Connection dbConnection = dataSource.getConnection();
        dbConnection.setAutoCommit(false);
        dbConnection.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
        return dbConnection;
    } catch (SQLException e) {
        String errMsg = "Error when getting a database connection object from the Identity data source.";
        throw IdentityRuntimeException.error(errMsg, e);
    }
}
 
Example #30
Source File: RegistryResourceMgtServiceImpl.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
@Override
public void deleteIdentityResource(String path,
                                   String tenantDomain,
                                   String locale) throws IdentityRuntimeException {
    path = getRegistryPath(path, locale);
    deleteIdentityResource(path, tenantDomain);
}