org.wso2.carbon.context.PrivilegedCarbonContext Java Examples

The following examples show how to use org.wso2.carbon.context.PrivilegedCarbonContext. 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: DeviceMgtAPIUtils.java    From carbon-device-mgt with Apache License 2.0 6 votes vote down vote up
public static IntegrationClientService getIntegrationClientService() {
    if (integrationClientService == null) {
        synchronized (DeviceMgtAPIUtils.class) {
            if (integrationClientService == null) {
                PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
                integrationClientService = (IntegrationClientService) ctx.getOSGiService(IntegrationClientService.class, null);
                if (integrationClientService == null) {
                    String msg = "IntegrationClientService is not initialized";
                    log.error(msg);
                    throw new IllegalStateException(msg);
                }
            }
        }
    }
    return integrationClientService;
}
 
Example #2
Source File: SSOConsentServiceImpl.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
private AddReceiptResponse addReceipt(String subject, String subjectTenantDomain, ServiceProvider
        serviceProvider, String spTenantDomain, List<ClaimMetaData> claims) throws
        SSOConsentServiceException {

    ReceiptInput receiptInput = buildReceiptInput(subject, serviceProvider, spTenantDomain, claims);
    AddReceiptResponse receiptResponse;
    try {
        startTenantFlowWithUser(subject, subjectTenantDomain);
        receiptResponse = getConsentManager().addConsent(receiptInput);
    } catch (ConsentManagementException e) {
        throw new SSOConsentServiceException("Consent receipt error", "Error while adding the consent " +
                "receipt", e);
    } finally {
        PrivilegedCarbonContext.endTenantFlow();
    }
    if (isDebugEnabled()) {
        logDebug("Successfully added consent receipt: " + receiptResponse.getConsentReceiptId());
    }
    return receiptResponse;
}
 
Example #3
Source File: BaseCache.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
/**
 * Remove everything in the cache.
 */
public void clear() {
    if (!isEnabled()) {
        return;
    }

    try {
        PrivilegedCarbonContext.startTenantFlow();
        PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext
                .getThreadLocalCarbonContext();
        carbonContext.setTenantId(MultitenantConstants.SUPER_TENANT_ID);
        carbonContext.setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
        Cache<K, V> cache = getBaseCache();
        if (cache != null) {
            cache.removeAll();
        }
    } finally {
        PrivilegedCarbonContext.endTenantFlow();
    }
}
 
Example #4
Source File: AbstractAdmin.java    From product-private-paas with Apache License 2.0 6 votes vote down vote up
protected ConfigurationContext getConfigContext() {

        // If a tenant has been set, then try to get the ConfigurationContext of that tenant
        PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
        ConfigurationContextService configurationContextService = (ConfigurationContextService) carbonContext
                .getOSGiService(ConfigurationContextService.class);
        ConfigurationContext mainConfigContext = configurationContextService.getServerConfigContext();
        String domain = carbonContext.getTenantDomain();
        if (domain != null && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(domain)) {
            return TenantAxisUtils.getTenantConfigurationContext(domain, mainConfigContext);
        } else if (carbonContext.getTenantId() == MultitenantConstants.SUPER_TENANT_ID) {
            return mainConfigContext;
        } else {
            throw new UnsupportedOperationException("Tenant domain unidentified. " +
                    "Upstream code needs to identify & set the tenant domain & tenant ID. " +
                    " The TenantDomain SOAP header could be set by the clients or " +
                    "tenant authentication should be carried out.");
        }
    }
 
Example #5
Source File: AccountCredentialMgtConfigService.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
/**
 * This method is used to load the tenant specific Email template configurations.
 *
 * @return an array of templates.
 * @throws IdentityMgtServiceException
 */
public EmailTemplateDTO[] getEmailConfig() throws IdentityMgtServiceException {

    int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext()
            .getTenantId();
    Config emailConfig = null;
    EmailTemplateDTO[] templates = null;
    ConfigBuilder configBuilder = ConfigBuilder.getInstance();
    try {
        emailConfig = configBuilder.loadConfiguration(ConfigType.EMAIL,
                                                      StorageType.REGISTRY, tenantId);
        if (emailConfig != null) {

            templates = EmailConfigTransformer.transform(emailConfig.getProperties());
        }
    } catch (Exception e) {
        log.error("Error occurred while loading email configuration", e);
        throw new IdentityMgtServiceException("Error occurred while loading email configuration");
    }

    return templates;
}
 
Example #6
Source File: ServerIdentityGovernanceService.java    From identity-api-server with Apache License 2.0 6 votes vote down vote up
/**
 * Get all governance connector categories.
 *
 * @param limit  Page size.
 * @param offset Page start index.
 * @param filter Filter to search for categories.
 * @param sort   Sort order.
 * @return List of governance connector categories.
 */
public List<CategoriesRes> getGovernanceConnectors(Integer limit, Integer offset, String filter, String sort) {

    handleNotImplementedCapabilities(limit, offset, filter, sort);

    try {
        IdentityGovernanceService identityGovernanceService = GovernanceDataHolder.getIdentityGovernanceService();
        String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain();
        Map<String, List<ConnectorConfig>> connectorConfigs =
                identityGovernanceService.getCategorizedConnectorListWithConfigs(tenantDomain);

        return buildConnectorCategoriesResDTOS(connectorConfigs);

    } catch (IdentityGovernanceException e) {
        GovernanceConstants.ErrorMessage errorEnum =
                GovernanceConstants.ErrorMessage.ERROR_CODE_ERROR_RETRIEVING_CATEGORIES;
        Response.Status status = Response.Status.INTERNAL_SERVER_ERROR;
        throw handleException(e, errorEnum, status);
    }
}
 
Example #7
Source File: IdPInitSSOAuthnRequestProcessor.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the configured service provider configurations. The
 * configurations are taken from the user registry or from the
 * sso-idp-config.xml configuration file. In Stratos deployment the
 * configurations are read from the sso-idp-config.xml file.
 *
 * @param authnReqDTO
 * @return
 * @throws IdentityException
 */
private SAMLSSOServiceProviderDO getServiceProviderConfig(SAMLSSOAuthnReqDTO authnReqDTO)
        throws IdentityException {
    try {
        SSOServiceProviderConfigManager stratosIdpConfigManager = SSOServiceProviderConfigManager
                .getInstance();
        SAMLSSOServiceProviderDO ssoIdpConfigs = stratosIdpConfigManager
                .getServiceProvider(authnReqDTO.getIssuer());
        if (ssoIdpConfigs == null) {
            IdentityPersistenceManager persistenceManager = IdentityPersistenceManager
                    .getPersistanceManager();
            Registry registry = (Registry) PrivilegedCarbonContext.getThreadLocalCarbonContext().getRegistry(RegistryType.SYSTEM_CONFIGURATION);
            ssoIdpConfigs = persistenceManager.getServiceProvider(registry,
                    authnReqDTO.getIssuer());
            authnReqDTO.setStratosDeployment(false); // not stratos
        } else {
            authnReqDTO.setStratosDeployment(true); // stratos deployment
        }
        return ssoIdpConfigs;
    } catch (Exception e) {
        throw IdentityException.error("Error while reading Service Provider configurations", e);
    }
}
 
Example #8
Source File: Utils.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * Put the access token that was cached in the tenant's cache space into invalid token cache
 *
 * @param accessToken        - Invalid token that should be added to the invalid token cache
 * @param cachedTenantDomain - Tenant domain of the cached token
 */
public static void putInvalidTokenIntoTenantInvalidTokenCache(String accessToken, String cachedTenantDomain) {
    //If the token was cached in the tenant cache
    if (cachedTenantDomain != null && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(cachedTenantDomain)) {

        if (log.isDebugEnabled()) {
            log.debug("Putting the cache entry " + accessToken + " of " + cachedTenantDomain + " domain " +
                    "to the invalid token cache...");
        }
        try {
            PrivilegedCarbonContext.startTenantFlow();
            PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(cachedTenantDomain, true);
            putInvalidTokenEntryIntoInvalidTokenCache(accessToken, cachedTenantDomain);
            if (log.isDebugEnabled()) {
                log.debug(" Token " + accessToken + " of " + cachedTenantDomain + " domain was put to the " +
                        "invalid token cache.");
            }
        } finally {
            PrivilegedCarbonContext.endTenantFlow();
        }
    }
}
 
Example #9
Source File: MigrateFrom200to210.java    From product-es with Apache License 2.0 6 votes vote down vote up
/**
 * This method removes the store.json file at config registry which will fix issue REGISTRY-3528
 * @param tenant tenant
 * @throws UserStoreException
 * @throws RegistryException
 * @throws XMLStreamException
 */
private void clean(Tenant tenant) throws UserStoreException, RegistryException, XMLStreamException {

    int tenantId = tenant.getId();
    try {
        PrivilegedCarbonContext.startTenantFlow();
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenant.getDomain(), true);
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(tenantId);
        String adminName = ServiceHolder.getRealmService().getTenantUserRealm(tenantId).getRealmConfiguration()
                .getAdminUserName();
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(adminName);
        ServiceHolder.getTenantRegLoader().loadTenantRegistry(tenantId);
        Registry registry = ServiceHolder.getRegistryService().getConfigUserRegistry(adminName,tenantId);
        if(registry.resourceExists(Constants.STORE_CONFIG_PATH)){
            registry.delete(Constants.STORE_CONFIG_PATH);
        }
    } finally {
        PrivilegedCarbonContext.endTenantFlow();
    }

}
 
Example #10
Source File: MediationSecurityAdminServiceProxy.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
public boolean isAliasExist(String alias) throws APIManagementException {

        UserRegistry registry = GatewayUtils.getRegistry(tenantDomain);
        PrivilegedCarbonContext.startTenantFlow();
        if (tenantDomain != null && StringUtils.isNotEmpty(tenantDomain)) {
            PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);
        } else {
            PrivilegedCarbonContext.getThreadLocalCarbonContext()
                    .setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME, true);
        }
        try {
            if (registry.resourceExists(APIConstants.API_SYSTEM_CONFIG_SECURE_VAULT_LOCATION)) {
                Resource resource = registry.get(APIConstants.API_SYSTEM_CONFIG_SECURE_VAULT_LOCATION);
                if (resource.getProperty(alias) != null) {
                    return true;
                }
            }
            return false;
        } catch (RegistryException e) {
            throw new APIManagementException("Error while reading registry resource "
                    + APIConstants.API_SYSTEM_CONFIG_SECURE_VAULT_LOCATION + " for tenant " + tenantDomain);
        } finally {
            PrivilegedCarbonContext.endTenantFlow();
        }
    }
 
Example #11
Source File: QueryBuilderImpl.java    From carbon-device-mgt with Apache License 2.0 6 votes vote down vote up
private String getGenericQueryPart(ValueType[] valueTypeArray) throws InvalidOperatorException {
    try {
        String query = "SELECT D.ID, D.DESCRIPTION, D.NAME,  \n" +
                "D.DEVICE_TYPE_ID, D.DEVICE_IDENTIFICATION,  DT.ID AS DEVICE_TYPE_ID, \n" +
                "DT.NAME AS DEVICE_TYPE_NAME, DD.DEVICE_ID, DD.DEVICE_MODEL, DD.VENDOR, \n" +
                "DD.OS_VERSION, DD.OS_BUILD_DATE, DD.BATTERY_LEVEL, DD.INTERNAL_TOTAL_MEMORY, DD.INTERNAL_AVAILABLE_MEMORY,\n" +
                "DD.EXTERNAL_TOTAL_MEMORY, DD.EXTERNAL_AVAILABLE_MEMORY, DD.CONNECTION_TYPE, \n" +
                "DD.SSID, DD.CPU_USAGE, DD.TOTAL_RAM_MEMORY, DD.AVAILABLE_RAM_MEMORY, \n" +
                "DD.PLUGGED_IN, DD.UPDATE_TIMESTAMP, DL.LATITUDE, DL.LONGITUDE, DL.STREET1, DL.STREET2, DL.CITY, DL.ZIP, \n" +
                "DL.STATE, DL.COUNTRY, DL.UPDATE_TIMESTAMP AS DL_UPDATED_TIMESTAMP, DE.OWNER, DE.OWNERSHIP, DE.STATUS " +
                "AS DE_STATUS FROM DM_DEVICE_DETAIL DD INNER JOIN DM_DEVICE D ON D.ID=DD.DEVICE_ID\n" +
                "LEFT JOIN DM_DEVICE_LOCATION DL ON DL.DEVICE_ID=D.ID \n" +
                "INNER JOIN DM_DEVICE_TYPE DT ON DT.ID=D.DEVICE_TYPE_ID\n" +
                "INNER JOIN DM_ENROLMENT DE ON D.ID=DE.DEVICE_ID\n" +
                "WHERE D.TENANT_ID = ? ";

        ValueType type = new ValueType();
        type.setIntValue(PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId());
        type.setColumnType(ValueType.columnType.INTEGER);
        valueTypeArray[0] = type;
        return query;

    } catch (Exception e) {
        throw new InvalidOperatorException("Error occurred while building the sql", e);
    }
}
 
Example #12
Source File: WorkflowExecutorFactoryTest.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Before
public void init() {
    System.setProperty(CARBON_HOME, "");
    carbonContext = Mockito.mock(PrivilegedCarbonContext.class);
    PowerMockito.mockStatic(PrivilegedCarbonContext.class);
    PowerMockito.when(PrivilegedCarbonContext.getThreadLocalCarbonContext()).thenReturn(carbonContext);
    PowerMockito.when(carbonContext.getTenantDomain()).thenReturn(tenantDomain);
    PowerMockito.when(carbonContext.getTenantId()).thenReturn(tenantID);
    cache = Mockito.mock(Cache.class);
    CacheManager cacheManager = Mockito.mock(CacheManager.class);
    PowerMockito.mockStatic(Caching.class);
    Mockito.when(Caching.getCacheManager(APIConstants.API_MANAGER_CACHE_MANAGER)).thenReturn(cacheManager);
    Mockito.when(cacheManager.getCache(APIConstants.WORKFLOW_CACHE_NAME)).thenReturn(cache);
    tenantWorkflowConfigHolder = Mockito.mock(TenantWorkflowConfigHolder.class);
    workflowExecutorFactory = WorkflowExecutorFactory.getInstance();
}
 
Example #13
Source File: EntitlementEngineCache.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
public EntitlementEngine get(int key) {
    try {
        PrivilegedCarbonContext.startTenantFlow();
        PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
        carbonContext.setTenantId(MultitenantConstants.SUPER_TENANT_ID);
        carbonContext.setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
        EntitlementEngine entitlementEngine = getEntitlementCache().get(key);
        if (entitlementEngine != null) {
            if (log.isDebugEnabled()) {
                log.debug("Cache : " + ENTITLEMENT_ENGINE_CACHE + "  is HIT " +
                        "for tenantId : " + key);
            }
        } else {
            if (log.isDebugEnabled()) {
                log.debug("Cache : " + ENTITLEMENT_ENGINE_CACHE + "  is MISSED " +
                        "for tenantId : " + key);
            }
        }
        return entitlementEngine;
    } finally {
        PrivilegedCarbonContext.endTenantFlow();
    }
}
 
Example #14
Source File: ConfigurationDAOImpl.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
private boolean isResourceExists(Resource resource, String resourceTypeId) throws TransactionException {

        JdbcTemplate jdbcTemplate = JdbcUtils.getNewTemplate();
        String resourceId = jdbcTemplate.withTransaction(template ->
                template.fetchSingleRecord(
                        GET_RESOURCE_ID_BY_NAME_SQL,
                        (resultSet, rowNumber) -> resultSet.getString(DB_SCHEMA_COLUMN_NAME_ID),
                        preparedStatement -> {
                            int initialParameterIndex = 1;
                            preparedStatement.setString(initialParameterIndex, resource.getResourceName());
                            preparedStatement.setInt(++initialParameterIndex,
                                    PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId());
                            preparedStatement.setString(++initialParameterIndex, resourceTypeId);
                        }
                )
        );
        return resourceId != null;
    }
 
Example #15
Source File: AbstractFeatureDAO.java    From carbon-device-mgt with Apache License 2.0 6 votes vote down vote up
@Override
public boolean deleteFeaturesOfProfile(int profileId) throws FeatureManagerDAOException {
    Connection conn;
    PreparedStatement stmt = null;
    int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
    try {
        conn = this.getConnection();
        String query = "DELETE FROM DM_PROFILE_FEATURES WHERE PROFILE_ID = ? AND TENANT_ID = ?";
        stmt = conn.prepareStatement(query);
        stmt.setInt(1, profileId);
        stmt.setInt(2, tenantId);
        if (stmt.executeUpdate() > 0) {
            return true;
        }
        return false;
    } catch (SQLException e) {
        throw new FeatureManagerDAOException("Error occurred while deleting the feature related to a profile.", e);
    } finally {
        PolicyManagementDAOUtil.cleanupResources(stmt, null);
    }
}
 
Example #16
Source File: SPInitSSOAuthnRequestProcessor.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the configured service provider configurations. The
 * configurations are taken from the user registry or from the
 * sso-idp-config.xml configuration file. In Stratos deployment the
 * configurations are read from the sso-idp-config.xml file.
 *
 * @param authnReqDTO
 * @return
 * @throws IdentityException
 */
private SAMLSSOServiceProviderDO getServiceProviderConfig(SAMLSSOAuthnReqDTO authnReqDTO)
        throws IdentityException {
    try {
        SSOServiceProviderConfigManager stratosIdpConfigManager = SSOServiceProviderConfigManager
                .getInstance();
        SAMLSSOServiceProviderDO ssoIdpConfigs = stratosIdpConfigManager
                .getServiceProvider(authnReqDTO.getIssuer());
        if (ssoIdpConfigs == null) {
            IdentityTenantUtil.initializeRegistry(PrivilegedCarbonContext.getThreadLocalCarbonContext()
                    .getTenantId(), PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain());
            IdentityPersistenceManager persistenceManager = IdentityPersistenceManager.getPersistanceManager();
            Registry registry = (Registry) PrivilegedCarbonContext.getThreadLocalCarbonContext().getRegistry
                    (RegistryType.SYSTEM_CONFIGURATION);
            ssoIdpConfigs = persistenceManager.getServiceProvider(registry, authnReqDTO.getIssuer());
            authnReqDTO.setStratosDeployment(false); // not stratos
        } else {
            authnReqDTO.setStratosDeployment(true); // stratos deployment
        }
        return ssoIdpConfigs;
    } catch (Exception e) {
        throw IdentityException.error("Error while reading Service Provider configurations", e);
    }
}
 
Example #17
Source File: BaseCache.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
/**
 * Add a cache entry.
 *
 * @param key   Key which cache entry is indexed.
 * @param entry Actual object where cache entry is placed.
 */
public void addToCache(K key, V entry) {

    if (!isEnabled()) {
        return;
    }

    try {
        PrivilegedCarbonContext.startTenantFlow();
        PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext
                .getThreadLocalCarbonContext();
        carbonContext.setTenantId(MultitenantConstants.SUPER_TENANT_ID);
        carbonContext.setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
        // Element already in the cache. Remove it first
        Cache<K, V> cache = getBaseCache();
        if (cache != null) {
            cache.put(key, entry);
        }
    } finally {
        PrivilegedCarbonContext.endTenantFlow();
    }
}
 
Example #18
Source File: OperationManagementTests.java    From carbon-device-mgt with Apache License 2.0 6 votes vote down vote up
@Test(dependsOnMethods = "getOperationForInactiveDevice", expectedExceptions = OperationManagementException.class)
public void getPaginatedOperationDeviceForInvalidDevice() throws DeviceManagementException,
        OperationManagementException {
    PrivilegedCarbonContext.startTenantFlow();
    PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(MultitenantConstants.SUPER_TENANT_ID, true);
    PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(ADMIN_USER);
    try {
        PaginationRequest request = new PaginationRequest(1, 2);
        request.setDeviceType(DEVICE_TYPE);
        request.setOwner(ADMIN_USER);
        PaginationResult result = this.operationMgtService.getOperations
                (new DeviceIdentifier(INVALID_DEVICE, DEVICE_TYPE), request);
        Assert.assertEquals(result.getRecordsFiltered(), 4);
        Assert.assertEquals(result.getData().size(), 2);
        Assert.assertEquals(result.getRecordsTotal(), 4);
    } finally {
        PrivilegedCarbonContext.endTenantFlow();
    }
}
 
Example #19
Source File: StratosAuthorizingHandler.java    From product-private-paas with Apache License 2.0 6 votes vote down vote up
private boolean authorize(String userName, String tenantDomain, int tenantId, Method targetMethod)
        throws Exception {
    // first we try to see whether this is a super.tenant only operation
    if (superTenantServiceSet.contains(targetMethod.getName()) && !isCurrentUserSuperTenant(tenantDomain,
            tenantId)) {
        return false;
    }
    // authorize using permissionString given as annotation in the service class
    String permissionString = authorizationActionMap.get(targetMethod.getName());

    // get the authorization manager for this tenant..
    UserRealm userRealm = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUserRealm();
    AuthorizationManager authorizationManager = userRealm.getAuthorizationManager();

    boolean isAuthorized = isAuthorized(authorizationManager, userName, permissionString, ACTION_ON_RESOURCE);
    return isAuthorized;

}
 
Example #20
Source File: DeviceTypeUtils.java    From product-iots with Apache License 2.0 6 votes vote down vote up
public static void setupMqttOutputAdapter() throws IOException {
    OutputEventAdapterConfiguration outputEventAdapterConfiguration =
            createMqttOutputEventAdapterConfiguration(DeviceTypeConstants.MQTT_ADAPTER_NAME,
                    DeviceTypeConstants.MQTT_ADAPTER_TYPE, MessageType.TEXT);
    try {
        PrivilegedCarbonContext.startTenantFlow();
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(
                DeviceTypeConstants.DEVICE_TYPE_PROVIDER_DOMAIN, true);
        DeviceTypeManagementDataHolder.getInstance().getOutputEventAdapterService()
                .create(outputEventAdapterConfiguration);
    } catch (OutputEventAdapterException e) {
        log.error("Unable to create Output Event Adapter : " + DeviceTypeConstants.MQTT_ADAPTER_NAME, e);
    } finally {
        PrivilegedCarbonContext.endTenantFlow();
    }
}
 
Example #21
Source File: EmailSender.java    From carbon-commons with Apache License 2.0 6 votes vote down vote up
private String getRequestMessage() {
    String msg;
    String targetEpr = config.getTargetEpr();
    String tenantDomain = this.tenantDomain;
    if (tenantDomain == null) {
        PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain(true);
    }
    if (tenantDomain != null && targetEpr.indexOf("/carbon") > 0 &&
        MultitenantUtils.getTenantDomainFromRequestURL(targetEpr) == null &&
        PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true)!= MultitenantConstants.SUPER_TENANT_ID) {
        targetEpr = targetEpr.replace("/carbon", "/" +
                                                 MultitenantConstants.TENANT_AWARE_URL_PREFIX + "/" + tenantDomain + "/carbon");
    }
    if (config.getEmailBody().length() == 0) {
        msg = EmailVerifierConfig.DEFAULT_VALUE_MESSAGE + "\n" + targetEpr + "?"
              + CONF_STRING + "=" + secretKey + "\n";
    } else {
        msg = config.getEmailBody() + "\n" + targetEpr + "?" + CONF_STRING + "="
              + secretKey + "\n";
    }
    if (config.getEmailFooter() != null) {
        msg = msg + "\n" + config.getEmailFooter();
    }
    return msg;
}
 
Example #22
Source File: PolicyDAOImpl.java    From carbon-device-mgt with Apache License 2.0 6 votes vote down vote up
@Override
public void setPolicyApplied(int deviceId, int enrollmentId) throws PolicyManagerDAOException {
    Connection conn;
    PreparedStatement stmt = null;
    Timestamp currentTimestamp = new Timestamp(Calendar.getInstance().getTime().getTime());
    int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
    try {
        conn = this.getConnection();
        String query = "UPDATE DM_DEVICE_POLICY_APPLIED SET APPLIED_TIME = ?, APPLIED = ? WHERE DEVICE_ID = ? AND" +
                " TENANT_ID = ? AND ENROLMENT_ID = ?";
        stmt = conn.prepareStatement(query);
        stmt.setTimestamp(1, currentTimestamp);
        stmt.setBoolean(2, true);
        stmt.setInt(3, deviceId);
        stmt.setInt(4, tenantId);
        stmt.setInt(5, enrollmentId);
        stmt.executeUpdate();
    } catch (SQLException e) {
        throw new PolicyManagerDAOException("Error occurred while updating applied policy to device (" +
                deviceId + ")", e);
    } finally {
        PolicyManagementDAOUtil.cleanupResources(stmt, null);
    }
}
 
Example #23
Source File: AbstractFeatureDAO.java    From carbon-device-mgt with Apache License 2.0 6 votes vote down vote up
@Override
public boolean deleteProfileFeatures(int featureId) throws FeatureManagerDAOException {
    Connection conn;
    PreparedStatement stmt = null;
    int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
    try {
        conn = this.getConnection();
        String query = "DELETE FROM DM_PROFILE_FEATURES WHERE ID = ? AND TENANT_ID = ?";
        stmt = conn.prepareStatement(query);
        stmt.setInt(1, featureId);
        stmt.setInt(2, tenantId);
        if (stmt.executeUpdate() > 0) {
            return true;
        }
        return false;
    } catch (SQLException e) {
        throw new FeatureManagerDAOException("Error occurred while deleting the feature related to a profile.", e);
    } finally {
        PolicyManagementDAOUtil.cleanupResources(stmt, null);
    }
}
 
Example #24
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 #25
Source File: GroupManagementServiceImpl.java    From carbon-device-mgt with Apache License 2.0 6 votes vote down vote up
@Override
public Response getGroups(String name, String owner, int offset, int limit) {
    try {
        RequestValidationUtil.validatePaginationParameters(offset, limit);
        String currentUser = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
        GroupPaginationRequest request = new GroupPaginationRequest(offset, limit);
        request.setGroupName(name);
        request.setOwner(owner);
        PaginationResult deviceGroupsResult = DeviceMgtAPIUtils.getGroupManagementProviderService()
                .getGroups(currentUser, request);
        DeviceGroupList deviceGroupList = new DeviceGroupList();
        if (deviceGroupsResult.getData() != null && deviceGroupsResult.getRecordsTotal() > 0) {
            deviceGroupList.setList(deviceGroupsResult.getData());
            deviceGroupList.setCount(deviceGroupsResult.getRecordsTotal());
        } else {
            deviceGroupList.setList(new ArrayList<>());
            deviceGroupList.setCount(0);
        }
        return Response.status(Response.Status.OK).entity(deviceGroupList).build();
    } catch (GroupManagementException e) {
        String error = "Error occurred while getting the groups.";
        log.error(error, e);
        return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(error).build();
    }
}
 
Example #26
Source File: HostObjectUtils.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * This method will clear recently added API cache.
 * @param username
 */
public static void invalidateRecentlyAddedAPICache(String username){
    try{
        PrivilegedCarbonContext.startTenantFlow();
        APIManagerConfiguration config = HostObjectComponent.getAPIManagerConfiguration();
        boolean isRecentlyAddedAPICacheEnabled =
              Boolean.parseBoolean(config.getFirstProperty(APIConstants.API_STORE_RECENTLY_ADDED_API_CACHE_ENABLE));

        if (username != null && isRecentlyAddedAPICacheEnabled) {
            String tenantDomainFromUserName = MultitenantUtils.getTenantDomain(username);
            if (tenantDomainFromUserName != null &&
                !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomainFromUserName)) {
                PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomainFromUserName,
                                                                                      true);
            } else {
                PrivilegedCarbonContext.getThreadLocalCarbonContext()
                                       .setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME, true);
            }
            Caching.getCacheManager(APIConstants.API_MANAGER_CACHE_MANAGER).getCache("RECENTLY_ADDED_API")
                   .remove(username + ":" + tenantDomainFromUserName);
        }
    } finally {
        PrivilegedCarbonContext.endTenantFlow();
    }
}
 
Example #27
Source File: StratosApiV41Utils.java    From attic-stratos with Apache License 2.0 6 votes vote down vote up
private static void clearMetadata(String applicationId) throws RestAPIException {

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

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

    try {
        UserRegistry registry = getRegistry(tenantDomain);
        PrivilegedCarbonContext.startTenantFlow();
        if (tenantDomain != null && StringUtils.isNotEmpty(tenantDomain)) {
            PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);
        } else {
            PrivilegedCarbonContext.getThreadLocalCarbonContext()
                    .setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME, true);
        }
        Resource resource = registry.get(path);
        if (resource != null && resource.getProperty(propertyName) != null) {
            resource.removeProperty(propertyName);
            registry.put(resource.getPath(), resource);
            resource.discard();
        }
    } catch (RegistryException | APIManagementException e) {
        String msg = "Failed to delete secure endpoint password alias " + e.getMessage();
        throw new AxisFault(msg, e);
    } finally {
        PrivilegedCarbonContext.endTenantFlow();
    }
}
 
Example #29
Source File: PolicyDAOImpl.java    From carbon-device-mgt with Apache License 2.0 6 votes vote down vote up
@Override
public void addDeviceGroupsToPolicy(Policy policy) throws PolicyManagerDAOException {

    Connection conn;
    PreparedStatement stmt = null;
    List<DeviceGroupWrapper> deviceGroupWrappers = policy.getDeviceGroups();
    int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();

    try {
        conn = this.getConnection();
        String query = "INSERT INTO DM_DEVICE_GROUP_POLICY (DEVICE_GROUP_ID, POLICY_ID, TENANT_ID) VALUES (?, ?, ?)";
        stmt = conn.prepareStatement(query);
        for (DeviceGroupWrapper wrapper : deviceGroupWrappers) {
            stmt.setInt(1, wrapper.getId());
            stmt.setInt(2, policy.getId());
            stmt.setInt(3, tenantId);
            stmt.addBatch();
        }
        stmt.executeBatch();

    } catch (SQLException e) {
        throw new PolicyManagerDAOException("Error occurred while adding the device group details to the policy.", e);
    } finally {
        PolicyManagementDAOUtil.cleanupResources(stmt, null);
    }
}
 
Example #30
Source File: CommonConfigDeployerTestCase.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Test
    public void testCreatedConfigurationContextRuntimeException() throws APIManagementException {
        System.setProperty(CARBON_HOME, "");
        PowerMockito.mockStatic(CommonUtil.class);
        PrivilegedCarbonContext privilegedCarbonContext = Mockito.mock(PrivilegedCarbonContext.class);
        PowerMockito.mockStatic(PrivilegedCarbonContext.class);
        PowerMockito.when(PrivilegedCarbonContext.getThreadLocalCarbonContext()).thenReturn(privilegedCarbonContext);
        Mockito.when(privilegedCarbonContext.getTenantDomain()).thenReturn(TENANT_DOMAIN);
        Mockito.when(privilegedCarbonContext.getTenantId()).thenReturn(TENANT_ID);

        ServiceReferenceHolder serviceReferenceHolder = Mockito.mock(ServiceReferenceHolder.class);
        PowerMockito.mockStatic(ServiceReferenceHolder.class);
        PowerMockito.when(ServiceReferenceHolder.getInstance()).thenReturn(serviceReferenceHolder);
        RegistryService registryService = Mockito.mock(RegistryService.class);
        Mockito.when(ServiceReferenceHolder.getInstance().getRegistryService()).thenReturn(registryService);

        APIManagerConfigurationService apiManagerConfigurationService = Mockito
                .mock(APIManagerConfigurationService.class);
        Mockito.when(serviceReferenceHolder.getAPIManagerConfigurationService())
                .thenReturn(apiManagerConfigurationService);

        APIManagerConfiguration apiManagerConfiguration = Mockito.mock(APIManagerConfiguration.class);
        Mockito.when(apiManagerConfigurationService.getAPIManagerConfiguration()).thenReturn(apiManagerConfiguration);
        Mockito.when(apiManagerConfiguration.getFirstProperty(APIConstants.API_GATEWAY_TYPE))
                .thenReturn(APIConstants.API_GATEWAY_TYPE_SYNAPSE);

        ConfigurationContext configurationContext = Mockito.mock(ConfigurationContext.class);
        PowerMockito.mockStatic(APIUtil.class);

//        Mockito.doThrow(new RuntimeException("error")).when(APIUtil.loadTenantConf(TENANT_ID));
        PowerMockito.doThrow(new RuntimeException("error")).when(APIUtil.class);
        APIUtil.createDefaultRoles(TENANT_ID);
        CommonConfigDeployer commonConfigDeployer = new CommonConfigDeployer();
        commonConfigDeployer.createdConfigurationContext(configurationContext);

        PowerMockito.verifyStatic(APIUtil.class, Mockito.times(1));
        APIUtil.createDefaultRoles(TENANT_ID);
    }