org.wso2.carbon.base.MultitenantConstants Java Examples

The following examples show how to use org.wso2.carbon.base.MultitenantConstants. 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: APIUtilTierTest.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Test
public void testAddDefaultSuperTenantAdvancedThrottlePoliciesAppLevel() throws Exception {
    ApiMgtDAOMockCreator daoMockHolder = new ApiMgtDAOMockCreator(1);
    ApiMgtDAO apiMgtDAO = daoMockHolder.getMock();

    String[] appPolicies = new String[]{APIConstants.DEFAULT_APP_POLICY_FIFTY_REQ_PER_MIN,
            APIConstants.DEFAULT_APP_POLICY_TWENTY_REQ_PER_MIN,
            APIConstants.DEFAULT_APP_POLICY_TEN_REQ_PER_MIN, APIConstants.DEFAULT_APP_POLICY_UNLIMITED};

    for (String policy : appPolicies) {
        Mockito.when(
                apiMgtDAO.isPolicyExist(eq(PolicyConstants.POLICY_LEVEL_APP), eq(MultitenantConstants.SUPER_TENANT_ID),
                        eq(policy))).thenReturn(false);
    }

    try {
        APIUtil.addDefaultSuperTenantAdvancedThrottlePolicies();
        Mockito.verify(apiMgtDAO, Mockito.times(appPolicies.length)).addApplicationPolicy(Mockito.any(ApplicationPolicy.class));
    } catch (APIManagementException e) {
        Assert.assertTrue("Exception thrown", false);
    }
}
 
Example #2
Source File: RegistryBasedTaskRepository.java    From carbon-commons with Apache License 2.0 6 votes vote down vote up
@Override
public synchronized boolean deleteTask(String taskName) throws TaskException {
    String tasksPath = this.getMyTasksPath();
    String currentTaskPath = tasksPath + "/" + taskName;
    try {
        PrivilegedCarbonContext.startTenantFlow();
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(
                MultitenantConstants.SUPER_TENANT_DOMAIN_NAME, true);
        if (!getRegistry().resourceExists(currentTaskPath)) {
            return false;
        }
        getRegistry().delete(currentTaskPath);
        return true;
    } catch (RegistryException e) {
        throw new TaskException("Error in deleting task '" + taskName + "' in the repository",
                Code.CONFIG_ERROR, e);
    } finally {
        PrivilegedCarbonContext.endTenantFlow();
    }
}
 
Example #3
Source File: APIManagerUtil.java    From carbon-device-mgt with Apache License 2.0 6 votes vote down vote up
/**
 * returns the tenant Id of the specific tenant Domain
 */
public static int getTenantId(String tenantDomain) throws APIManagerException {
    try {
        if (MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
            return MultitenantConstants.SUPER_TENANT_ID;
        }
        TenantManager tenantManager = APIApplicationManagerExtensionDataHolder.getInstance().getTenantManager();
        int tenantId = tenantManager.getTenantId(tenantDomain);
        if (tenantId == -1) {
            throw new APIManagerException("invalid tenant Domain :" + tenantDomain);
        }
        return tenantId;
    } catch (UserStoreException e) {
        throw new APIManagerException("invalid tenant Domain :" + tenantDomain);
    }
}
 
Example #4
Source File: APIUtilTierTest.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Test
public void testAddDefaultSuperTenantAdvancedThrottlePoliciesApiLevelAlreadyAdded() throws Exception {
    ApiMgtDAOMockCreator daoMockHolder = new ApiMgtDAOMockCreator(1);
    ApiMgtDAO apiMgtDAO = daoMockHolder.getMock();

    String[] apiPolicies = new String[]{APIConstants.DEFAULT_API_POLICY_FIFTY_THOUSAND_REQ_PER_MIN,
            APIConstants.DEFAULT_API_POLICY_TWENTY_THOUSAND_REQ_PER_MIN,
            APIConstants.DEFAULT_API_POLICY_TEN_THOUSAND_REQ_PER_MIN, APIConstants.DEFAULT_API_POLICY_UNLIMITED};

    for (String policy : apiPolicies) {
        Mockito.when(
                apiMgtDAO.isPolicyExist(eq(PolicyConstants.POLICY_LEVEL_API), eq(MultitenantConstants.SUPER_TENANT_ID),
                        eq(policy))).thenReturn(true);
    }

    try {
        APIUtil.addDefaultSuperTenantAdvancedThrottlePolicies();
        Mockito.verify(apiMgtDAO, Mockito.never()).addAPIPolicy(Mockito.any(APIPolicy.class));
    } catch (APIManagementException e) {
        Assert.assertTrue("Exception thrown", false);
    }
}
 
Example #5
Source File: DeviceTypeManagerServiceTest.java    From carbon-device-mgt with Apache License 2.0 6 votes vote down vote up
@Test(description = "This test cases tests the retrieval of provisioning config after providing the configurations "
        + "values")
public void testWithProvisioningConfig() throws Exception {
    boolean isRasberryPiSharedWithTenants =
            (rasberrypiDeviceConfiguration.getProvisioningConfig() != null) && rasberrypiDeviceConfiguration
                    .getProvisioningConfig().isSharedWithAllTenants();
    setProvisioningConfig.invoke(androidDeviceTypeManagerService, MultitenantConstants.SUPER_TENANT_DOMAIN_NAME,
            androidDeviceConfiguration);
    ProvisioningConfig provisioningConfig = androidDeviceTypeManagerService.getProvisioningConfig();
    Assert.assertEquals(provisioningConfig.isSharedWithAllTenants(),
            androidDeviceConfiguration.getProvisioningConfig().isSharedWithAllTenants(),
            "Provisioning configs are not correctly set as per the configuration file provided");

    setProvisioningConfig.invoke(rasberrypiDeviceTypeManagerService, MultitenantConstants.SUPER_TENANT_DOMAIN_NAME,
            rasberrypiDeviceConfiguration);
    provisioningConfig = rasberrypiDeviceTypeManagerService.getProvisioningConfig();
    Assert.assertEquals(provisioningConfig.isSharedWithAllTenants(), isRasberryPiSharedWithTenants,
            "Provisioning configs are not correctly set as per the configuration file provided.");
}
 
Example #6
Source File: DeviceAgentServiceTest.java    From carbon-device-mgt with Apache License 2.0 6 votes vote down vote up
@Test(description = "Test publish events with no device access authorization.")
public void testPublishEventsWithoutAuthorization() throws DeviceAccessAuthorizationException {
    PowerMockito.stub(PowerMockito.method(PrivilegedCarbonContext.class, "getThreadLocalCarbonContext"))
            .toReturn(this.privilegedCarbonContext);
    PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class,
            "getDeviceAccessAuthorizationService")).toReturn(this.deviceAccessAuthorizationService);
    Mockito.when(this.deviceAccessAuthorizationService.isUserAuthorized(Mockito.any(DeviceIdentifier.class)))
            .thenReturn(false);
    Mockito.when(this.privilegedCarbonContext.getTenantDomain())
            .thenReturn(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
    Map<String, Object> payload = new HashMap<>();
    Response response = this.deviceAgentService.publishEvents(payload, TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER);
    Assert.assertNotNull(response, "Response should not be null");
    Assert.assertEquals(response.getStatus(), Response.Status.UNAUTHORIZED.getStatusCode(),
            "The response status should be 401");
    List<Object> payloadList = new ArrayList<>();
    Response response2 = this.deviceAgentService.publishEvents(payloadList, TEST_DEVICE_TYPE,
            TEST_DEVICE_IDENTIFIER);
    Assert.assertNotNull(response2, "Response should not be null");
    Assert.assertEquals(response2.getStatus(), Response.Status.UNAUTHORIZED.getStatusCode(),
            "The response status should be 401");
    Mockito.reset(this.deviceAccessAuthorizationService);
}
 
Example #7
Source File: RegistryBasedTaskRepository.java    From carbon-commons with Apache License 2.0 6 votes vote down vote up
private Resource getTaskMetadataPropResource(String taskName) throws TaskException,
        RegistryException {
    try {
        PrivilegedCarbonContext.startTenantFlow();
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(
                MultitenantConstants.SUPER_TENANT_DOMAIN_NAME, true);
        return getRegistry().get(
                RegistryBasedTaskRepository.REG_TASK_REPO_BASE_PATH + "/"
                        + this.getTenantId() + "/" + this.getTasksType() + "/" + taskName);
    } catch (ResourceNotFoundException e) {
        throw new TaskException("The task '" + taskName + "' does not exist",
                Code.NO_TASK_EXISTS, e);
    } finally {
        PrivilegedCarbonContext.endTenantFlow();
    }
}
 
Example #8
Source File: CertificateManagerImplTest.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * This method tests the behaviour of updateClientCertificate method.
 */
@Test
public void testUpdateClientCertificate() throws APIManagementException {
    PowerMockito
            .stub(PowerMockito.method(CertificateMgtUtils.class, "validateCertificate"))
            .toReturn(ResponseCode.CERTIFICATE_EXPIRED);
    ResponseCode responseCode = certificateManager
            .updateClientCertificate(BASE64_ENCODED_CERT, ALIAS, null, MultitenantConstants.SUPER_TENANT_ID);
    Assert.assertEquals("Response code was wrong while trying add a expired client certificate",
            ResponseCode.CERTIFICATE_EXPIRED.getResponseCode(), responseCode.getResponseCode());
    PowerMockito
            .stub(PowerMockito.method(CertificateMgtUtils.class, "validateCertificate"))
            .toReturn(ResponseCode.SUCCESS);
    PowerMockito.stub(PowerMockito.method(CertificateMgtDAO.class, "updateClientCertificate")).toReturn(false);
    responseCode = certificateManager
            .updateClientCertificate(BASE64_ENCODED_CERT, ALIAS, null, MultitenantConstants.SUPER_TENANT_ID);
    Assert.assertEquals("Response code was wrong, for a failure in update",
            ResponseCode.INTERNAL_SERVER_ERROR.getResponseCode(), responseCode.getResponseCode());
}
 
Example #9
Source File: BSTAuthenticatorTest.java    From carbon-device-mgt with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public void init() throws NoSuchFieldException {
    bstAuthenticator = new BSTAuthenticator();
    properties = new Properties();
    headersField = org.apache.coyote.Request.class.getDeclaredField("headers");
    headersField.setAccessible(true);
    oAuth2TokenValidationService = Mockito
            .mock(OAuth2TokenValidationService.class, Mockito.CALLS_REAL_METHODS);
    oAuth2ClientApplicationDTO = Mockito
            .mock(OAuth2ClientApplicationDTO.class, Mockito.CALLS_REAL_METHODS);

    OAuth2TokenValidationResponseDTO authorizedValidationResponse = new OAuth2TokenValidationResponseDTO();
    authorizedValidationResponse.setValid(true);
    authorizedValidationResponse.setAuthorizedUser("admin@" + MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);

    Mockito.doReturn(oAuth2ClientApplicationDTO).when(oAuth2TokenValidationService)
            .findOAuthConsumerIfTokenIsValid(Mockito.any());
    oAuth2ClientApplicationDTO.setAccessTokenValidationResponse(authorizedValidationResponse);
    AuthenticatorFrameworkDataHolder.getInstance().setOAuth2TokenValidationService(oAuth2TokenValidationService);
}
 
Example #10
Source File: TokenGenTest.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
    PowerMockito.mockStatic(CarbonUtils.class);
    PowerMockito.mockStatic(SubscriptionDataHolder.class);
    ServerConfiguration serverConfiguration = Mockito.mock(ServerConfiguration.class);
    Mockito.when(serverConfiguration.getFirstProperty(APIConstants.PORT_OFFSET_CONFIG)).thenReturn("2");
    PowerMockito.when(CarbonUtils.getServerConfiguration()).thenReturn(serverConfiguration);
    String dbConfigPath = System.getProperty("APIManagerDBConfigurationPath");
    APIManagerConfiguration config = new APIManagerConfiguration();
    config.load(dbConfigPath);
    ServiceReferenceHolder.getInstance().setAPIManagerConfigurationService(
            new APIManagerConfigurationServiceImpl(config));
    SubscriptionDataStore subscriptionDataStore = Mockito.mock(SubscriptionDataStore.class);
    SubscriptionDataHolder subscriptionDataHolder = Mockito.mock(SubscriptionDataHolder.class);
    PowerMockito.when(SubscriptionDataHolder.getInstance()).thenReturn(subscriptionDataHolder);
    PowerMockito.when(SubscriptionDataHolder.getInstance()
            .getTenantSubscriptionStore(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME))
            .thenReturn(subscriptionDataStore);
    Application application = new Application();
    application.setId(1);
    application.setName("app2");
    application.setUUID(UUID.randomUUID().toString());
    application.addAttribute("abc","cde");
    Mockito.when(subscriptionDataStore.getApplicationById(1)).thenReturn(application);
}
 
Example #11
Source File: User.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a User object constructed from fully qualified username
 *
 * @param username Fully qualified username
 * @return User object
 * @throws IllegalArgumentException
 */
public static User getUserFromUserName(String username) {

    User user = new User();
    if (StringUtils.isNotBlank(username)) {
        String tenantDomain = MultitenantUtils.getTenantDomain(username);
        String tenantAwareUsername = MultitenantUtils.getTenantAwareUsername(username);
        String tenantAwareUsernameWithNoUserDomain = UserCoreUtil.removeDomainFromName(tenantAwareUsername);
        String userStoreDomain = IdentityUtil.extractDomainFromName(username).toUpperCase(Locale.ENGLISH);
        user.setUserName(tenantAwareUsernameWithNoUserDomain);
        if (StringUtils.isNotEmpty(tenantDomain)) {
            user.setTenantDomain(tenantDomain);
        } else {
            user.setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
        }
        if (StringUtils.isNotEmpty(userStoreDomain)) {
            user.setUserStoreDomain(userStoreDomain);
        } else {
            user.setTenantDomain(UserCoreConstants.PRIMARY_DEFAULT_DOMAIN_NAME);
        }
    }
    return user;
}
 
Example #12
Source File: RegistryBasedTaskRepository.java    From carbon-commons with Apache License 2.0 6 votes vote down vote up
private TaskInfo getTaskInfoRegistryPath(String path) throws Exception {
    try {
        PrivilegedCarbonContext.startTenantFlow();
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(
                MultitenantConstants.SUPER_TENANT_DOMAIN_NAME, true);
        Resource resource = getRegistry().get(path);
        InputStream in = resource.getContentStream();
        TaskInfo taskInfo;
        /*
         * the following synchronized block is to avoid
         * "org.xml.sax.SAXException: FWK005" error where the XML parser is
         * not thread safe
         */
        synchronized (getTaskUnmarshaller()) {
            taskInfo = (TaskInfo) getTaskUnmarshaller().unmarshal(in);
        }
        in.close();
        taskInfo.getProperties().put(TaskInfo.TENANT_ID_PROP,
                String.valueOf(this.getTenantId()));
        return taskInfo;
    } finally {
        PrivilegedCarbonContext.endTenantFlow();
    }
}
 
Example #13
Source File: OAuthHandler.java    From attic-stratos with Apache License 2.0 6 votes vote down vote up
private String extractAppIdFromIdToken(String token) {
    String appId = null;
    KeyStoreManager keyStoreManager = KeyStoreManager.getInstance(MultitenantConstants.SUPER_TENANT_ID);
    try {
        keyStoreManager.getDefaultPrimaryCertificate();
        JWSVerifier verifier =
                new RSASSAVerifier((RSAPublicKey) keyStoreManager.getDefaultPublicKey());
        SignedJWT jwsObject = SignedJWT.parse(token);
        if (jwsObject.verify(verifier)) {
            appId = jwsObject.getJWTClaimsSet().getStringClaim("appId");
        }

    } catch (Exception e) {
        String message = "Could not extract application id from id token";
        log.error(message, e);
    }
    return appId;
}
 
Example #14
Source File: IdPManagementDAO.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
/**
 * @param dbConnection
 * @param idPName
 * @param tenantId
 * @return
 * @throws SQLException
 * @throws IdentityProviderManagementException
 */
private int getIdentityProviderIdentifier(Connection dbConnection, String idPName, int tenantId)
        throws SQLException, IdentityProviderManagementException {

    String sqlStmt = null;
    PreparedStatement prepStmt = null;
    ResultSet rs = null;
    try {
        sqlStmt = IdPManagementConstants.SQLQueries.GET_IDP_BY_NAME_SQL;
        prepStmt = dbConnection.prepareStatement(sqlStmt);
        prepStmt.setInt(1, tenantId);
        prepStmt.setInt(2, MultitenantConstants.SUPER_TENANT_ID);
        prepStmt.setString(3, idPName);
        rs = prepStmt.executeQuery();
        if (rs.next()) {
            return rs.getInt("ID");
        } else {
            throw new IdentityProviderManagementException("Invalid Identity Provider Name "
                    + idPName);
        }
    } finally {
        IdentityDatabaseUtil.closeAllConnections(null, rs, prepStmt);
    }
}
 
Example #15
Source File: CertificateManagerImpl.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Override
public boolean deleteClientCertificateFromGateway(String alias) {

    int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
    /*
        Tenant ID is checked to make sure that tenant admins cannot delete the alias that do not belong their
        tenant. Super tenant is special cased, as it is required to delete the certificates from different tenants.
     */
    if (alias.endsWith("_" + tenantId) || tenantId == org.wso2.carbon.utils.multitenancy.MultitenantConstants.SUPER_TENANT_ID) {
        return deleteCertificateFromListenerAndSenderProfiles(alias, true);
    } else {
        log.warn("Attempt to delete the alias " + alias + " by tenant " + tenantId + " has been rejected. Only "
                + "the client certificates that belongs to " + tenantId + " can be deleted. All the client "
                + "certificates belongs to " + tenantId + " have '_" + tenantId + "' suffix in alias");
        return false;
    }
}
 
Example #16
Source File: IdentityUtil.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
/**
 * Check the case sensitivity of the user store.
 *
 * @param userStoreDomain user store domain
 * @param tenantId        tenant id of the user store
 * @return
 */
public static boolean isUserStoreCaseSensitive(String userStoreDomain, int tenantId) {

    boolean isUsernameCaseSensitive = true;
    if (tenantId == MultitenantConstants.INVALID_TENANT_ID){
        //this is to handle federated scenarios
        return true;
    }
    try {
        org.wso2.carbon.user.core.UserStoreManager userStoreManager = (org.wso2.carbon.user.core
                .UserStoreManager) IdentityTenantUtil.getRealmService()
                .getTenantUserRealm(tenantId).getUserStoreManager();
        org.wso2.carbon.user.core.UserStoreManager userAvailableUserStoreManager = userStoreManager
                .getSecondaryUserStoreManager(userStoreDomain);
        return isUserStoreCaseSensitive(userAvailableUserStoreManager);
    } catch (UserStoreException e) {
        if (log.isDebugEnabled()) {
            log.debug("Error while reading user store property CaseInsensitiveUsername. Considering as case " +
                    "sensitive.");
        }
    }
    return isUsernameCaseSensitive;
}
 
Example #17
Source File: DefaultClaimsRetriever.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
@Override
public String[] getDefaultClaims(String endUserName) throws IdentityOAuth2Exception {

    int tenantId = MultitenantConstants.SUPER_TENANT_ID;
    try {
        tenantId = OAuth2Util.getTenantIdFromUserName(endUserName);
        // if no claims were requested, return all
        if(log.isDebugEnabled()){
            log.debug("No claims set requested. Returning all claims in the dialect");
        }
        ClaimManager claimManager =
                OAuthComponentServiceHolder.getRealmService().getTenantUserRealm(tenantId).getClaimManager();
        ClaimMapping[] claims = claimManager.getAllClaimMappings(dialectURI);
        return claimToString(claims);
    } catch (UserStoreException e) {
        throw new IdentityOAuth2Exception("Error while reading default claims for user : " + endUserName, e);
    }
}
 
Example #18
Source File: IdPManagementDAO.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
/**
 * @param dbConnection
 * @param idpName
 * @param tenantId
 * @return
 * @throws SQLException
 * @throws IdentityProviderManagementException
 */
private int getIdentityProviderIdByName(Connection dbConnection, String idpName, int tenantId)
        throws SQLException, IdentityProviderManagementException {

    boolean dbConnInitialized = true;
    PreparedStatement prepStmt = null;
    ResultSet rs = null;
    if (dbConnection == null) {
        dbConnection = IdentityDatabaseUtil.getDBConnection();
    } else {
        dbConnInitialized = false;
    }
    try {

        String sqlStmt = IdPManagementConstants.SQLQueries.GET_IDP_ROW_ID_SQL;
        prepStmt = dbConnection.prepareStatement(sqlStmt);
        prepStmt.setInt(1, tenantId);
        prepStmt.setInt(2, MultitenantConstants.SUPER_TENANT_ID);
        prepStmt.setString(3, idpName);
        rs = prepStmt.executeQuery();
        if (rs.next()) {
            return rs.getInt(1);
        }
    } finally {
        if (dbConnInitialized) {
            IdentityDatabaseUtil.closeAllConnections(dbConnection, rs, prepStmt);
        }else{
            IdentityDatabaseUtil.closeAllConnections(null, rs, prepStmt);
        }
    }
    return 0;
}
 
Example #19
Source File: ConfigurationUtils.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
/**
 * Retrieves loaded tenant domain from carbon context.
 *
 * @return tenant domain of the request is being served.
 */
public static String getTenantDomainFromContext() {

    String tenantDomain = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
    if (IdentityUtil.threadLocalProperties.get().get(TENANT_NAME_FROM_CONTEXT) != null) {
        tenantDomain = (String) IdentityUtil.threadLocalProperties.get().get(TENANT_NAME_FROM_CONTEXT);
    }
    return tenantDomain;
}
 
Example #20
Source File: ReCaptchaApi.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
/**
 * Return the reCaptchaGet details in the headers for the given tenant.
 *
 * @param tenantDomain          Tenant domain. Default &#x60;carbon.super&#x60; (optional).
 * @param isEndpointTenantAware Is tenant aware endpoint.
 * @param captchaType           Captcha type.
 * @param recoveryType          Recovery type.
 * @return Return captcha details as ReCaptchaProperties.
 * @throws ApiException if fails to make API call.
 */
public ReCaptchaProperties getReCaptcha(String tenantDomain, boolean isEndpointTenantAware, String captchaType,
                                        String recoveryType) throws ApiException {

    if (StringUtils.isBlank(tenantDomain)) {
        tenantDomain = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
    }

    basePath = IdentityManagementEndpointUtil.getBasePath(tenantDomain,
            IdentityManagementEndpointConstants.UserInfoRecovery.RECOVERY_API_RELATIVE_PATH, isEndpointTenantAware);
    apiClient.setBasePath(basePath);

    String localVarPath = "/captcha";

    // Query params
    List<Pair> localVarQueryParams = new ArrayList<>();
    Map<String, String> localVarHeaderParams = new HashMap<>();
    Map<String, Object> localVarFormParams = new HashMap<>();

    localVarQueryParams.addAll(apiClient.parameterToPairs(StringUtils.EMPTY, TENANTDOMAIN, tenantDomain));
    localVarQueryParams.addAll(apiClient.parameterToPairs(StringUtils.EMPTY, CAPTCHA_TYPE, captchaType));
    localVarQueryParams.addAll(apiClient.parameterToPairs(StringUtils.EMPTY, RECOVERY_TYPE, recoveryType));

    final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);
    final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);

    String[] localVarAuthNames = new String[]{};

    GenericType<ReCaptchaProperties> localVarReturnType = new GenericType<ReCaptchaProperties>() {
    };

    return apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, null, localVarHeaderParams,
            localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType);
}
 
Example #21
Source File: IdPManagementDAO.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
/**
 * @param realmId
 * @param tenantId
 * @param tenantDomain
 * @return
 * @throws IdentityProviderManagementException
 * @throws SQLException
 */
public IdentityProvider getIdPByRealmId(String realmId, int tenantId, String tenantDomain)
        throws IdentityProviderManagementException {

    Connection dbConnection = IdentityDatabaseUtil.getDBConnection(false);
    PreparedStatement prepStmt = null;
    ResultSet rs = null;
    String idPName = null;

    try {
        String sqlStmt = IdPManagementConstants.SQLQueries.GET_IDP_NAME_BY_REALM_ID_SQL;
        prepStmt = dbConnection.prepareStatement(sqlStmt);
        prepStmt.setInt(1, tenantId);
        prepStmt.setInt(2, MultitenantConstants.SUPER_TENANT_ID);
        prepStmt.setString(3, realmId);
        rs = prepStmt.executeQuery();
        if (rs.next()) {
            idPName = rs.getString("NAME");
        }
        return getIdPByName(dbConnection, idPName, tenantId, tenantDomain);
    } catch (SQLException e) {
        throw new IdentityProviderManagementException("Error while retreiving Identity Provider by realm " +
                realmId, e);
    } finally {
        IdentityDatabaseUtil.closeAllConnections(dbConnection, rs, prepStmt);
    }

}
 
Example #22
Source File: AbstractAPIMgtGatewayJWTGenerator.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
public byte[] signJWT(String assertion) throws APIManagementException {

        try {
            KeyStoreManager keyStoreManager = KeyStoreManager.getInstance(MultitenantConstants.SUPER_TENANT_ID);
            PrivateKey privateKey = keyStoreManager.getDefaultPrivateKey();
            return APIUtil.signJwt(assertion, privateKey, signatureAlgorithm);
        } catch (Exception e) {
            throw new APIManagementException(e);
        }
    }
 
Example #23
Source File: RegistryBasedTaskRepository.java    From carbon-commons with Apache License 2.0 5 votes vote down vote up
public static Registry getRegistry() throws TaskException {
    if (registry == null) {
        synchronized (RegistryBasedTaskRepository.class) {
            if (registry == null) {
                registry = TaskUtils
                        .getGovRegistryForTenant(MultitenantConstants.SUPER_TENANT_ID);
            }
        }
    }
    return registry;
}
 
Example #24
Source File: CertificateManagerImpl.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Override
public boolean addCertificateToGateway(String certificate, String alias) {
    // Check whether the api is invoked via the APIGatewayAdmin service.
    int loggedInTenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
    if (loggedInTenantId != MultitenantConstants.SUPER_TENANT_ID) {
        alias = alias + "_" + loggedInTenantId;
    }
    return addCertificateToListenerOrSenderProfile(certificate, alias, false);
}
 
Example #25
Source File: RoleManagementServiceImpl.java    From carbon-device-mgt with Apache License 2.0 5 votes vote down vote up
private UIPermissionNode getUIPermissionNode(String roleName, UserRealm userRealm)
        throws UserAdminException {
    org.wso2.carbon.user.core.UserRealm userRealmCore = null;
    if (userRealm instanceof org.wso2.carbon.user.core.UserRealm) {
        userRealmCore = (org.wso2.carbon.user.core.UserRealm) userRealm;
    }
    final UserRealmProxy userRealmProxy = new UserRealmProxy(userRealmCore);
    final UIPermissionNode rolePermissions =
            userRealmProxy.getRolePermissions(roleName, MultitenantConstants.SUPER_TENANT_ID);
    UIPermissionNode[] deviceMgtPermissions = new UIPermissionNode[4];

    for (UIPermissionNode permissionNode : rolePermissions.getNodeList()) {
        if (permissionNode.getResourcePath().equals("/permission/admin")) {
            for (UIPermissionNode node : permissionNode.getNodeList()) {
                if (node.getResourcePath().equals("/permission/admin/device-mgt")) {
                    deviceMgtPermissions[0] = node;
                } else if (node.getResourcePath().equals("/permission/admin/login")) {
                    deviceMgtPermissions[1] = node;
                } else if (node.getResourcePath().equals("/permission/admin/manage")) {
                    // Adding permissions related to app-store in emm-console
                    for (UIPermissionNode subNode : node.getNodeList()) {
                        if (subNode.getResourcePath().equals("/permission/admin/manage/mobileapp")) {
                            deviceMgtPermissions[2] = subNode;
                        } else if (subNode.getResourcePath().equals("/permission/admin/manage/webapp")) {
                            deviceMgtPermissions[3] = subNode;
                        }
                    }
                }
            }
        }
    }
    rolePermissions.setNodeList(deviceMgtPermissions);
    return rolePermissions;
}
 
Example #26
Source File: RoleManagementServiceImpl.java    From carbon-device-mgt with Apache License 2.0 5 votes vote down vote up
private UIPermissionNode getAllRolePermissions(String roleName, UserRealm userRealm) throws UserAdminException {
    org.wso2.carbon.user.core.UserRealm userRealmCore = null;
    if (userRealm instanceof org.wso2.carbon.user.core.UserRealm) {
        userRealmCore = (org.wso2.carbon.user.core.UserRealm) userRealm;
    }
    final UserRealmProxy userRealmProxy = new UserRealmProxy(userRealmCore);
    final UIPermissionNode rolePermissions =
            userRealmProxy.getRolePermissions(roleName, MultitenantConstants.SUPER_TENANT_ID);
    return rolePermissions;
}
 
Example #27
Source File: APIMgtDAOTest.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Test
public void testAddGetApplicationByNameWithUserNameNullGroupIdNull() throws Exception {
    Subscriber subscriber = new Subscriber("LA_F_APP_UN_GROUP_ID_NULL");
    subscriber.setEmail("[email protected]");
    subscriber.setSubscribedDate(new Date());
    subscriber.setTenantId(MultitenantConstants.SUPER_TENANT_ID);
    apiMgtDAO.addSubscriber(subscriber, null);
    Application application = new Application("testApplication2", subscriber);
    int applicationId = apiMgtDAO.addApplication(application, subscriber.getName());
    application.setId(applicationId);
    assertTrue(applicationId > 0);
    assertNotNull(apiMgtDAO.getApplicationByUUID(apiMgtDAO.getApplicationById(applicationId).getUUID()));
    assertNull(apiMgtDAO.getApplicationByName("testApplication2", null, null));

}
 
Example #28
Source File: APIMgtDAOTest.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Test
public void testAddGetApplicationByNameGroupIdNull() throws Exception {
    Subscriber subscriber = new Subscriber("LA_F_GROUP_ID_NULL");
    subscriber.setEmail("[email protected]");
    subscriber.setSubscribedDate(new Date());
    subscriber.setTenantId(MultitenantConstants.SUPER_TENANT_ID);
    apiMgtDAO.addSubscriber(subscriber, null);
    Application application = new Application("testApplication", subscriber);
    int applicationId = apiMgtDAO.addApplication(application, subscriber.getName());
    application.setId(applicationId);
    assertTrue(applicationId > 0);
    this.checkApplicationsEqual(application, apiMgtDAO.getApplicationByName("testApplication", subscriber.getName
            (), null));

}
 
Example #29
Source File: DeviceTypeManagerNegativeTest.java    From carbon-device-mgt with Apache License 2.0 5 votes vote down vote up
@Test(description = "This test case tests the behaviour of the DeviceTypeManager creation when having a "
        + "defective platform configuration ", expectedExceptions = {DeviceTypeDeployerPayloadException.class},
        expectedExceptionsMessageRegExp = "Error occurred while getting default platform configuration for the "
                + "device type wrong *")
public void testWithDefectivePlatformConfiguration() {
    DeviceTypeConfigIdentifier wrongDeviceTypeConfigIdentifier = new DeviceTypeConfigIdentifier("wrong",
            MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
    new DeviceTypeManager(wrongDeviceTypeConfigIdentifier, androidDeviceTypeConfiguration);
}
 
Example #30
Source File: ProviderMigrationClient.java    From product-es with Apache License 2.0 5 votes vote down vote up
private List<Tenant> getTenantsArray() throws UserStoreException {
    TenantManager tenantManager = ServiceHolder.getRealmService().getTenantManager();
    List<Tenant> tenantsArray = new ArrayList<Tenant>(Arrays.asList(tenantManager.getAllTenants()));
    Tenant superTenant = new Tenant();
    superTenant.setDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
    superTenant.setId(MultitenantConstants.SUPER_TENANT_ID);
    tenantsArray.add(superTenant);
    return tenantsArray;
}