Java Code Examples for org.wso2.carbon.registry.core.Resource#setProperty()

The following examples show how to use org.wso2.carbon.registry.core.Resource#setProperty() . 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: CustomAPIIndexHandlerTest.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * This method tests whether the CustomAPIIndexer works correctly under different circumstances without throwing
 * Exception.
 *
 * @throws RegistryException Registry Exception.
 */
@Test
public void testPut() throws RegistryException {
    // Resource without property.
    Resource resource = new ResourceImpl();
    RequestContext requestContext = Mockito.mock(RequestContext.class);
    Mockito.doReturn(Mockito.mock(Registry.class)).when(requestContext).getRegistry();
    ResourcePath resourcePath = Mockito.mock(ResourcePath.class);
    Mockito.doReturn(resource).when(requestContext).getResource();
    Mockito.doReturn(resourcePath).when(requestContext).getResourcePath();
    CustomAPIIndexHandler customAPIIndexHandler = new CustomAPIIndexHandler();
    customAPIIndexHandler.put(requestContext);

    // Resource with property.
    resource.setProperty(APIConstants.CUSTOM_API_INDEXER_PROPERTY, "true");
    Mockito.doReturn(resource).when(requestContext).getResource();
    customAPIIndexHandler.put(requestContext);
}
 
Example 2
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 3
Source File: CustomAPIIndexerTest.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * This method checks the indexer's behaviour for new APIs which does not have the relevant properties.
 *
 * @throws RegistryException Registry Exception.
 * @throws APIManagementException API Management Exception.
 */
@Test
public void testIndexDocumentForNewAPI() throws APIManagementException, RegistryException {
    Resource resource = new ResourceImpl();
    PowerMockito.mockStatic(APIUtil.class);
    GenericArtifactManager artifactManager = Mockito.mock(GenericArtifactManager.class);
    PowerMockito.when(APIUtil.getArtifactManager((UserRegistry)(Mockito.anyObject()), Mockito.anyString())).
            thenReturn(artifactManager);
    GenericArtifact genericArtifact = Mockito.mock(GenericArtifact.class);
    Mockito.when(artifactManager.getGenericArtifact(Mockito.anyString())).thenReturn(genericArtifact);
    Mockito.when(genericArtifact.getAttribute(APIConstants.API_OVERVIEW_VISIBILITY)).thenReturn("public");
    PowerMockito.when(APIUtil.getAPI(genericArtifact, userRegistry))
            .thenReturn(Mockito.mock(API.class));
    resource.setProperty(APIConstants.ACCESS_CONTROL, APIConstants.NO_ACCESS_CONTROL);
    resource.setProperty(APIConstants.PUBLISHER_ROLES, APIConstants.NULL_USER_ROLE_LIST);
    resource.setProperty(APIConstants.STORE_VIEW_ROLES, APIConstants.NULL_USER_ROLE_LIST);
    Mockito.doReturn(resource).when(userRegistry).get(Mockito.anyString());
    indexer.getIndexedDocument(file2Index);
    Assert.assertNull(APIConstants.CUSTOM_API_INDEXER_PROPERTY + " property was set for the API which does not "
            + "require migration", resource.getProperty(APIConstants.CUSTOM_API_INDEXER_PROPERTY));
}
 
Example 4
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 5
Source File: PolicyPublisher.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
private void populateProperties(PublisherDataHolder holder,
                                PublisherDataHolder oldHolder, Resource resource) {

    PublisherPropertyDTO[] propertyDTOs = holder.getPropertyDTOs();
    for (PublisherPropertyDTO dto : propertyDTOs) {
        if (dto.getId() != null && dto.getValue() != null && dto.getValue().trim().length() > 0) {
            ArrayList<String> list = new ArrayList<String>();
            if (dto.isSecret()) {
                PublisherPropertyDTO propertyDTO = null;
                if (oldHolder != null) {
                    propertyDTO = oldHolder.getPropertyDTO(dto.getId());
                }
                if (propertyDTO == null || !propertyDTO.getValue().equalsIgnoreCase(dto.getValue())) {
                    try {
                        String encryptedValue = CryptoUtil.getDefaultCryptoUtil().
                                encryptAndBase64Encode(dto.getValue().getBytes());
                        dto.setValue(encryptedValue);
                    } catch (CryptoException e) {
                        log.error("Error while encrypting secret value of subscriber. " +
                                "Secret would not be persist.", e);
                        continue;
                    }
                }
            }
            list.add(dto.getValue());
            list.add(dto.getDisplayName());
            list.add(Integer.toString(dto.getDisplayOrder()));
            list.add(Boolean.toString(dto.isRequired()));
            list.add(Boolean.toString(dto.isSecret()));
            resource.setProperty(dto.getId(), list);
        }
    }
    resource.setProperty(PublisherDataHolder.MODULE_NAME, holder.getModuleName());
}
 
Example 6
Source File: APIEndpointPasswordRegistryHandler.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * This method is called for a registry get operation
 *
 * @param requestContext - The request context
 * @return - returns the modified resource
 * @throws RegistryException
 */
public Resource get(RequestContext requestContext) throws RegistryException {
    Resource resource = requestContext.getResource();
    if (resource != null) {
        String resourceContent = RegistryUtils.decodeBytes((byte[]) resource.getContent());
        try {
            OMElement omElement = AXIOMUtil.stringToOM(resourceContent);
            Iterator mainChildIt = omElement.getChildren();
            while (mainChildIt.hasNext()) {
                Object childObj = mainChildIt.next();
                if ((childObj instanceof OMElement) && ((APIConstants.OVERVIEW_ELEMENT)
                        .equals(((OMElement) childObj).getLocalName()))) {
                    Iterator childIt = ((OMElement) childObj)
                            .getChildrenWithLocalName(APIConstants.ENDPOINT_PASSWORD_ELEMENT);
                    //There is only one ep-password, hence no iteration
                    if (childIt.hasNext()) {
                        OMElement child = (OMElement) childIt.next();
                        String actualPassword = child.getText();
                        //Store the password in a hidden property to access in the PUT method.
                        if (!actualPassword.isEmpty()) {
                            resource.setProperty(APIConstants.REGISTRY_HIDDEN_ENDPOINT_PROPERTY, actualPassword);
                            child.setText(APIConstants.DEFAULT_MODIFIED_ENDPOINT_PASSWORD);
                        }
                    }
                }
            }
            resource.setContent(RegistryUtils.encodeString(omElement.toString()));
            log.debug("Modified API resource content with default password before get operation");
        } catch (XMLStreamException e) {
            log.error("There was an error in reading XML Stream during API get.");
            throw new RegistryException("There was an error reading the API resource.", e);
        }
    }
    return resource;
}
 
Example 7
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 8
Source File: RegistryConfigWriter.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
@Override
public void write(int tenantId, Properties props, String resourcePath)
        throws IdentityMgtConfigException {

    if(log.isDebugEnabled()) {
        log.debug("Writing data to registry path : " + resourcePath);
    }
    
    RegistryService registry = IdentityMgtServiceComponent.getRegistryService();
    try {
        UserRegistry userReg = registry.getConfigSystemRegistry(tenantId);
        Resource resource = userReg.newResource();
        Set<String> names = props.stringPropertyNames();
        // Only key value pairs exists and no multiple values exists a key.
        for (String keyName : names) {
            List<String> value = new ArrayList<String>();
            String valueStr = props.getProperty(keyName);
            
            if(log.isDebugEnabled()) {
                log.debug("Write key : " + keyName + " value : " + value);
            }
            
            // This is done due to casting to List in JDBCRegistryDao
            value.add(valueStr);
            resource.setProperty(keyName, value);
        }
        userReg.put(resourcePath, resource);

    } catch (RegistryException e) {
        throw new IdentityMgtConfigException(
                "Error occurred while writing data to registry path : " + resourcePath, e);
    }

}
 
Example 9
Source File: RegistryManager.java    From carbon-commons with Apache License 2.0 5 votes vote down vote up
/**
 * @param host
 *            The virtual host to be stored in the registry
 * @param webApp
 *            The webapp to be deployed in the virtual host
 * @throws Exception
 */
public void updateHostToRegistry(Host host, String webApp) throws Exception {
	try {
		registryService.beginTransaction();
		Resource hostResource;
		String hostResourcePath = (UrlMapperConstants.HostProperties.HOSTINFO + host.getName());
		if (registryService.resourceExists(hostResourcePath)) {
			hostResource = registryService.get(hostResourcePath);
			hostResource.setProperty(UrlMapperConstants.HostProperties.HOST_NAME,
					host.getName());
			hostResource.setProperty(UrlMapperConstants.HostProperties.WEB_APP, webApp);
			registryService.put(UrlMapperConstants.HostProperties.HOSTINFO + host.getName(),
					hostResource);
		} else {
			hostResource = registryService.newResource();
			hostResource.addProperty(UrlMapperConstants.HostProperties.HOST_NAME,
					host.getName());
			hostResource.addProperty(UrlMapperConstants.HostProperties.WEB_APP, webApp);
			registryService.put(UrlMapperConstants.HostProperties.HOSTINFO + host.getName(),
					hostResource);
		}
		registryService.commitTransaction();

	} catch (Exception e) {
		registryService.rollbackTransaction();
		log.error("Unable to update the host", e);
		throw e;
	}
}
 
Example 10
Source File: RegistryPolicyStoreManageModule.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
/**
 * This helper method creates properties object which contains the policy meta data.
 *
 * @param attributeDTOs List of AttributeDTO
 * @param resource      registry resource
 */
private void setAttributesAsProperties(AttributeDTO[] attributeDTOs, Resource resource) {

    int attributeElementNo = 0;
    if (attributeDTOs != null) {
        for (AttributeDTO attributeDTO : attributeDTOs) {
            resource.setProperty(KEY_VALUE_POLICY_META_DATA + attributeElementNo,
                                 attributeDTO.getCategory() + "," +
                                 attributeDTO.getAttributeValue() + "," +
                                 attributeDTO.getAttributeId() + "," +
                                 attributeDTO.getAttributeDataType());
            attributeElementNo++;
        }
    }
}
 
Example 11
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 12
Source File: SimplePAPStatusDataHandler.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
/**
 * @param statusHolders
 * @param resource
 */
private void populateStatusProperties(StatusHolder[] statusHolders, Resource resource) {
    if (statusHolders != null) {
        for (StatusHolder statusHolder : statusHolders) {
            if (statusHolder != null) {
                List<String> list = new ArrayList<String>();
                list.add(statusHolder.getType());
                list.add(statusHolder.getTimeInstance());
                list.add(statusHolder.getUser());
                list.add(statusHolder.getKey());
                list.add(Boolean.toString(statusHolder.isSuccess()));
                if (statusHolder.getMessage() != null) {
                    list.add(statusHolder.getMessage());
                } else {
                    list.add("");
                }
                if (statusHolder.getTarget() != null) {
                    list.add(statusHolder.getTarget());
                } else {
                    list.add("");
                }
                if (statusHolder.getTargetAction() != null) {
                    list.add(statusHolder.getTargetAction());
                } else {
                    list.add("");
                }
                if (statusHolder.getVersion() != null) {
                    list.add(statusHolder.getVersion());
                } else {
                    list.add("");
                }
                resource.setProperty(UUID.randomUUID().toString(), list);
            }
        }
    }
}
 
Example 13
Source File: EntitlementUtil.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
/**
 * This helper method creates properties object which contains the policy meta data.
 *
 * @param attributeDTOs List of AttributeDTO
 * @param resource      registry resource
 */
public static void setAttributesAsProperties(AttributeDTO[] attributeDTOs, Resource resource) {

    int attributeElementNo = 0;
    if (attributeDTOs != null) {
        for (AttributeDTO attributeDTO : attributeDTOs) {
            resource.setProperty("policyMetaData" + attributeElementNo,
                    attributeDTO.getCategory() + "," +
                            attributeDTO.getAttributeValue() + "," +
                            attributeDTO.getAttributeId() + "," +
                            attributeDTO.getAttributeDataType());
            attributeElementNo++;
        }
    }
}
 
Example 14
Source File: SimplePAPStatusDataHandler.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
/**
 * @param statusHolders
 * @param resource
 */
private void populateStatusProperties(StatusHolder[] statusHolders, Resource resource) {
    if (statusHolders != null) {
        for (StatusHolder statusHolder : statusHolders) {
            if (statusHolder != null) {
                List<String> list = new ArrayList<String>();
                list.add(statusHolder.getType());
                list.add(statusHolder.getTimeInstance());
                list.add(statusHolder.getUser());
                list.add(statusHolder.getKey());
                list.add(Boolean.toString(statusHolder.isSuccess()));
                if (statusHolder.getMessage() != null) {
                    list.add(statusHolder.getMessage());
                } else {
                    list.add("");
                }
                if (statusHolder.getTarget() != null) {
                    list.add(statusHolder.getTarget());
                } else {
                    list.add("");
                }
                if (statusHolder.getTargetAction() != null) {
                    list.add(statusHolder.getTargetAction());
                } else {
                    list.add("");
                }
                if (statusHolder.getVersion() != null) {
                    list.add(statusHolder.getVersion());
                } else {
                    list.add("");
                }
                resource.setProperty(UUID.randomUUID().toString(), list);
            }
        }
    }
}
 
Example 15
Source File: CarbonRepositoryUtils.java    From carbon-commons with Apache License 2.0 5 votes vote down vote up
/**
 * Save the given DeploymentSynchronizerConfiguration to the registry. The target
 * configuration registry space will be selected using the specified tenant ID. As a result
 * the configuration will be stored in the configuration registry of the specified
 * tenant.
 *
 * @param config The configuration to be saved
 * @param tenantId Tenant ID to select the configuration registry
 * @throws org.wso2.carbon.registry.core.exceptions.RegistryException if an error occurs while accessing the registry
 */
public static void persistConfiguration(DeploymentSynchronizerConfiguration config,
                                        int tenantId) throws RegistryException {

    Resource resource;
    UserRegistry localRepository = getLocalRepository(tenantId);
    if (!localRepository.resourceExists(DeploymentSynchronizerConstants.CARBON_REPOSITORY)) {
        resource = localRepository.newResource();
    } else {
        resource = localRepository.get(DeploymentSynchronizerConstants.CARBON_REPOSITORY);
    }

    resource.setProperty(DeploymentSynchronizerConstants.AUTO_COMMIT_MODE,
            String.valueOf(config.isAutoCommit()));
    resource.setProperty(DeploymentSynchronizerConstants.AUTO_CHECKOUT_MODE,
            String.valueOf(config.isAutoCheckout()));
    resource.setProperty(DeploymentSynchronizerConstants.AUTO_SYNC_PERIOD,
            String.valueOf(config.getPeriod()));
    resource.setProperty(DeploymentSynchronizerConstants.USE_EVENTING,
            String.valueOf(config.isUseEventing()));
    resource.setProperty(DeploymentSynchronizerConstants.REPOSITORY_TYPE,
            config.getRepositoryType());
    resource.setContent(config.isEnabled() ? "enabled" : "disabled");

    //Get Repository specific configuration parameters from config object.
    RepositoryConfigParameter[] parameters = config.getRepositoryConfigParameters();

    if (parameters != null && parameters.length != 0) {
        //Save each Repository specific configuration parameter in registry.
        for (int i = 0; i < parameters.length; i++) {
            resource.setProperty(parameters[i].getName(), parameters[i].getValue());
        }
    }

    localRepository.put(DeploymentSynchronizerConstants.CARBON_REPOSITORY, resource);
    resource.discard();
}
 
Example 16
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 17
Source File: PolicyPublisher.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
private void populateProperties(PublisherDataHolder holder,
                                PublisherDataHolder oldHolder, Resource resource) {

    PublisherPropertyDTO[] propertyDTOs = holder.getPropertyDTOs();
    for (PublisherPropertyDTO dto : propertyDTOs) {
        if (dto.getId() != null && dto.getValue() != null && dto.getValue().trim().length() > 0) {
            ArrayList<String> list = new ArrayList<String>();
            if (dto.isSecret()) {
                PublisherPropertyDTO propertyDTO = null;
                if (oldHolder != null) {
                    propertyDTO = oldHolder.getPropertyDTO(dto.getId());
                }
                if (propertyDTO == null || !propertyDTO.getValue().equalsIgnoreCase(dto.getValue())) {
                    try {
                        String encryptedValue = CryptoUtil.getDefaultCryptoUtil().
                                encryptAndBase64Encode(dto.getValue().getBytes());
                        dto.setValue(encryptedValue);
                    } catch (CryptoException e) {
                        log.error("Error while encrypting secret value of subscriber. " +
                                "Secret would not be persist.", e);
                        continue;
                    }
                }
            }
            list.add(dto.getValue());
            list.add(dto.getDisplayName());
            list.add(Integer.toString(dto.getDisplayOrder()));
            list.add(Boolean.toString(dto.isRequired()));
            list.add(Boolean.toString(dto.isSecret()));
            resource.setProperty(dto.getId(), list);
        }
    }
    resource.setProperty(PublisherDataHolder.MODULE_NAME, holder.getModuleName());
}
 
Example 18
Source File: XMPPSettingsDAO.java    From carbon-identity-framework with Apache License 2.0 4 votes vote down vote up
/**
 * Update XMPP Settings of a user
 *
 * @param userId
 * @param xmppServer
 * @param xmppUserName
 * @param xmppUserCode
 * @throws IdentityException
 */
public void updateXmppSettings(String userId, String xmppServer, String xmppUserName,
                               String xmppUserCode, boolean enabled, boolean pinEnabled) throws IdentityException {
    String path = null;
    Resource resource = null;

    String xmppEnabled = "false";
    String isPINEnabled = "false";

    if (enabled) {
        xmppEnabled = "true";
    }

    if (pinEnabled) {
        isPINEnabled = "true";
    }

    try {
        if (userId != null) {
            path = IdentityRegistryResources.XMPP_SETTINGS_ROOT + userId;
        }

        if (!registry.resourceExists(path)) {
            if (log.isInfoEnabled()) {
                log.info("XMPP Settings does not exist for the user " + userId);
            }
            return;
        }

        resource = registry.get(path);
        resource.setProperty(IdentityRegistryResources.XMPP_SERVER, xmppServer);
        resource.setProperty(IdentityRegistryResources.XMPP_USERNAME, xmppUserName);
        resource.setProperty(IdentityRegistryResources.XMPP_USERCODE, xmppUserCode);
        resource.setProperty(IdentityRegistryResources.XMPP_ENABLED, xmppEnabled);
        resource.setProperty(IdentityRegistryResources.XMPP_PIN_ENABLED, isPINEnabled);

        registry.put(path, resource);

        if (log.isInfoEnabled()) {
            log.info("XMPP Settings are updated for the user " + userId);
        }

    } catch (RegistryException e) {
        log.error("Error occured while updating the XMPP Settings.", e);
        throw IdentityException.error("Error occured while updating the XMPP Settings.", e);
    }
}
 
Example 19
Source File: APIConsumerImplTest.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
@Test
public void testGetRecentlyAddedAPIs() throws Exception {
    Registry userRegistry = Mockito.mock(Registry.class);
    APIConsumerImpl apiConsumer = new APIConsumerImplWrapper(userRegistry, apiMgtDAO);
    UserRegistry userRegistry1 = Mockito.mock(UserRegistry.class);
    APIManagerConfiguration apiManagerConfiguration = Mockito.mock(APIManagerConfiguration.class);
    APIManagerConfigurationService apiManagerConfigurationService = Mockito.
            mock(APIManagerConfigurationService.class);
    Mockito.when(serviceReferenceHolder.getAPIManagerConfigurationService()).thenReturn(apiManagerConfigurationService);
    Mockito.when(apiManagerConfigurationService.getAPIManagerConfiguration()).thenReturn(apiManagerConfiguration);
    Mockito.when(apiManagerConfiguration.getFirstProperty(Mockito.anyString())).thenReturn("true", "false");

    API api = Mockito.mock(API.class);
    Set<API> recentlyAddedAPI = new HashSet<API>();
    recentlyAddedAPI.add(api);
    PowerMockito.mockStatic(Caching.class);

    CacheManager cacheManager = Mockito.mock(CacheManager.class);
    Cache<Object, Object> cache = Mockito.mock(Cache.class);
    Mockito.when(Caching.getCacheManager(Mockito.anyString())).thenReturn(cacheManager);
    Mockito.when(cacheManager.getCache(Mockito.anyString())).thenReturn(cache);
    Mockito.when(cache.get(Mockito.anyObject())).thenReturn(recentlyAddedAPI);
    Resource resource = new ResourceImpl();
    resource.setProperty("overview_status", "overview_status");
    resource.setProperty("store_view_roles", "store_view_roles");
    String path = "testPath";
    Mockito.when(APIUtil.getAPIPath((APIIdentifier) Mockito.anyObject())).thenReturn(path);
    Mockito.when(userRegistry1.get(Mockito.anyString())).thenReturn(resource);

    PowerMockito.mockStatic(GovernanceUtils.class);
    PowerMockito.doNothing().when(APIUtil.class, "loadTenantRegistry", Mockito.anyInt());
    PowerMockito.when(APIUtil.isAllowDisplayMultipleVersions()).thenReturn(true, false);
    System.setProperty(CARBON_HOME, "");

    Mockito.when(registryService.getGovernanceUserRegistry(Mockito.anyString(), Mockito.anyInt())).
            thenReturn(userRegistry1);
    Mockito.when(registryService.getGovernanceSystemRegistry(Mockito.anyInt())).thenReturn(userRegistry1);
    GenericArtifactManager artifactManager = Mockito.mock(GenericArtifactManager.class);
    PowerMockito.when(APIUtil.getArtifactManager((UserRegistry)(Mockito.anyObject()), Mockito.anyString())).
            thenReturn(artifactManager);
    GenericArtifact artifact = Mockito.mock(GenericArtifact.class);
    GenericArtifact[] genericArtifacts = new GenericArtifact[]{artifact};
    Mockito.when(artifactManager.findGovernanceArtifacts(Mockito.anyString())).thenReturn(genericArtifacts);

    APIIdentifier apiId1 = new APIIdentifier("admin", "API1", "1.0.0");
    API api1 = new API(apiId1);
    Mockito.when(APIUtil.getAPI(artifact)).thenReturn(api1);
    //set isAllowDisplayMultipleVersions true
    assertNotNull(apiConsumer.getRecentlyAddedAPIs(10, "testDomain"));
    //set isAllowDisplayMultipleVersions false
    assertNotNull(apiConsumer.getRecentlyAddedAPIs(10, "testDomain"));
}
 
Example 20
Source File: CloudServicesUtil.java    From carbon-commons with Apache License 2.0 4 votes vote down vote up
public static void setCloudServiceActive(boolean active,
                                         String cloudServiceName,
                                         int tenantId, CloudServiceConfig cloudServiceConfig)
                                                                                             throws Exception {
    if (cloudServiceConfig.getLabel() == null) {
        // for the non-labled services, we are not setting/unsetting the
        // service active
        return;
    }

    UserRegistry govRegistry =
            CloudCommonServiceComponent.getGovernanceSystemRegistry(
                    MultitenantConstants.SUPER_TENANT_ID);
    UserRegistry configRegistry = CloudCommonServiceComponent.getConfigSystemRegistry(tenantId);
    String cloudServiceInfoPath = StratosConstants.CLOUD_SERVICE_INFO_STORE_PATH +
                                  RegistryConstants.PATH_SEPARATOR + tenantId +
                                  RegistryConstants.PATH_SEPARATOR + cloudServiceName;
    
    Resource cloudServiceInfoResource;
    if (govRegistry.resourceExists(cloudServiceInfoPath)) {
        cloudServiceInfoResource = govRegistry.get(cloudServiceInfoPath);
    } else {
        cloudServiceInfoResource = govRegistry.newCollection();
    }
    cloudServiceInfoResource.setProperty(StratosConstants.CLOUD_SERVICE_IS_ACTIVE_PROP_KEY,
                                         active ? "true" : "false");
    govRegistry.put(cloudServiceInfoPath, cloudServiceInfoResource);

    // then we will copy the permissions
    List<PermissionConfig> permissionConfigs = cloudServiceConfig.getPermissionConfigs();
    for (PermissionConfig permissionConfig : permissionConfigs) {
        String path = permissionConfig.getPath();
        String name = permissionConfig.getName();
        if (active) {
            if (!configRegistry.resourceExists(path)) {
                Collection collection = configRegistry.newCollection();
                collection.setProperty(StratosConstants.DISPLAY_NAME, name);
                configRegistry.put(path, collection);
            }
        } else {
            if (configRegistry.resourceExists(path)) {
                configRegistry.delete(path);
            }
        }
    }
}