Java Code Examples for org.wso2.carbon.registry.core.Registry#put()

The following examples show how to use org.wso2.carbon.registry.core.Registry#put() . 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: SecurityMgtServiceComponent.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
private void addKeystores() throws RegistryException {
    Registry registry = SecurityServiceHolder.getRegistryService().getGovernanceSystemRegistry();
    try {
        boolean transactionStarted = Transaction.isStarted();
        if (!transactionStarted) {
            registry.beginTransaction();
        }
        if (!registry.resourceExists(SecurityConstants.KEY_STORES)) {
            Collection kstores = registry.newCollection();
            registry.put(SecurityConstants.KEY_STORES, kstores);

            Resource primResource = registry.newResource();
            if (!registry.resourceExists(RegistryResources.SecurityManagement.PRIMARY_KEYSTORE_PHANTOM_RESOURCE)) {
                registry.put(RegistryResources.SecurityManagement.PRIMARY_KEYSTORE_PHANTOM_RESOURCE,
                        primResource);
            }
        }
        if (!transactionStarted) {
            registry.commitTransaction();
        }
    } catch (Exception e) {
        registry.rollbackTransaction();
        throw e;
    }
}
 
Example 2
Source File: RegistryResourceMgtServiceImpl.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
@Override
public void putIdentityResource(Resource identityResource,
                                String path,
                                String tenantDomain) throws IdentityRuntimeException {
    startTenantFlow(tenantDomain);
    try {
        Registry registry = getRegistryForTenant(tenantDomain);
        registry.put(path, identityResource);
        if (log.isDebugEnabled()) {
            log.debug(String.format(MSG_RESOURCE_PERSIST, path, tenantDomain));
        }
    } catch (RegistryException e) {
        String errorMsg = String.format(ERROR_PERSIST_RESOURCE, tenantDomain, path);
        throw IdentityRuntimeException.error(errorMsg, e);
    } finally {
        PrivilegedCarbonContext.endTenantFlow();
    }
}
 
Example 3
Source File: JWTClientUtil.java    From carbon-device-mgt with Apache License 2.0 6 votes vote down vote up
/**
 * Get the jwt details from the registry for tenants.
 *
 * @param tenantId for accesing tenant space.
 * @return the config for tenant
 * @throws RegistryException
 */
public static void addJWTConfigResourceToRegistry(int tenantId, String content)
		throws RegistryException {
	try {
		PrivilegedCarbonContext.startTenantFlow();
		PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(tenantId, true);
		RegistryService registryService = JWTClientExtensionDataHolder.getInstance().getRegistryService();
		if (registryService != null) {
			Registry registry = registryService.getConfigSystemRegistry(tenantId);
			JWTClientUtil.loadTenantRegistry(tenantId);
			if (!registry.resourceExists(TENANT_JWT_CONFIG_LOCATION)) {
				Resource resource = registry.newResource();
				resource.setContent(content.getBytes());
				registry.put(TENANT_JWT_CONFIG_LOCATION, resource);
			}
		}
	} finally {
		PrivilegedCarbonContext.endTenantFlow();
	}
}
 
Example 4
Source File: RegistryBasedTrustedServiceStore.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
/**
 * Add a trusted service to which tokens are issued with given claims.
 *
 * @param realmName    - this uniquely represents the trusted service
 * @param claimDialect - claim dialects uris
 * @param claims       - these comma separated default claims are issued when a request is done from the given realm
 * @throws Exception - if fails to add trusted service
 */
public void addTrustedService(String realmName, String claimDialect, String claims)
        throws Exception {
    realmName = replaceSlashWithConstantString(realmName);
    try {
        Registry registry = IdentityPassiveSTSServiceComponent.getConfigSystemRegistry();
        String trustedServicePath = registryTrustedServicePath + realmName;
        // if registry collection does not exists, create
        if (!registry.resourceExists(trustedServicePath)) {
            Resource resource = registry.newResource();
            resource.addProperty(REALM_NAME, realmName);
            resource.addProperty(CLAIMS, claims);
            resource.addProperty(CLAIM_DIALECT, claimDialect);
            registry.put(trustedServicePath, resource);
        } else {
            throw new Exception(realmName + " already added. Please remove first and add again.");
        }
    } catch (RegistryException e) {
        String error = "Error occurred when adding a trusted service due to error in accessing registry.";
        throw new Exception(error, e);
    }
}
 
Example 5
Source File: ApplicationManagementServiceImpl.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
/**
 * Remove trusted service
 *
 * @param groupName      Group name
 * @param serviceName    Service name
 * @param trustedService Trusted service name
 * @throws org.wso2.carbon.registry.api.RegistryException
 */
private void removeTrustedService(String groupName, String serviceName,
                                  String trustedService) throws RegistryException {

    String resourcePath = RegistryResources.SERVICE_GROUPS + groupName +
                RegistryResources.SERVICES + serviceName + "/trustedServices";
    Registry registry = getConfigSystemRegistry();
    if (registry != null) {
        if (registry.resourceExists(resourcePath)) {
            Resource resource = registry.get(resourcePath);
            if (resource.getProperty(trustedService) != null) {
                resource.removeProperty(trustedService);
            }
            registry.put(resourcePath, resource);
        }
    }
}
 
Example 6
Source File: SecurityDeploymentInterceptor.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
private void addKeystores() throws RegistryException {
    Registry registry = SecurityServiceHolder.getRegistryService().getGovernanceSystemRegistry();
    try {
        boolean transactionStarted = Transaction.isStarted();
        if (!transactionStarted) {
            registry.beginTransaction();
        }
        if (!registry.resourceExists(SecurityConstants.KEY_STORES)) {
            Collection kstores = registry.newCollection();
            registry.put(SecurityConstants.KEY_STORES, kstores);

            Resource primResource = registry.newResource();
            if (!registry.resourceExists(RegistryResources.SecurityManagement.PRIMARY_KEYSTORE_PHANTOM_RESOURCE)) {
                registry.put(RegistryResources.SecurityManagement.PRIMARY_KEYSTORE_PHANTOM_RESOURCE,
                        primResource);
            }
        }
        if (!transactionStarted) {
            registry.commitTransaction();
        }
    } catch (Exception e) {
        registry.rollbackTransaction();
        throw e;
    }
}
 
Example 7
Source File: ProviderMigrationClient.java    From product-es with Apache License 2.0 5 votes vote down vote up
private void migrateProvider(Collection root, Registry registry)
        throws RegistryException, SAXException, TransformerException, ParserConfigurationException, IOException {
    String[] childrenPaths = root.getChildren();
    for (String child : childrenPaths) {
        Resource childResource = registry.get(child);
        if (childResource instanceof Collection) {
            migrateProvider((Collection) childResource, registry);
        } else {
            String path = childResource.getPath();
            byte[] configContent = (byte[]) childResource.getContent();
            String contentString = RegistryUtils.decodeBytes(configContent);
            Document dom = stringToDocument(contentString);
            if (dom.getElementsByTagName(Constants.OVERVIEW).getLength() > 0) {
                Node overview = dom.getElementsByTagName(Constants.OVERVIEW).item(0);
                NodeList childrenList = overview.getChildNodes();
                for (int j = 0; j < childrenList.getLength(); j++) {
                    Node node = childrenList.item(j);
                    if (Constants.PROVIDER.equals(node.getNodeName())) {
                        overview.removeChild(node);
                    }
                }
                String newContentString = documentToString(dom);
                byte[] newContentObject = RegistryUtils.encodeString(newContentString);
                childResource.setContent(newContentObject);
                registry.put(path, childResource);
            }
        }
    }
}
 
Example 8
Source File: DefaultPolicyDataStore.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
@Override
public void setPolicyData(String policyId, PolicyStoreDTO policyDataDTO) throws EntitlementException {

    Registry registry = getGovernanceRegistry();
    try {
        String path = policyDataCollection + policyId;
        Resource resource;
        if (registry.resourceExists(path)) {
            resource = registry.get(path);
        } else {
            resource = registry.newCollection();
        }

        if (policyDataDTO.isSetActive()) {
            resource.setProperty("active", Boolean.toString(policyDataDTO.isActive()));
        }
        if (policyDataDTO.isSetOrder()) {
            int order = policyDataDTO.getPolicyOrder();
            if (order > 0) {
                resource.setProperty("order", Integer.toString(order));
            }
        }
        registry.put(path, resource);
    } catch (RegistryException e) {
        log.error("Error while updating Policy data in policy store ", e);
        throw new EntitlementException("Error while updating Policy data in policy store");
    }
}
 
Example 9
Source File: MetadataApiRegistry.java    From attic-stratos with Apache License 2.0 5 votes vote down vote up
public boolean removePropertyValueFromApplication(String applicationId, String propertyKey, String valueToRemove)
        throws RegistryException, MetadataException {
    Registry registry = getRegistry();
    String resourcePath = mainResource + applicationId;

    try {
        acquireWriteLock(applicationId);
        // We are using only super tenant registry to persist
        PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
        ctx.setTenantId(MultitenantConstants.SUPER_TENANT_ID);
        ctx.setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
        Resource nodeResource;
        if (registry.resourceExists(resourcePath)) {
            nodeResource = registry.get(resourcePath);
        } else {
            log.warn(String.format("Registry property not found: [resource-path] %s, [key] %s", resourcePath,
                    propertyKey));
            return false;
        }
        nodeResource.removePropertyValue(propertyKey, valueToRemove);
        registry.put(resourcePath, nodeResource);
        log.info(
                String.format("Registry property removed: [application-id] %s, [key] %s, [value] %s", applicationId,
                        propertyKey, valueToRemove));
        return true;
    } catch (Exception e) {
        throw new MetadataException(
                String.format("Could not remove registry resource: [resource-path] %s, [key] %s, [value] %s",
                        resourcePath, propertyKey, valueToRemove), e);
    } finally {
        try {
            releaseWriteLock(applicationId);
        } catch (MetadataException ignored) {
        }
    }
}
 
Example 10
Source File: RegistryManager.java    From attic-stratos with Apache License 2.0 5 votes vote down vote up
/**
 * Persist a serializable object in the registry with the given resource path.
 *
 * @param object object to be persisted.
 */
@Override
public synchronized void persist(String resourcePath, Object object) throws RegistryException {
    if (log.isDebugEnabled()) {
        log.debug(String.format("Persisting resource in registry: [resource-path] %s", resourcePath));
    }

    Registry registry = getRegistry();

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

        registry.beginTransaction();

        Resource nodeResource = registry.newResource();
        nodeResource.setContent(serializeToByteArray(object));
        registry.put(resourcePath, nodeResource);

        registry.commitTransaction();

        if (log.isDebugEnabled()) {
            log.debug(String.format("Resource persisted successfully in registry: [resource-path] %s",
                    resourcePath));
        }
    } catch (Exception e) {
        try {
            registry.rollbackTransaction();
        } catch (RegistryException e1) {
            if (log.isErrorEnabled()) {
                log.error("Could not rollback transaction", e1);
            }
        }
        throw new RegistryException("Failed to persist resource in registry: [resource-path] " + resourcePath, e);
    }
}
 
Example 11
Source File: DeviceTypeUtils.java    From carbon-device-mgt with Apache License 2.0 5 votes vote down vote up
public static boolean putRegistryResource(String path, Resource resource) throws DeviceTypeMgtPluginException {
    try {
        Registry registry = getConfigurationRegistry();
        registry.beginTransaction();
        registry.put(path, resource);
        registry.commitTransaction();
        return true;
    } catch (RegistryException e) {
        throw new DeviceTypeMgtPluginException(
                "Error occurred while persisting registry resource : " + e.getMessage(), e);
    }
}
 
Example 12
Source File: AbstractMetaDataHandler.java    From carbon-commons with Apache License 2.0 5 votes vote down vote up
public void saveMetadata
        () throws ReportingException {
    try {
        RegistryService registryService = ReportingTemplateComponent.getRegistryService();
        Registry registry = registryService.getConfigSystemRegistry();
        registry.beginTransaction();
        Resource reportFilesResource = registry.newResource();
        reportFilesResource.setContent(reportsElement.toString());
        String location = ReportConstants.REPORT_META_DATA_PATH + ReportConstants.METADATA_FILE_NAME;
        registry.put(location, reportFilesResource);
        registry.commitTransaction();
    } catch (RegistryException e) {
        throw new ReportingException("Exception occured in loading the meta-data of reports", e);
    }
}
 
Example 13
Source File: STSAdminServiceImpl.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
private void persistTrustedService(String groupName, String serviceName, String trustedService,
                                   String certAlias) throws SecurityConfigException {
    Registry registry;
    String resourcePath;
    Resource resource;
    try {
        resourcePath = RegistryResources.SERVICE_GROUPS + groupName
                + RegistryResources.SERVICES + serviceName + "/trustedServices";
        registry = getConfigSystemRegistry(); //TODO: Multitenancy
        if (registry != null) {
            if (registry.resourceExists(resourcePath)) {
                resource = registry.get(resourcePath);
            } else {
                resource = registry.newResource();
            }
            if (resource.getProperty(trustedService) != null) {
                resource.removeProperty(trustedService);
            }
            resource.addProperty(trustedService, certAlias);
            registry.put(resourcePath, resource);
        }
    } catch (Exception e) {
        log.error("Error occured while adding trusted service for STS", e);
        throw new SecurityConfigException("Error occured while adding trusted service for STS",
                e);
    }
}
 
Example 14
Source File: MigrateData.java    From product-es with Apache License 2.0 5 votes vote down vote up
private void updateResource(Registry registry, String path) throws RegistryException {
    if (registry.resourceExists(path)) {
        Resource resource = registry.get(path);
        String content = new String((byte[]) resource.getContent());
        if (content.contains(Constants.LOGIN_SCRIPT)) {
            content = content.replace(Constants.LOGIN_PERMISSION, "");
            content = content.replace(Constants.PERMISSION_ACTION, "");
            resource.setContent(content);
            registry.put(path, resource);
        }

    }
}
 
Example 15
Source File: MetadataApiRegistry.java    From attic-stratos with Apache License 2.0 4 votes vote down vote up
public boolean removePropertyFromApplication(String applicationId, String propertyKey)
        throws RegistryException, MetadataException {
    Registry registry = getRegistry();
    String resourcePath = mainResource + applicationId;
    Resource nodeResource;

    try {
        acquireWriteLock(applicationId);
        // We are using only super tenant registry to persist
        PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
        ctx.setTenantId(MultitenantConstants.SUPER_TENANT_ID);
        ctx.setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
        if (registry.resourceExists(resourcePath)) {
            nodeResource = registry.get(resourcePath);
            if (nodeResource.getProperty(propertyKey) == null) {
                log.info(String.format("Registry property not found: [application-id] %s [key] %s ", applicationId,
                        propertyKey));
                return false;
            } else {
                nodeResource.removeProperty(propertyKey);
                registry.put(resourcePath, nodeResource);
            }
        } else {
            log.error("Registry resource not not found at " + resourcePath);
            return false;
        }

        log.info(String.format("Registry property removed: [application-id] %s, [key] %s", applicationId,
                propertyKey));
        return true;
    } catch (Exception e) {
        throw new MetadataException(
                String.format("Could not remove registry resource: [resource-path] %s, [key] %s", resourcePath,
                        propertyKey), e);
    } finally {
        try {
            releaseWriteLock(applicationId);
        } catch (MetadataException ignored) {
        }
    }
}
 
Example 16
Source File: SecurityDeploymentInterceptor.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
private void loadSecurityScenarios(Registry registry,
                                   BundleContext bundleContext) throws CarbonException, IOException, RegistryException {

    // TODO: Load into all tenant DBs
    // Load security scenarios
    URL resource = bundleContext.getBundle().getResource("/scenarios/scenario-config.xml");
    XmlConfiguration xmlConfiguration = new XmlConfiguration(resource.openStream(),
            SecurityConstants.SECURITY_NAMESPACE);

    OMElement[] elements = xmlConfiguration.getElements("//ns:Scenario");
    try {
        boolean transactionStarted = Transaction.isStarted();
        if (!transactionStarted) {
            registry.beginTransaction();
        }

        for (OMElement scenarioEle : elements) {
            SecurityScenario scenario = new SecurityScenario();
            String scenarioId = scenarioEle.getAttribute(SecurityConstants.ID_QN)
                    .getAttributeValue();

            scenario.setScenarioId(scenarioId);
            scenario.setSummary(scenarioEle.getFirstChildWithName(SecurityConstants.SUMMARY_QN)
                    .getText());
            scenario.setDescription(scenarioEle.getFirstChildWithName(
                    SecurityConstants.DESCRIPTION_QN).getText());
            scenario.setCategory(scenarioEle.getFirstChildWithName(SecurityConstants.CATEGORY_QN)
                    .getText());
            scenario.setWsuId(scenarioEle.getFirstChildWithName(SecurityConstants.WSUID_QN)
                    .getText());
            scenario.setType(scenarioEle.getFirstChildWithName(SecurityConstants.TYPE_QN).getText());

            String resourceUri = SecurityConstants.SECURITY_POLICY + "/" + scenarioId;

            for (Iterator modules = scenarioEle.getFirstChildWithName(SecurityConstants.MODULES_QN)
                    .getChildElements(); modules.hasNext(); ) {
                String module = ((OMElement) modules.next()).getText();
                scenario.addModule(module);
            }

            // Save it in the DB
            SecurityScenarioDatabase.put(scenarioId, scenario);

            // Store the scenario in the Registry
            if (!scenarioId.equals(SecurityConstants.SCENARIO_DISABLE_SECURITY) &&
                    !scenarioId.equals(SecurityConstants.POLICY_FROM_REG_SCENARIO)) {
                Resource scenarioResource = new ResourceImpl();
                scenarioResource.
                        setContentStream(bundleContext.getBundle().
                                getResource("scenarios/" + scenarioId + "-policy.xml").openStream());
                scenarioResource.setMediaType("application/policy+xml");
                if (!registry.resourceExists(resourceUri)) {
                    registry.put(resourceUri, scenarioResource);
                }

                // Cache the resource in-memory in order to add it to the newly created tenants
                SecurityServiceHolder.addPolicyResource(resourceUri, scenarioResource);
            }
        }
        if (!transactionStarted) {
            registry.commitTransaction();
        }
    } catch (Exception e) {
        registry.rollbackTransaction();
        throw e;
    }
}
 
Example 17
Source File: IdentitySTSMgtServiceComponent.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
/**
 * This method is used to load custom security scenarios used inside Identity STS componsnts.
 *
 * @throws Exception
 */
private void loadSecurityScenarios() throws Exception {

    Registry registry = registryService.getConfigSystemRegistry();

    try {
        // Scenarios are listed in resources/scenario-config.xml
        URL resource = bundleContext.getBundle().getResource("scenario-config.xml");
        XmlConfiguration xmlConfiguration = new XmlConfiguration(resource.openStream(),
                                                                 SecurityConstants.SECURITY_NAMESPACE);

        OMElement[] elements = xmlConfiguration.getElements("//ns:Scenario");

        boolean transactionStarted = Transaction.isStarted();
        if (!transactionStarted) {
            registry.beginTransaction();
        }

        for (OMElement scenarioEle : elements) {
            SecurityScenario scenario = new SecurityScenario();
            String scenarioId = scenarioEle.getAttribute(SecurityConstants.ID_QN).getAttributeValue();

            scenario.setScenarioId(scenarioId);
            scenario.setSummary(scenarioEle.getFirstChildWithName(SecurityConstants.SUMMARY_QN).getText());
            scenario.setDescription(scenarioEle.getFirstChildWithName(SecurityConstants.DESCRIPTION_QN).getText());
            scenario.setCategory(scenarioEle.getFirstChildWithName(SecurityConstants.CATEGORY_QN).getText());
            scenario.setWsuId(scenarioEle.getFirstChildWithName(SecurityConstants.WSUID_QN).getText());
            scenario.setType(scenarioEle.getFirstChildWithName(SecurityConstants.TYPE_QN).getText());

            OMElement genPolicyElem = scenarioEle.getFirstChildWithName(SecurityConstants.IS_GEN_POLICY_QN);
            if (genPolicyElem != null && "false".equals(genPolicyElem.getText())) {
                scenario.setGeneralPolicy(false);
            }

            String resourceUri = SecurityConstants.SECURITY_POLICY + "/" + scenarioId;

            for (Iterator modules = scenarioEle.getFirstChildWithName(SecurityConstants.MODULES_QN)
                                               .getChildElements(); modules.hasNext(); ) {
                String module = ((OMElement) modules.next()).getText();
                scenario.addModule(module);
            }

            // Save it in the DB
            SecurityScenarioDatabase.put(scenarioId, scenario);

            // Store the scenario in the Registry
            if (!scenarioId.equals(SecurityConstants.SCENARIO_DISABLE_SECURITY) &&
                !scenarioId.equals(SecurityConstants.POLICY_FROM_REG_SCENARIO)) {
                Resource scenarioResource = new ResourceImpl();
                scenarioResource.setContentStream(
                        bundleContext.getBundle().getResource(scenarioId + "-policy.xml").openStream());
                if (!registry.resourceExists(resourceUri)) {
                    registry.put(resourceUri, scenarioResource);
                }
            }

        }
        if (!transactionStarted) {
            registry.commitTransaction();
        }
    } catch (Exception e) {
        registry.rollbackTransaction();
        throw e;
    }
}
 
Example 18
Source File: JRxmlFileBundleListener.java    From carbon-commons with Apache License 2.0 4 votes vote down vote up
/**
 * used to add .jrxml files to registry at bundle deployment time
 *
 * @param bundle Bundle
 * @throws ReportingException error occurred adding .jrxml file to registry
 */
public void addJrXmlToRegistry(Bundle bundle) throws ReportingException {

    BundleContext bundleContext = bundle.getBundleContext();
    String reportResource = "/reports/";
    Enumeration enumeration = bundleContext.getBundle().getEntryPaths(reportResource);
    if (enumeration == null) {
        return;
    }
    try {
        RegistryService registryService = ReportingComponent.getRegistryService();
        Registry registry = registryService.getConfigSystemRegistry();
        registry.beginTransaction();
        Resource reportFilesResource = registry.newResource();
        InputStream xmlStream = null;
        try{
        while (enumeration.hasMoreElements()) {
            String path = enumeration.nextElement().toString();
            URL url = bundleContext.getBundle().getResource(path);
            if (url == null) {
                return;
            }
             xmlStream = url.openStream();
            if (xmlStream == null) {
                return;
            }
            reportFilesResource.setContentStream(xmlStream);
            String location = ReportConstants.REPORT_BASE_PATH + bundle.getSymbolicName() + "/" + path.split("/")[1];
            if (!registry.resourceExists(location)) {
                registry.put(location, reportFilesResource);
            }
        }
        }finally {
          xmlStream.close();
        }
        registry.commitTransaction();
    } catch (Exception e) {
        String msg = "Error occurred adding .jrxml file from " +
                bundle.getSymbolicName() + " to registry";
        throw new ReportingException(msg, e);
    }

}
 
Example 19
Source File: RegistryDataManager.java    From product-ei with Apache License 2.0 4 votes vote down vote up
/**
 * Encrypt the security policy password by new algorithm and update
 *
 * @param tenantId
 * @throws RegistryException
 * @throws CryptoException
 * @throws XMLStreamException
 */
private void updateSecurityPolicyPassword(int tenantId) throws RegistryException, CryptoException,
        XMLStreamException {
    InputStream resourceContent = null;
    XMLStreamReader parser = null;
    try {
        Registry registry = MigrationServiceDataHolder.getRegistryService().getConfigSystemRegistry(tenantId);
        List<String> policyPaths = getSTSPolicyPaths(registry);
        String newEncryptedPassword = null;
        for (String resourcePath : policyPaths) {
            if (registry.resourceExists(resourcePath)) {
                Resource resource = registry.get(resourcePath);
                resourceContent = resource.getContentStream();
                parser = XMLInputFactory.newInstance().createXMLStreamReader(resourceContent);
                StAXOMBuilder builder = new StAXOMBuilder(parser);
                OMElement documentElement = builder.getDocumentElement();
                Iterator it = documentElement.getChildrenWithName(new QName(Constant.CARBON_SEC_CONFIG));

                while (it != null && it.hasNext()) {
                    OMElement secConfig = (OMElement) it.next();
                    Iterator kerberosProperties = secConfig.getChildrenWithName(new QName(Constant.KERBEROS));
                    Iterator propertySet = null;
                    if ((kerberosProperties != null && kerberosProperties.hasNext())) {
                        propertySet = ((OMElement) kerberosProperties.next()).getChildElements();
                    }
                    if (propertySet != null) {
                        while (propertySet.hasNext()) {
                            OMElement kbProperty = (OMElement) propertySet.next();
                            if (Constant.SERVICE_PRINCIPAL_PASSWORD
                                    .equals(kbProperty.getAttributeValue(Constant.NAME_Q))) {
                                String encryptedPassword = kbProperty.getText();
                                newEncryptedPassword = Utility.getNewEncryptedValue(encryptedPassword);
                                if (StringUtils.isNotEmpty(newEncryptedPassword)) {
                                    kbProperty.setText(newEncryptedPassword);
                                }
                            }
                        }
                    }
                }
                if (StringUtils.isNotEmpty(newEncryptedPassword)) {
                    resource.setContent(RegistryUtils.encodeString(documentElement.toString()));
                    registry.beginTransaction();
                    registry.put(resourcePath, resource);
                    registry.commitTransaction();
                }
            }
        }
    } finally {
        try {
            if (parser != null) {
                parser.close();
            }
            if (resourceContent != null) {
                try {
                    resourceContent.close();
                } catch (IOException e) {
                    log.error("Error occurred while closing Input stream", e);
                }
            }
        } catch (XMLStreamException ex) {
            log.error("Error while closing XML stream", ex);
        }
    }

}
 
Example 20
Source File: ManagementPermissionsAdder.java    From carbon-identity-framework with Apache License 2.0 4 votes vote down vote up
public void addUIPermissionFromBundle(Bundle bundle) throws Exception {
    BundleContext bundleContext = bundle.getBundleContext();
    if (bundleContext == null) { // If the bundle got uninstalled, the bundleContext will be null
        return;
    }

    URL url = bundleContext.getBundle().getEntry("META-INF/component.xml");
    if (url == null) {
        return;
    }

    InputStream xmlStream = url.openStream();
    if (xmlStream == null) {
        return;
    }

    if (log.isDebugEnabled()) {
        log.debug("Adding permissions in bundle" + 
                bundle.getSymbolicName());
    }

    Component component = ComponentConfigFactory.build(xmlStream);
    ManagementPermission[] uiPermissions = null;
    if (component != null) {
        uiPermissions = (ManagementPermission[]) component
                .getComponentConfig(ManagementPermissionsBuilder.LOCALNAME_MGT_PERMISSIONS);
    }

    if (uiPermissions != null) {
        // at the starup we are only adding permission only to tenant 0
        Registry registry = UserMgtDSComponent.getRegistryService().getGovernanceSystemRegistry();
        for (ManagementPermission uiPermission : uiPermissions) {
            if (registry.resourceExists(uiPermission.getResourceId())) {
                Resource existingResource = registry.get(uiPermission.getResourceId());
                if (existingResource.getProperty(UserMgtConstants.DISPLAY_NAME) == null) {
                    existingResource.setProperty(UserMgtConstants.DISPLAY_NAME, uiPermission.getDisplayName());
                    registry.put(uiPermission.getResourceId(), existingResource);
                }
                continue;
            }
            Collection resource = registry.newCollection();
            resource.setProperty(UserMgtConstants.DISPLAY_NAME, uiPermission.getDisplayName());
            registry.put(uiPermission.getResourceId(), resource);
        }
    }
}