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

The following examples show how to use org.wso2.carbon.registry.core.Registry#resourceExists() . 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: DefaultPolicyDataStore.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
@Override
public String getGlobalPolicyAlgorithmName() {

    Registry registry = EntitlementServiceComponent.
            getGovernanceRegistry(CarbonContext.getThreadLocalCarbonContext().getTenantId());
    String algorithm = null;
    try {

        if (registry.resourceExists(policyDataCollection)) {
            Collection collection = (Collection) registry.get(policyDataCollection);
            algorithm = collection.getProperty("globalPolicyCombiningAlgorithm");
        }
    } catch (RegistryException e) {
        if (log.isDebugEnabled()) {
            log.debug(e);
        }
    }

    // set default
    if (algorithm == null) {
        algorithm = "deny-overrides";
    }

    return algorithm;
}
 
Example 2
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 3
Source File: RegistryPolicyStoreManageModule.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
@Override
public boolean isPolicyExist(String policyId) {

    Registry registry;
    String policyPath;
    int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();

    if (policyId == null || policyId.trim().length() == 0) {
        return false;
    }

    try {
        registry = EntitlementServiceComponent.getRegistryService().
                getGovernanceSystemRegistry(tenantId);

        policyPath = policyStorePath + policyId;
        return registry.resourceExists(policyPath);
    } catch (RegistryException e) {
        //ignore
        return false;
    }
}
 
Example 4
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 5
Source File: DefaultPolicyDataStore.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
@Override
public PolicyStoreDTO getPolicyData(String policyId) {

    Registry registry = EntitlementServiceComponent.
            getGovernanceRegistry(CarbonContext.getThreadLocalCarbonContext().getTenantId());
    PolicyStoreDTO dataDTO = new PolicyStoreDTO();
    try {
        String path = policyDataCollection + policyId;
        if (registry.resourceExists(path)) {
            Resource resource = registry.get(path);
            String order = resource.getProperty("order");
            String active = resource.getProperty("active");
            if (order != null && order.trim().length() > 0) {
                dataDTO.setPolicyOrder(Integer.parseInt(order));
            }
            dataDTO.setActive(Boolean.parseBoolean(active));
        }
    } catch (RegistryException e) {
        if (log.isDebugEnabled()) {
            log.debug(e);
        }
    }
    return dataDTO;
}
 
Example 6
Source File: APIMRegistryServiceImpl.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Override
public String getGovernanceRegistryResourceContent(String tenantDomain, String registryLocation)
                                    throws UserStoreException, RegistryException {
    String content = null;
    if (tenantDomain == null) {
        tenantDomain = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
    }

    try {
        PrivilegedCarbonContext.startTenantFlow();
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);

        int tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager().getTenantId(tenantDomain);
        Registry registry = ServiceReferenceHolder.getInstance().getRegistryService().getGovernanceSystemRegistry(tenantId);

        if (registry.resourceExists(registryLocation)) {
            Resource resource = registry.get(registryLocation);
            content = getString(resource);
        }
    }
    finally {
        PrivilegedCarbonContext.endTenantFlow();
    }

    return content;
}
 
Example 7
Source File: RegistryDataManager.java    From product-ei with Apache License 2.0 6 votes vote down vote up
/**
 * Encrypt the registry properties by new algorithm and update
 *
 * @param registry
 * @param resource
 * @param properties
 * @throws RegistryException
 * @throws CryptoException
 */
private void updateRegistryProperties(Registry registry, String resource, List<String> properties)
        throws RegistryException, CryptoException {
    if (registry == null || StringUtils.isEmpty(resource) || CollectionUtils.isEmpty(properties)) {
        return;
    }
    if (registry.resourceExists(resource)) {
        try {
            registry.beginTransaction();
            Resource resourceObj = registry.get(resource);
            for (String encryptedPropertyName : properties) {
                String oldValue = resourceObj.getProperty(encryptedPropertyName);
                String newValue = Utility.getNewEncryptedValue(oldValue);
                if (StringUtils.isNotEmpty(newValue)) {
                    resourceObj.setProperty(encryptedPropertyName, newValue);
                }
            }
            registry.put(resource, resourceObj);
            registry.commitTransaction();
        } catch (RegistryException e) {
            registry.rollbackTransaction();
            log.error("Unable to update the registry resource", e);
            throw e;
        }
    }
}
 
Example 8
Source File: RegistryBasedTrustedServiceStore.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
/**
 * Remove the given trusted service with realmName
 *
 * @param realmName - the realm of the service
 * @throws Exception
 */
public void removeTrustedService(String realmName) throws Exception {
    realmName = replaceSlashWithConstantString(realmName);
    try {
        Registry registry = IdentityPassiveSTSServiceComponent.getConfigSystemRegistry();
        String trustedServicePath = registryTrustedServicePath + realmName;
        if (registry.resourceExists(trustedServicePath)) {
            registry.delete(trustedServicePath);
        } else {
            throw new Exception(realmName + " ,No such trusted service exists to delete.");
        }

    } catch (RegistryException e) {
        String error = "Error occurred when removing a trusted service due to error in accessing registry.";
        throw new Exception(error, e);
    }
}
 
Example 9
Source File: DefaultPolicyDataStore.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
@Override
public void removePolicyData(String policyId) throws EntitlementException {

    Registry registry = getGovernanceRegistry();
    try {
        String path = policyDataCollection + policyId;
        if (registry.resourceExists(path)) {
            registry.delete(path);
        }
    } catch (RegistryException e) {
        log.error("Error while deleting Policy data in policy store ", e);
        throw new EntitlementException("Error while deleting Policy data in policy store");
    }

}
 
Example 10
Source File: APIMRegistryServiceImpl.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Override
public String getConfigRegistryResourceContent(String tenantDomain, final String registryLocation)
                                    throws UserStoreException, RegistryException {
    String content = null;
    if (tenantDomain == null) {
        tenantDomain = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
    }

    try {
        PrivilegedCarbonContext.startTenantFlow();
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);

        int tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager().getTenantId(tenantDomain);
        Registry registry = ServiceReferenceHolder.getInstance().getRegistryService().getConfigSystemRegistry(tenantId);
        APIUtil.loadTenantRegistry(tenantId);
        if (!MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
            APIUtil.loadTenantConf(tenantId);
        }

        if (registry.resourceExists(registryLocation)) {
            Resource resource = registry.get(registryLocation);
            content = getString(resource);
        }
    } catch (APIManagementException e) {
        log.error("Error occurred while loading tenant configuration for '" + tenantDomain + "'");

    } finally {
        PrivilegedCarbonContext.endTenantFlow();
    }

    return content;
}
 
Example 11
Source File: EmailUserNameMigrationClient.java    From product-es with Apache License 2.0 5 votes vote down vote up
/**
 * This method replaces artifacts containing email username with ':' to '-at-'.
 * This will replace the storage path and resource content which contains overview_provider attribute with emailusername.
 *
 * @param artifacts artifacts of a particular rxt type. with overview-provider attribute in the storage path.
 * @param registry registry instance
 * @throws RegistryException
 * @throws javax.xml.stream.XMLStreamException
 */
private static void migrateArtifactsWithEmailUserName(GenericArtifact[] artifacts, Registry registry)
        throws RegistryException, XMLStreamException {
    for (GenericArtifact artifact : artifacts) {
        boolean isProviderMetadataUpdated = false;
        String relativePath = artifact.getPath();
        if (registry.resourceExists(relativePath)) {
            Resource resource = registry.get(relativePath);
            String metadataString = RegistryUtils.decodeBytes((byte[]) resource.getContent());
            OMElement metadataOM = AXIOMUtil.stringToOM(metadataString);
            OMElement overview = metadataOM.getFirstChildWithName(new QName(Constants.METADATA_NAMESPACE,
                                                                            Constants.OVERVIEW));
            OMElement providerElement = overview.getFirstChildWithName(new QName(Constants.METADATA_NAMESPACE,
                                                                                 Constants.PROVIDER));
            if (providerElement != null && providerElement.getText().contains(Constants.OLD_EMAIL_AT_SIGN)) {
                String oldProviderName = providerElement.getText();
                String newProviderName = oldProviderName.replace(Constants.OLD_EMAIL_AT_SIGN,
                                                                 Constants.NEW_EMAIL_AT_SIGN);
                providerElement.setText(newProviderName);
                resource.setContent(metadataOM.toStringWithConsume());
                isProviderMetadataUpdated = true;
            }
            String newPath = null;
            if (relativePath.contains(Constants.OLD_EMAIL_AT_SIGN)) {
                newPath = relativePath.replace(Constants.OLD_EMAIL_AT_SIGN,
                                               Constants.NEW_EMAIL_AT_SIGN);//TODO:replaceALL
                registry.move(relativePath, newPath);
                registry.put(newPath, resource);
            } else if (relativePath.contains(Constants.NEW_EMAIL_AT_SIGN)) {
                newPath = relativePath;
                if(isProviderMetadataUpdated==true) {
                    registry.put(newPath, resource);
                }
            }
        }
    }
}
 
Example 12
Source File: ChallengeQuestionProcessor.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
/**
 * @param questionDTOs
 * @throws IdentityException
 */
public void setChallengeQuestions(ChallengeQuestionDTO[] questionDTOs) throws IdentityException {
    Registry registry = null;
    try {
        int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
        registry = IdentityMgtServiceComponent.getRegistryService().getConfigSystemRegistry(tenantId);

        if (!registry.resourceExists(IdentityMgtConstants.IDENTITY_MANAGEMENT_PATH)) {
            Collection securityQuestionResource = registry.newCollection();
            registry.put(IdentityMgtConstants.IDENTITY_MANAGEMENT_PATH, securityQuestionResource);
        }
        Resource identityMgtResource = registry.get(IdentityMgtConstants.IDENTITY_MANAGEMENT_PATH);
        if (identityMgtResource != null) {
            String questionCollectionPath = IdentityMgtConstants.IDENTITY_MANAGEMENT_QUESTIONS;
            if (registry.resourceExists(questionCollectionPath)) {
                registry.delete(questionCollectionPath);
            }

            Collection questionCollection = registry.newCollection();
            registry.put(questionCollectionPath, questionCollection);

            for (int i = 0; i < questionDTOs.length; i++) {
                Resource resource = registry.newResource();
                resource.addProperty("question", questionDTOs[i].getQuestion());
                resource.addProperty("isPromoteQuestion", String.valueOf(questionDTOs[i].isPromoteQuestion()));
                resource.addProperty("questionSetId", questionDTOs[i].getQuestionSetId());
                registry.put(IdentityMgtConstants.IDENTITY_MANAGEMENT_QUESTIONS +
                        RegistryConstants.PATH_SEPARATOR + "question" + i +
                        RegistryConstants.PATH_SEPARATOR, resource);
            }
        }
    } catch (RegistryException e) {
        throw IdentityException.error("Error while setting challenge question.", e);
    }

}
 
Example 13
Source File: DefaultPolicyDataStore.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
@Override
public void setPolicyData(String policyId, PolicyStoreDTO policyDataDTO) throws EntitlementException {

    Registry registry = EntitlementServiceComponent.
            getGovernanceRegistry(CarbonContext.getThreadLocalCarbonContext().getTenantId());
    try {
        String path = policyDataCollection + policyId;
        Resource resource;
        if (registry.resourceExists(path)) {
            resource = registry.get(path);
        } else {
            resource = registry.newCollection();
        }
        resource.setMediaType(PDPConstants.REGISTRY_MEDIA_TYPE);
        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 14
Source File: RegistryDataManager.java    From product-ei with Apache License 2.0 5 votes vote down vote up
/**
 * Migrate keystore password in super tenant and other tenants
 *
 * @param tenantId
 * @throws RegistryException
 * @throws CryptoException
 */
private void migrateKeyStorePasswordForTenant(int tenantId) throws RegistryException, CryptoException {
    Registry registry = MigrationServiceDataHolder.getRegistryService().getGovernanceSystemRegistry(tenantId);
    if (registry.resourceExists(Constant.KEYSTORE_RESOURCE_PATH)) {
        Collection keyStoreCollection = (Collection) registry.get(Constant.KEYSTORE_RESOURCE_PATH);
        for (String keyStorePath : keyStoreCollection.getChildren()) {
            updateRegistryProperties(registry, keyStorePath,
                    new ArrayList<>(Arrays.asList(Constant.PASSWORD, Constant.PRIVATE_KEY_PASS)));
        }
    }
}
 
Example 15
Source File: ChallengeQuestionProcessor.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
/**
 * @return
 * @throws IdentityException
 */
public List<ChallengeQuestionDTO> getAllChallengeQuestions() throws IdentityException {

    List<ChallengeQuestionDTO> questionDTOs = new ArrayList<ChallengeQuestionDTO>();
    try {
        int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
        Registry registry = IdentityMgtServiceComponent.getRegistryService().
                getConfigSystemRegistry(tenantId);
        if (registry.resourceExists(IdentityMgtConstants.IDENTITY_MANAGEMENT_QUESTIONS)) {
            Collection collection = (Collection) registry.
                    get(IdentityMgtConstants.IDENTITY_MANAGEMENT_QUESTIONS);
            String[] children = collection.getChildren();
            for (String child : children) {
                Resource resource = registry.get(child);
                String question = resource.getProperty("question");
                String isPromoteQuestion = resource.getProperty("isPromoteQuestion");
                String questionSetId = resource.getProperty("questionSetId");
                if (question != null) {
                    ChallengeQuestionDTO questionDTO = new ChallengeQuestionDTO();
                    questionDTO.setQuestion(question);
                    if (isPromoteQuestion != null) {
                        questionDTO.setPromoteQuestion(Boolean.parseBoolean(isPromoteQuestion));
                    }
                    if (questionSetId != null) {
                        questionDTO.setQuestionSetId(questionSetId);
                    }
                    questionDTO.setPromoteQuestion(false);
                    questionDTOs.add(questionDTO);
                }
            }

        }
    } catch (RegistryException e) {
        throw IdentityException.error(e.getMessage(), e);
    }
    return questionDTOs;
}
 
Example 16
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);
        }
    }
}
 
Example 17
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 18
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 19
Source File: MetadataApiRegistry.java    From attic-stratos with Apache License 2.0 4 votes vote down vote up
public void addPropertyToApplication(String applicationId, Property property)
        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 {
            nodeResource = registry.newCollection();
            if (log.isDebugEnabled()) {
                log.debug(String.format("Registry resource created: [resource-path] %s", resourcePath));
            }
        }

        boolean updated = false;
        for (String value : property.getValues()) {
            if (!propertyValueExist(nodeResource, property.getKey(), value)) {
                updated = true;
                if (log.isDebugEnabled()) {
                    log.debug(String.format("Registry property updated: [resource-path] %s, [key] %s [value] %s",
                            resourcePath, property.getKey(), value));
                }
                nodeResource.addProperty(property.getKey(), value);
            } else {
                if (log.isDebugEnabled()) {
                    log.debug(
                            String.format("Registry value already exists: [resource-path] %s, [key] %s, [value] %s",
                                    resourcePath, property.getKey(), value));
                }
            }
        }
        if (updated) {
            registry.put(resourcePath, nodeResource);
            if (log.isDebugEnabled()) {
                log.debug(String.format("Registry property is persisted: [resource-path] %s, [key] %s, [values] %s",
                        resourcePath, property.getKey(), Arrays.asList(property.getValues())));
            }
        }
    } catch (Exception e) {
        String msg = String
                .format("Failed to persist properties in registry: [resource-path] %s, [key] %s, [values] %s",
                        resourcePath, property.getKey(), Arrays.asList(property.getValues()));
        log.error(msg, e);
        throw new MetadataException(msg, e);
    } finally {
        try {
            releaseWriteLock(applicationId);
        } catch (MetadataException ignored) {
        }
    }
}
 
Example 20
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);
    }

}