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

The following examples show how to use org.wso2.carbon.registry.core.Registry#get() . 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: SecurityUIUtil.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
public static String getUrl() throws Exception {

        if (url == null) {
            ServiceHolder serviceHodler = ServiceHolder.getInstance();
            RegistryService regService = serviceHodler.getRegistryService();
            Registry systemRegistry = regService.getConfigSystemRegistry();
            Resource resource = systemRegistry.get("/carbon/connection/props");
            String servicePath = resource.getProperty("service-path");
            String contextRoot = resource.getProperty("context-root");

            String host = resource.getProperty("host-name");
            contextRoot = StringUtils.equals("/", contextRoot) ? "" : contextRoot;

            host = (host == null) ? "localhost" : host;
            String port = System.getProperty("carbon.https.port");
            StringBuilder urlValue = new StringBuilder();
            url = (urlValue.append("https://").append(host).append(":").append(port).append("/").append(contextRoot).append(servicePath).append("/")).toString();
        }

        return url;
    }
 
Example 2
Source File: APIKeyMgtUtil.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * This returns API object for given APIIdentifier. Reads from registry entry for given APIIdentifier
 * creates API object
 *
 * @param identifier APIIdentifier object for the API
 * @return API object for given identifier
 * @throws APIManagementException on error in getting API artifact
 */
public static API getAPI(APIIdentifier identifier) throws APIManagementException {
    String apiPath = APIUtil.getAPIPath(identifier);

    try {
        Registry registry = APIKeyMgtDataHolder.getRegistryService().getGovernanceSystemRegistry();
        GenericArtifactManager artifactManager = APIUtil.getArtifactManager(registry,
                APIConstants.API_KEY);
        if (artifactManager == null) {
            String errorMessage = "Artifact manager is null when retrieving API " + identifier.getApiName();
            log.error(errorMessage);
            throw new APIManagementException(errorMessage);
        }
        Resource apiResource = registry.get(apiPath);
        String artifactId = apiResource.getUUID();
        if (artifactId == null) {
            throw new APIManagementException("artifact id is null for : " + apiPath);
        }
        GenericArtifact apiArtifact = artifactManager.getGenericArtifact(artifactId);
        return APIUtil.getAPI(apiArtifact, registry);

    } catch (RegistryException e) {
        return null;
    }
}
 
Example 3
Source File: Util.java    From carbon-commons with Apache License 2.0 6 votes vote down vote up
public static String getRelativeUrl() {
    BundleContext context = CarbonUIUtil.getBundleContext();
    ServiceReference reference =
            context.getServiceReference(RegistryService.class.getName());
    RegistryService registryService = (RegistryService) context.getService(reference);
    String url = null;
    try {
        Registry systemRegistry = registryService.getConfigSystemRegistry();
        Resource resource = systemRegistry.get(RegistryResources.CONNECTION_PROPS);
        String servicePath = resource.getProperty("service-path");
        String contextRoot = resource.getProperty("context-root");
        contextRoot = contextRoot.equals("/") ? "" : contextRoot;
        url = contextRoot + servicePath + "/WSDL2CodeService";
    } catch (Exception e) {
        log.error(e);
    }
    return url;
}
 
Example 4
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 5
Source File: MetadataFinder.java    From carbon-commons with Apache License 2.0 6 votes vote down vote up
private static boolean loadMetaData() throws ReportingException {
    try {
        RegistryService registryService = ReportingTemplateComponent.getRegistryService();
        Registry registry = registryService.getConfigSystemRegistry();
        registry.beginTransaction();
        String location = ReportConstants.REPORT_META_DATA_PATH + ReportConstants.METADATA_FILE_NAME;
        Resource resource = null;
        if (registry.resourceExists(location)) {
            resource = registry.get(location);
            loadXML(resource);
            registry.commitTransaction();
            return true;
        } else {
            registry.commitTransaction();
            return false;
        }
    } catch (RegistryException e) {
        log.error("Exception occurred in loading the mete-data of reports", e);
        throw new ReportingException("Exception occurred in loading the mete-data of reports", e);
    }

}
 
Example 6
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 7
Source File: RegistryBasedTrustedServiceStore.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
/**
 * Get default claims for given trusted service
 *
 * @param realmName - trusted service realm name
 * @return - default claims for given trusted service
 * @throws Exception
 */
public ClaimDTO getTrustedServiceClaims(String realmName) throws Exception {
    realmName = replaceSlashWithConstantString(realmName);
    try {
        Registry registry = IdentityPassiveSTSServiceComponent.getConfigSystemRegistry();
        String trustedServicePath = registryTrustedServicePath + realmName;

        if (!registry.resourceExists(trustedServicePath)) {
            log.info("No trusted service found with name:" + realmName);
            return new ClaimDTO();
        }
        Resource resource = registry.get(trustedServicePath);
        ClaimDTO claimDTO = new ClaimDTO();
        claimDTO.setRealm(realmName.replace(SLASH_REPLACE_CHARACTER, "/"));
        String claims = resource.getProperty(CLAIMS);

        if (claims.startsWith("[")) {
            claims = claims.replaceFirst("\\[", "");
        }
        if (claims.endsWith("]")) {
            // replace ] and , too. handle better way. ugly code
            claims = claims.substring(0, claims.length() - 3);
        }

        claimDTO.setDefaultClaims(claims.split(","));

        claimDTO.setClaimDialect(resource.getProperty(CLAIM_DIALECT));
        return claimDTO;
    } catch (RegistryException e) {
        String error = "Error occurred when getting a trusted service due to error in accessing registry.";
        throw new Exception(error, e);
    }
}
 
Example 8
Source File: RegistryBasedTrustedServiceStore.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
/**
 * Get all trusted services
 *
 * @return
 * @throws Exception
 */
public ClaimDTO[] getAllTrustedServices() throws Exception {
    try {
        Registry registry = IdentityPassiveSTSServiceComponent.getConfigSystemRegistry();
        List<ClaimDTO> trustedServices = new ArrayList<ClaimDTO>();

        if (!registry.resourceExists(registryTrustedServicePath)) {
            return new ClaimDTO[0];
        }
        Collection trustedServiceCollection = (Collection) registry.get(registryTrustedServicePath);
        for (String resourcePath : trustedServiceCollection.getChildren()) {
            Resource resource = registry.get(resourcePath);
            ClaimDTO claimDTO = new ClaimDTO();
            claimDTO.setRealm(resource.getProperty(REALM_NAME).replace(SLASH_REPLACE_CHARACTER, "/"));

            String claims = resource.getProperty(CLAIMS);
            if (claims.startsWith("[")) {
                claims = claims.replaceFirst("\\[", "");
            }
            if (claims.endsWith("]")) {
                claims = claims.substring(0, claims.length() - 2);
            }
            claimDTO.setDefaultClaims(claims.split(","));

            claimDTO.setClaimDialect(resource.getProperty(CLAIM_DIALECT));

            trustedServices.add(claimDTO);
        }

        return trustedServices.toArray(new ClaimDTO[trustedServices.size()]);
    } catch (RegistryException e) {
        String error = "Error occurred when getting all trusted services due to error in accessing registry.";
        throw new Exception(error, e);
    }
}
 
Example 9
Source File: ProviderMigrationClient.java    From product-es with Apache License 2.0 5 votes vote down vote up
private String getMediaType(String rxtPath, Registry registry)
        throws RegistryException, IOException, SAXException, ParserConfigurationException {
    Resource artifactRxt = registry.get(rxtPath);
    byte[] rxtContent = (byte[]) artifactRxt.getContent();
    String rxtContentString = RegistryUtils.decodeBytes(rxtContent);
    Document dom = stringToDocument(rxtContentString);
    Element domElement = (Element) dom.getElementsByTagName(Constants.ARTIFACT_TYPE).item(0);
    return domElement.getAttribute(Constants.TYPE);
}
 
Example 10
Source File: DefaultPolicyDataStore.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
@Override
public PolicyStoreDTO[] getPolicyData() {

    Registry registry = EntitlementServiceComponent.
            getGovernanceRegistry(CarbonContext.getThreadLocalCarbonContext().getTenantId());
    List<PolicyStoreDTO> policyStoreDTOs = new ArrayList<PolicyStoreDTO>();
    try {
        if (registry.resourceExists(policyDataCollection)) {
            Collection collection = (Collection) registry.get(policyDataCollection);
            String[] paths = collection.getChildren();
            for (String path : paths) {
                if (registry.resourceExists(path)) {
                    PolicyStoreDTO dataDTO = new PolicyStoreDTO();
                    Resource resource = registry.get(path);
                    String order = resource.getProperty("order");
                    String active = resource.getProperty("active");
                    String id = path.substring(path.lastIndexOf(RegistryConstants.PATH_SEPARATOR) + 1);
                    dataDTO.setPolicyId(id);
                    if (order != null && order.trim().length() > 0) {
                        dataDTO.setPolicyOrder(Integer.parseInt(order));
                    }
                    dataDTO.setActive(Boolean.parseBoolean(active));
                    policyStoreDTOs.add(dataDTO);
                }
            }
        }
    } catch (RegistryException e) {
        if (log.isDebugEnabled()) {
            log.debug(e);
        }
    }
    return policyStoreDTOs.toArray(new PolicyStoreDTO[policyStoreDTOs.size()]);
}
 
Example 11
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 12
Source File: MetadataApiRegistry.java    From attic-stratos with Apache License 2.0 5 votes vote down vote up
private List<Property> getRegistryResourceProperties(String registryResourcePath, String applicationId)
        throws RegistryException, MetadataException {
    Registry tempRegistry = getRegistry();
    if (!tempRegistry.resourceExists(registryResourcePath)) {
        return null;
    }

    // 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 regResource = tempRegistry.get(registryResourcePath);
    ArrayList<Property> newProperties = new ArrayList<>();
    Properties props = regResource.getProperties();
    Enumeration<?> x = props.propertyNames();
    while (x.hasMoreElements()) {
        String key = (String) x.nextElement();
        List<String> values = regResource.getPropertyValues(key);
        Property property = new Property();
        property.setKey(key);
        String[] valueArr = new String[values.size()];
        property.setValues(values.toArray(valueArr));

        newProperties.add(property);
    }
    return newProperties;
}
 
Example 13
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 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: ProviderMigrationClient.java    From product-es with Apache License 2.0 5 votes vote down vote up
private String getStoragePath(String rxtPath, Registry registry)
        throws RegistryException, IOException, SAXException, ParserConfigurationException {
    Resource artifactRxt = registry.get(rxtPath);
    byte[] rxtContent = (byte[]) artifactRxt.getContent();
    String rxtContentString = RegistryUtils.decodeBytes(rxtContent);
    Document dom = stringToDocument(rxtContentString);
    Node storagePath = dom.getElementsByTagName(Constants.STORAGE_PATH).item(0);
    return storagePath.getFirstChild().getNodeValue();
}
 
Example 16
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 17
Source File: ChallengeQuestionProcessor.java    From carbon-identity-framework 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 18
Source File: ProviderMigrationClient.java    From product-es with Apache License 2.0 5 votes vote down vote up
/**
 * This method checks whether there is a provider in the overview table.
 * @param rxtPath path of the rxt file
 * @param registry registry instance
 * @return boolean
 * @throws RegistryException
 * @throws IOException
 * @throws SAXException
 * @throws ParserConfigurationException
 * @throws XMLStreamException
 */
private boolean hasOverviewProviderElement(String rxtPath, Registry registry)
        throws RegistryException, IOException, SAXException, ParserConfigurationException, XMLStreamException {
    Resource artifactRxt = registry.get(rxtPath);
    byte[] rxtContent = (byte[]) artifactRxt.getContent();
    String rxtContentString = RegistryUtils.decodeBytes(rxtContent);
    OMElement rxtContentOM = AXIOMUtil.stringToOM(rxtContentString);
    OMElement contentElement = rxtContentOM.getFirstChildWithName(new QName(Constants.CONTENT));
    Iterator tableNodes = contentElement.getChildrenWithLocalName(Constants.TABLE);
    while (tableNodes.hasNext()) {
        OMElement tableOMElement = (OMElement) tableNodes.next();
        if ("Overview".equals(tableOMElement.getAttributeValue(new QName(Constants.NAME)))) {
            Iterator fieldNodes = tableOMElement.getChildrenWithLocalName(Constants.FIELD);
            while (fieldNodes.hasNext()) {
                OMElement fieldElement = (OMElement) fieldNodes.next();
                OMElement nameElement = fieldElement.getFirstChildWithName(new QName(Constants.NAME));
                if (nameElement != null) {
                    if ("Provider".equals(nameElement.getText())) {
                        return true;
                    }
                }
            }
        }
    }

    return false;
}
 
Example 19
Source File: SimplePAPStatusDataHandler.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
private synchronized List<StatusHolder> readStatus(String path, String about) throws EntitlementException {

        Resource resource = null;
        Registry registry = null;
        int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
        try {
            registry = EntitlementServiceComponent.getRegistryService().
                    getGovernanceSystemRegistry(tenantId);
            if (registry.resourceExists(path)) {
                resource = registry.get(path);
            }
        } catch (RegistryException e) {
            log.error(e);
            throw new EntitlementException("Error while persisting policy status", e);
        }

        List<StatusHolder> statusHolders = new ArrayList<StatusHolder>();
        if (resource != null && resource.getProperties() != null) {
            Properties properties = resource.getProperties();
            for (Map.Entry<Object, Object> entry : properties.entrySet()) {
                PublisherPropertyDTO dto = new PublisherPropertyDTO();
                dto.setId((String) entry.getKey());
                Object value = entry.getValue();
                if (value instanceof ArrayList) {
                    List list = (ArrayList) entry.getValue();
                    if (list != null && list.size() > 0 && list.get(0) != null) {
                        StatusHolder statusHolder = new StatusHolder(about);
                        if (list.size() > 0 && list.get(0) != null) {
                            statusHolder.setType((String) list.get(0));
                        }
                        if (list.size() > 1 && list.get(1) != null) {
                            statusHolder.setTimeInstance((String) list.get(1));
                        } else {
                            continue;
                        }
                        if (list.size() > 2 && list.get(2) != null) {
                            String user = (String) list.get(2);
                            statusHolder.setUser(user);
                        } else {
                            continue;
                        }
                        if (list.size() > 3 && list.get(3) != null) {
                            statusHolder.setKey((String) list.get(3));
                        }
                        if (list.size() > 4 && list.get(4) != null) {
                            statusHolder.setSuccess(Boolean.parseBoolean((String) list.get(4)));
                        }
                        if (list.size() > 5 && list.get(5) != null) {
                            statusHolder.setMessage((String) list.get(5));
                        }
                        if (list.size() > 6 && list.get(6) != null) {
                            statusHolder.setTarget((String) list.get(6));
                        }
                        if (list.size() > 7 && list.get(7) != null) {
                            statusHolder.setTargetAction((String) list.get(7));
                        }
                        if (list.size() > 8 && list.get(8) != null) {
                            statusHolder.setVersion((String) list.get(8));
                        }
                        statusHolders.add(statusHolder);
                    }
                }
            }
        }
        if (statusHolders.size() > 0) {
            StatusHolder[] array = statusHolders.toArray(new StatusHolder[statusHolders.size()]);
            java.util.Arrays.sort(array, new StatusHolderComparator());
            if (statusHolders.size() > maxRecodes) {
                statusHolders = new ArrayList<StatusHolder>();
                for (int i = 0; i < maxRecodes; i++) {
                    statusHolders.add(array[i]);
                }
                persistStatus(path, statusHolders, true);
            } else {
                statusHolders = new ArrayList<StatusHolder>(Arrays.asList(array));
            }
        }

        return statusHolders;
    }
 
Example 20
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) {
        }
    }
}