javax.websocket.OnError#org.wso2.carbon.base.MultitenantConstants源码实例Demo

下面列出了javax.websocket.OnError#org.wso2.carbon.base.MultitenantConstants 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: carbon-device-mgt   文件: APIManagerUtil.java
/**
 * 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);
    }
}
 
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();
    }
}
 
源代码3 项目: carbon-identity-framework   文件: User.java
/**
 * 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;
}
 
/**
 * 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());
}
 
源代码5 项目: carbon-identity   文件: DefaultClaimsRetriever.java
@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);
    }
}
 
源代码6 项目: carbon-apimgt   文件: TokenGenTest.java
@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);
}
 
源代码7 项目: carbon-apimgt   文件: CertificateManagerImpl.java
@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;
    }
}
 
源代码8 项目: carbon-apimgt   文件: APIUtilTierTest.java
@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);
    }
}
 
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();
    }
}
 
源代码10 项目: attic-stratos   文件: OAuthHandler.java
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;
}
 
/**
 * @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);
    }
}
 
源代码12 项目: carbon-identity   文件: IdentityUtil.java
/**
 * 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;
}
 
源代码13 项目: carbon-device-mgt   文件: BSTAuthenticatorTest.java
@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("[email protected]" + MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);

    Mockito.doReturn(oAuth2ClientApplicationDTO).when(oAuth2TokenValidationService)
            .findOAuthConsumerIfTokenIsValid(Mockito.any());
    oAuth2ClientApplicationDTO.setAccessTokenValidationResponse(authorizedValidationResponse);
    AuthenticatorFrameworkDataHolder.getInstance().setOAuth2TokenValidationService(oAuth2TokenValidationService);
}
 
源代码14 项目: carbon-device-mgt   文件: DeviceAgentServiceTest.java
@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);
}
 
@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.");
}
 
@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();
    }
}
 
源代码17 项目: carbon-apimgt   文件: APIUtilTierTest.java
@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);
    }
}
 
@Override
public Response deleteCertificate(String alias) {

    if (StringUtils.equals(getTenantDomainFromContext(), MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)) {
        return Response.status(Response.Status.METHOD_NOT_ALLOWED).build();
    }
    keyStoreService.deleteCertificate(alias);
    return Response.noContent().build();
}
 
/**
 * Add a cache entry.
 *
 * @param key   Key which cache entry is indexed.
 * @param entry Actual object where cache entry is placed.
 */
public void addToCache(AuthenticationResultCacheKey key, AuthenticationResultCacheEntry entry) {
    super.addToCache(key, entry);
    if (isTemporarySessionDataPersistEnabled) {
        int tenantId = MultitenantConstants.INVALID_TENANT_ID;
        if (entry.getResult() != null && entry.getResult().getSubject() != null) {
            String tenantDomain = entry.getResult().getSubject().getTenantDomain();
            if (tenantDomain != null) {
                tenantId = IdentityTenantUtil.getTenantId(tenantDomain);
            }
        }
        SessionDataStore.getInstance().storeSessionData(key.getResultId(), CACHE_NAME, entry, tenantId);
    }
}
 
源代码20 项目: carbon-commons   文件: Util.java
/**
 * This method validates the signature of the SAML Response.
 * @param resp SAML Response
 * @return true, if signature is valid.
 */
public static boolean validateSignature(Response resp, String keyStoreName,
                                        String keyStorePassword, String alias, int tenantId,
                                        String tenantDomain) {
    boolean isSigValid = false;
    try {
        KeyStore keyStore = null;
        java.security.cert.X509Certificate cert = null;
        if (tenantId != MultitenantConstants.SUPER_TENANT_ID) {
            // get an instance of the corresponding Key Store Manager instance
            KeyStoreManager keyStoreManager = KeyStoreManager.getInstance(tenantId);
            keyStore = keyStoreManager.getKeyStore(generateKSNameFromDomainName(tenantDomain));
            cert = (java.security.cert.X509Certificate) keyStore.getCertificate(tenantDomain);
        } else {
            keyStore = KeyStore.getInstance("JKS");
            keyStore.load(new FileInputStream(new File(keyStoreName)), keyStorePassword.toCharArray());
            cert = (java.security.cert.X509Certificate) keyStore.getCertificate(alias);
        }
        if(log.isDebugEnabled()){
            log.debug("Validating against "+cert.getSubjectDN().getName());
        }
        X509CredentialImpl credentialImpl = new X509CredentialImpl(cert);
        SignatureValidator signatureValidator = new SignatureValidator(credentialImpl);
        signatureValidator.validate(resp.getSignature());
        isSigValid = true;
        return isSigValid;
    } catch (Exception e) {
        if (log.isDebugEnabled()){
        log.debug("Signature verification is failed for "+tenantDomain);
        }
        return isSigValid;
    }
}
 
public void addToCache(String key, IdentityMessageContext context) {
    super.addToCache(key, context);
    if (enableRequestScopeCache) {
        int tenantId = MultitenantConstants.INVALID_TENANT_ID;
        String tenantDomain = context.getRequest().getTenantDomain();
        if (tenantDomain != null) {
            tenantId = IdentityTenantUtil.getTenantId(tenantDomain);
        }
        SessionDataStore.getInstance().storeSessionData(key, INBOUND_CONTEXT_CACHE_NAME, context, tenantId);
    }
}
 
源代码22 项目: carbon-apimgt   文件: CertificateManagerImplTest.java
/**
 * This method tests the behaviour of addClientCertificate method under different conditions.
 */
@Test
public void testAddClientCertificate() {
    PowerMockito
            .stub(PowerMockito.method(CertificateMgtUtils.class, "validateCertificate"))
            .toReturn(ResponseCode.ALIAS_EXISTS_IN_TRUST_STORE);
    ResponseCode responseCode = certificateManager
            .addClientCertificate(null, BASE64_ENCODED_CERT, ALIAS, null, MultitenantConstants.SUPER_TENANT_ID);
    Assert.assertEquals("Response code was wrong while trying add a client certificate with an existing alias",
            ResponseCode.ALIAS_EXISTS_IN_TRUST_STORE.getResponseCode(), responseCode.getResponseCode());
    PowerMockito
            .stub(PowerMockito.method(CertificateMgtUtils.class, "validateCertificate"))
            .toReturn(ResponseCode.SUCCESS);
    PowerMockito.stub(PowerMockito.method(CertificateMgtDAO.class, "checkWhetherAliasExist"))
            .toReturn(true);
    responseCode = certificateManager
            .addClientCertificate(null, BASE64_ENCODED_CERT, ALIAS, null, MultitenantConstants.SUPER_TENANT_ID);
    Assert.assertEquals("Response code was wrong while trying add a client certificate with an existing alias",
            ResponseCode.ALIAS_EXISTS_IN_TRUST_STORE.getResponseCode(), responseCode.getResponseCode());
    PowerMockito.stub(PowerMockito.method(CertificateMgtDAO.class, "checkWhetherAliasExist"))
            .toReturn(false);
    PowerMockito.stub(PowerMockito.method(CertificateMgtDAO.class, "addClientCertificate")).toReturn(true);
    responseCode = certificateManager
            .addClientCertificate(null, BASE64_ENCODED_CERT, ALIAS, null, MultitenantConstants.SUPER_TENANT_ID);
    Assert.assertEquals("Response code was wrong while trying add a client certificate",
            ResponseCode.SUCCESS.getResponseCode(), responseCode.getResponseCode());
}
 
源代码23 项目: product-es   文件: MigrateFrom200to210.java
/**
 * This method returns the list of tenants.
 * @return list of tenants
 * @throws org.wso2.carbon.user.api.UserStoreException
 */
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;
}
 
/**
 * Add a cache entry.
 *
 * @param key   Key which cache entry is indexed.
 * @param entry Actual object where cache entry is placed.
 */
public void addToCache(AuthenticationRequestCacheKey key, AuthenticationRequestCacheEntry entry) {
    super.addToCache(key,entry);
    if (isTemporarySessionDataPersistEnabled) {
        int tenantId = MultitenantConstants.INVALID_TENANT_ID;
        String tenantDomain = entry.getAuthenticationRequest().getTenantDomain();
        if (tenantDomain != null) {
            tenantId = IdentityTenantUtil.getTenantId(tenantDomain);
        }
        SessionDataStore.getInstance().storeSessionData(key.getResultId(), AUTHENTICATION_REQUEST_CACHE_NAME,
                entry, tenantId);
    }
}
 
/**
 * Add a cache entry.
 *
 * @param key   Key which cache entry is indexed.
 * @param entry Actual object where cache entry is placed.
 */
public void addToCache(AuthenticationContextCacheKey key, AuthenticationContextCacheEntry entry) {
    super.addToCache(key, entry);
    if (isTemporarySessionDataPersistEnabled) {
        int tenantId = MultitenantConstants.INVALID_TENANT_ID;
        String tenantDomain = entry.getContext().getTenantDomain();
        if (tenantDomain != null) {
            tenantId = IdentityTenantUtil.getTenantId(tenantDomain);
        }

        if (entry.getContext() != null && entry.getContext().getProperties() != null) {
            Iterator it = entry.getContext().getProperties().entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry<String, Object> item = (Map.Entry<String, Object>) it.next();
                if (!(item.getValue() instanceof Serializable)) {
                    it.remove();
                }
            }
            if (log.isDebugEnabled()) {
                String message = "[ Context Id : " + key.getContextId() +
                        ", Cache type : " + AUTHENTICATION_CONTEXT_CACHE_NAME +
                        ", Operation : STORE ]";
                log.debug("Authentication context is stored with details " + message);
            }
            SessionDataStore.getInstance().storeSessionData(key.getContextId(), AUTHENTICATION_CONTEXT_CACHE_NAME,
                    entry, tenantId);
        }
    }
}
 
源代码26 项目: carbon-identity   文件: IdPManagementDAO.java
/**
 * @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();
    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");
        }

        dbConnection.commit();
        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);
    }

}
 
private long getCleanupTimeout(String type, int tenantId) {
    if (isTempCache(type)) {
        return TimeUnit.MINUTES.toNanos(IdentityUtil.getTempDataCleanUpTimeout());
    } else if (tenantId != MultitenantConstants.INVALID_TENANT_ID) {
        String tenantDomain = IdentityTenantUtil.getTenantDomain(tenantId);
        return TimeUnit.SECONDS.toNanos(IdPManagementUtil.getRememberMeTimeout(tenantDomain));
    } else {
        return TimeUnit.MINUTES.toNanos(IdentityUtil.getCleanUpTimeout());
    }
}
 
/**
 * Add a cache entry.
 *
 * @param key   Key which cache entry is indexed.
 * @param entry Actual object where cache entry is placed.
 */
public void addToCache(AuthenticationContextCacheKey key, AuthenticationContextCacheEntry entry) {
    super.addToCache(key, entry);
    if (isTemporarySessionDataPersistEnabled) {
        int tenantId = MultitenantConstants.INVALID_TENANT_ID;
        String tenantDomain = entry.getContext().getTenantDomain();
        if (tenantDomain != null) {
            tenantId = IdentityTenantUtil.getTenantId(tenantDomain);
        }
        SessionDataStore.getInstance().storeSessionData(key.getContextId(), AUTHENTICATION_CONTEXT_CACHE_NAME,
                entry, tenantId);
    }
}
 
源代码29 项目: carbon-apimgt   文件: SAMLSSORelyingPartyObject.java
/**
 * Get SAML authentication request build with given issuer
 *
 * @param cx
 * @param thisObj
 * @param args
 * @param funObj
 * @return
 * @throws Exception
 */

public static String jsFunction_getSAMLAuthRequest(Context cx, Scriptable thisObj, Object[] args, Function funObj)
        throws Exception {
    SAMLSSORelyingPartyObject relyingPartyObject = (SAMLSSORelyingPartyObject) thisObj;

    int argLength = args.length;
    String acsUrl = argLength >= 1 ? (String) args[0] : null; //set as the value of 1st arg if exists
    boolean isPassiveAuthRequired = argLength >= 2 ? (Boolean) args[1] : false; //set as 2nd arg if exists
    String nameIdPolicy = relyingPartyObject.getSSOProperty(SSOConstants.NAME_ID_POLICY);

    //check if request signing is required
    if (Boolean.parseBoolean(relyingPartyObject.getSSOProperty(SSOConstants.SIGN_REQUESTS))) {
        //builds a signed authentication request
        return Util.marshall(new AuthReqBuilder().
                buildSignedAuthRequest(
                        relyingPartyObject.getSSOProperty(SSOConstants.ISSUER_ID),
                        relyingPartyObject.getSSOProperty(SSOConstants.IDP_URL),
                        acsUrl, isPassiveAuthRequired, MultitenantConstants.SUPER_TENANT_ID,
                        MultitenantConstants.SUPER_TENANT_DOMAIN_NAME, nameIdPolicy));
    } else {
        //builds an unsigned authentication request
        return Util.marshall(new AuthReqBuilder().
                buildAuthenticationRequest(
                        relyingPartyObject.getSSOProperty(SSOConstants.ISSUER_ID), acsUrl, isPassiveAuthRequired,
                        nameIdPolicy));
    }
}
 
源代码30 项目: carbon-apimgt   文件: SelfSignUpUtil.java
/**
 * This method is used to construct the endpoint URL to call the consent management service
 *
 * @param tenantDomain The tenant domain
 * @return endpoint url
 */
private static String getPurposesEndpoint(String tenantDomain) {
    APIManagerConfiguration config = ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService()
            .getAPIManagerConfiguration();
    String serviceUrl = config.getFirstProperty(APIConstants.AUTH_MANAGER_URL);
    String purposesEndpoint;
    if (!MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equalsIgnoreCase(tenantDomain)) {
        purposesEndpoint = serviceUrl.replace(APIConstants.SERVICES_URL_RELATIVE_PATH,
                "t/" + tenantDomain + "/" + CONSENT_API_RELATIVE_PATH + PURPOSES_ENDPOINT_RELATIVE_PATH);
    } else {
        purposesEndpoint = serviceUrl.replace(APIConstants.SERVICES_URL_RELATIVE_PATH,
                CONSENT_API_RELATIVE_PATH + PURPOSES_ENDPOINT_RELATIVE_PATH);
    }
    return purposesEndpoint;
}