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

The following examples show how to use org.wso2.carbon.registry.core.Registry#newResource() . 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: 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 3
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 4
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 5
Source File: RemoteTaskUtils.java    From carbon-commons with Apache License 2.0 6 votes vote down vote up
public static String createRemoteTaskMapping(int tenantId, String taskType,
        String taskName) throws TaskException {
    try {
        PrivilegedCarbonContext.startTenantFlow();
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(
                MultitenantConstants.SUPER_TENANT_DOMAIN_NAME, true);
        Registry registry = RegistryBasedTaskRepository.getRegistry();
        Resource res = registry.newResource();
        res.setProperty(REMOTE_TASK_TENANT_ID, Integer.toString(tenantId));
        res.setProperty(REMOTE_TASK_TASK_TYPE, taskType);
        res.setProperty(REMOTE_TASK_TASK_NAME, taskName);
        String remoteTaskId = generateRemoteTaskID();
        registry.put(resourcePathFromRemoteTaskId(remoteTaskId), res);
        return remoteTaskId;
    } catch (Exception e) {
        throw new TaskException(e.getMessage(), Code.UNKNOWN, e);
    } finally {
        PrivilegedCarbonContext.endTenantFlow();
    }
}
 
Example 6
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 7
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 8
Source File: ChallengeQuestionProcessor.java    From carbon-identity 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 9
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 10
Source File: Util.java    From carbon-commons with Apache License 2.0 5 votes vote down vote up
/**
 * Sends an email to the user with the link to verify.
 * @param data of the user
 * @param serviceConfig, EmailVerifier Configuration.
 * @throws Exception, if sending the user verification mail failed.
 */
public static void requestUserVerification(Map<String, String> data,
                                           EmailVerifierConfig serviceConfig) throws Exception {
    String emailAddress = data.get("email");

    emailAddress = emailAddress.trim();
    try {
        String secretKey = UUID.randomUUID().toString();

        // User is supposed to give where he wants to store the intermediate data.
        // But, here there is no tenant signing in happened yet.
        // So get the super tenant registry instance.
        Registry registry = Util.getConfigSystemRegistry(MultitenantConstants.SUPER_TENANT_ID);
        Resource resource = registry.newResource();
        // store the redirector url
        resource.setProperty("redirectPath", serviceConfig.getRedirectPath());
        // store the user data, redirectPath can be overwritten here.
        for (String s : data.keySet()) {
            resource.setProperty(s, data.get(s));
        }

        resource.setVersionableChange(false);
        String secretKeyPath = EMAIL_VERIFICATION_COLLECTION +
                RegistryConstants.PATH_SEPARATOR + secretKey;
        registry.put(secretKeyPath, resource);
        // sending the mail
        EmailSender sender = new EmailSender(serviceConfig, emailAddress, secretKey,
             PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain(true), data);
        sender.sendEmail();
    } catch (Exception e) {
        String msg = "Error in sending the email to validation.";
        log.error(msg, e);
        throw new Exception(msg, e);
    }
}
 
Example 11
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 12
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 serializableObject object to be persisted.
 */
public synchronized void persist(String resourcePath, Serializable serializableObject) 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(serializableObject));
        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 (Exception e1){
            if (log.isErrorEnabled()) {
                log.error("Could not rollback transaction", e1);
            }
        }
        String msg = "Failed to persist resource in registry: " + resourcePath;
        throw new RegistryException(msg, e);
    }
}
 
Example 13
Source File: MetadataApiRegistry.java    From attic-stratos with Apache License 2.0 5 votes vote down vote up
/**
 * Add property to cluster
 *
 * @param applicationId Application ID against which added property will be stored
 * @param clusterId     Cluster ID against which added property will be stored
 * @param property      Property to be stored in the registry
 * @throws RegistryException, MetadataException
 */
public void addPropertyToCluster(String applicationId, String clusterId, Property property)
        throws RegistryException, MetadataException {
    Registry registry = getRegistry();
    String resourcePath = mainResource + applicationId + "/" + clusterId;

    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.newResource();
            if (log.isDebugEnabled()) {
                log.debug(String.format("Registry resource created for [cluster-id] %s", clusterId));
            }
        }
        nodeResource.setProperty(property.getKey(), Arrays.asList(property.getValues()));
        registry.put(resourcePath, nodeResource);
        log.info(String.format(
                "Registry property persisted: [resource-path] %s [Property Name] %s [Property Values] %s",
                resourcePath, property.getKey(), Arrays.asList(property.getValues())));
    } catch (Exception e) {
        throw new MetadataException(
                String.format("Could not add registry resource: [resource-path] %s, [key] %s, [value] %s",
                        resourcePath, property.getKey(), Arrays.asList(property.getValues())), e);

    } finally {
        try {
            releaseWriteLock(applicationId);
        } catch (MetadataException ignored) {
        }
    }
}
 
Example 14
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 serializableObject object to be persisted.
 */
public synchronized void persist(String resourcePath, Serializable serializableObject) 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(serializableObject));
        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 (Exception e1){
           if (log.isErrorEnabled()) {
               log.error("Could not rollback transaction", e1);
           }
       }
        String msg = "Failed to persist resource in registry: " + resourcePath;
        throw new RegistryException(msg, e);
    }
}
 
Example 15
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);
    }

}