Package org.wso2.carbon.governance.api.util

Source Code of org.wso2.carbon.governance.api.util.GovernanceUtils

/*
* Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*      http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wso2.carbon.governance.api.util;

import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.impl.builder.StAXOMBuilder;
import org.apache.axiom.om.xpath.AXIOMXPath;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jaxen.JaxenException;
import org.wso2.carbon.governance.api.common.dataobjects.GovernanceArtifact;
import org.wso2.carbon.governance.api.endpoints.dataobjects.Endpoint;
import org.wso2.carbon.governance.api.exception.GovernanceException;
import org.wso2.carbon.governance.api.policies.dataobjects.Policy;
import org.wso2.carbon.governance.api.schema.dataobjects.Schema;
import org.wso2.carbon.governance.api.services.dataobjects.Service;
import org.wso2.carbon.governance.api.wsdls.dataobjects.Wsdl;
import org.wso2.carbon.registry.core.Registry;
import org.wso2.carbon.registry.core.RegistryConstants;
import org.wso2.carbon.registry.core.Resource;
import org.wso2.carbon.registry.core.ResourceImpl;
import org.wso2.carbon.registry.core.config.RegistryContext;
import org.wso2.carbon.registry.core.exceptions.RegistryException;
import org.wso2.carbon.registry.core.service.RegistryService;
import org.wso2.carbon.registry.core.session.UserRegistry;
import org.wso2.carbon.registry.extensions.utils.CommonUtil;

import javax.xml.namespace.QName;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class GovernanceUtils {

    private static final Log log = LogFactory.getLog(GovernanceUtils.class);
    private static RegistryService registryService;
    private static final String SEPARATOR = ":"; /*used only within this utility class for
                                                  association manipulation */

    /**
     * Setting the registry service.
     *
     * @param registryService the registryService.
     */
    public static void setRegistryService(RegistryService registryService) {
        GovernanceUtils.registryService = registryService;
    }

    /**
     * Returns the system governance registry.
     *
     * @param registry the user registry.
     * @return the system registry.
     * @throws RegistryException throws if an error occurs
     */
    public static Registry getGovernanceSystemRegistry(Registry registry) throws RegistryException {
        if (registryService == null) {
            return null;
        }
        UserRegistry userRegistry;
        if (!(registry instanceof UserRegistry)) {
            return null;
        }
        userRegistry = (UserRegistry) registry;
        return registryService.getGovernanceSystemRegistry(userRegistry.getTenantId());
    }

    /**
     * Obtains the governance user registry from the given root registry instance. This is useful
     * when creating a governance user registry out of a remote client registry instance.
     *
     * @param registry the remote client registry instance.
     * @param username the name of the user to connect as.
     *
     * @return the system registry.
     * @throws RegistryException throws if an error occurs
     */
    @SuppressWarnings("unused")
    public static Registry getGovernanceUserRegistry(Registry registry, String username)
            throws RegistryException {
        if (RegistryContext.getBaseInstance() == null) {
            RegistryContext.getBaseInstance(null, false);
        }
        return new UserRegistry(username, 0, registry, null,
                RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH);
    }

    /**
     * Method to remove a governance artifact from the registry.
     *
     * @param registry   the registry instance.
     * @param artifactId the identifier of the artifact.
     * @throws GovernanceException if the operation failed.
     */
    public static void removeArtifact(Registry registry, String artifactId)
            throws GovernanceException {

        try {
            Resource resource;
            Registry governanceSystemRegistry = getGovernanceSystemRegistry(registry);
            if (governanceSystemRegistry == null) {
                governanceSystemRegistry = registry;
            }
            if (governanceSystemRegistry.resourceExists(
                    GovernanceConstants.GOVERNANCE_ARTIFACT_INDEX_PATH)) {
                resource = governanceSystemRegistry.get(
                        GovernanceConstants.GOVERNANCE_ARTIFACT_INDEX_PATH);
            } else {
                String msg = "The artifact index doesn't exist. artifact index path: " +
                        GovernanceConstants.GOVERNANCE_ARTIFACT_INDEX_PATH + ".";
                log.error(msg);
                throw new GovernanceException(msg);
            }
            String path = resource.getProperty(artifactId);
            if (registry.resourceExists(path)) {
                registry.delete(path);
            }
            resource.removeProperty(artifactId);
            governanceSystemRegistry.put(
                    GovernanceConstants.GOVERNANCE_ARTIFACT_INDEX_PATH, resource);
        } catch (RegistryException e) {
            String msg = "Error in deleting the the artifact id:" + artifactId + ".";
            log.error(msg, e);
            throw new GovernanceException(msg, e);
        }
    }

    /**
     * Method to obtain the artifact path of a governance artifact on the registry.
     *
     * @param registry   the registry instance.
     * @param artifactId the identifier of the artifact.
     * @return the artifact path.
     * @throws GovernanceException if the operation failed.
     */
    public static String getArtifactPath(Registry registry, String artifactId)
            throws GovernanceException {

        try {
            Registry governanceSystemRegistry = getGovernanceSystemRegistry(registry);
            if (governanceSystemRegistry == null) {
                governanceSystemRegistry = registry;
            }
            if (!governanceSystemRegistry.resourceExists(
                    GovernanceConstants.GOVERNANCE_ARTIFACT_INDEX_PATH)) {
                String msg = "The artifact index doesn't exist. artifact index path: " +
                        GovernanceConstants.GOVERNANCE_ARTIFACT_INDEX_PATH + ".";
                if (log.isDebugEnabled()) {
                    log.debug(msg);
                }
                return null;
            }
            Resource resource = governanceSystemRegistry.get(
                    GovernanceConstants.GOVERNANCE_ARTIFACT_INDEX_PATH);
            return resource.getProperty(artifactId);
        } catch (RegistryException e) {
            String msg = "Error in getting the artifact id to path map: " +
                    GovernanceConstants.GOVERNANCE_ARTIFACT_INDEX_PATH +
                    ", artifact id:" + artifactId + ".";
            log.error(msg, e);
            throw new GovernanceException(msg, e);
        }
    }

    /**
     * Method to obtain a governance artifact on the registry.
     *
     * @param registry   the registry instance.
     * @param artifactId the identifier of the artifact.
     * @return the artifact.
     * @throws GovernanceException if the operation failed.
     */
    public static GovernanceArtifact retrieveGovernanceArtifactById(Registry registry,
                                                                    String artifactId)
            throws GovernanceException {
        String artifactPath = getArtifactPath(registry, artifactId);
        if (artifactPath == null) {
            String msg = "Governance artifact is not found for id: " + artifactId + ".";
            if (log.isDebugEnabled()) {
                log.debug(msg);
            }
            return null;
        }
        return retrieveGovernanceArtifactByPath(registry, artifactPath);
    }

    /**
     * Method to obtain a governance artifact on the registry by the artifact path.
     *
     * @param registry     the registry instance.
     * @param artifactPath the path of the artifact.
     * @return the artifact.
     * @throws GovernanceException if the operation failed.
     */
    public static GovernanceArtifact retrieveGovernanceArtifactByPath(Registry registry,
                                                                      String artifactPath)
            throws GovernanceException {
        try {
            Resource artifactResource;
            if (registry.resourceExists(artifactPath)) {
                artifactResource = registry.get(artifactPath);
            } else {
                // if the artifact path doesn't exist we are returning null.
                if (log.isDebugEnabled()) {
                    String msg = "The artifact path doesn't exists at " + artifactPath + ".";
                    log.debug(msg);
                }
                return null;
            }
            String artifactId =
                    artifactResource.getProperty(GovernanceConstants.ARTIFACT_ID_PROP_KEY);
            if (GovernanceConstants.SERVICE_MEDIA_TYPE.equals(artifactResource.getMediaType())) {
                // it is a service
                byte[] contentBytes = (byte[]) artifactResource.getContent();
                if (contentBytes == null) {
                    throw new GovernanceException("Unable to read payload of governance artifact " +
                            "at path: " + artifactPath);
                }
                OMElement contentElement = buildOMElement(contentBytes);
                Service service = new Service(artifactId, contentElement);
                service.associateRegistry(registry);
                return service;
//            }
            /*else if (GovernanceConstants.PROCESS_MEDIA_TYPE.equals(
                    artifactResource.getMediaType())) {
                // it is a process
                byte[] contentBytes = (byte[]) artifactResource.getContent();
                if (contentBytes == null) {
                    throw new GovernanceException("Unable to read payload of governance artifact " +
                            "at path: " + artifactPath);
                }
                OMElement contentElement = buildOMElement(contentBytes);
                Process process = new Process(artifactId, contentElement);
                process.associateRegistry(registry);
                return process;
            } else if (GovernanceConstants.SLA_MEDIA_TYPE.equals(artifactResource.getMediaType())) {
                // it is a SLA
                byte[] contentBytes = (byte[]) artifactResource.getContent();
                if (contentBytes == null) {
                    throw new GovernanceException("Unable to read payload of governance artifact " +
                            "at path: " + artifactPath);
                }
                OMElement contentElement = buildOMElement(contentBytes);
                SLA sla = new SLA(artifactId, contentElement);
                sla.associateRegistry(registry);
                return sla;*/
            } else if (GovernanceConstants.WSDL_MEDIA_TYPE
                    .equals(artifactResource.getMediaType())) {
                return new Wsdl(artifactId, registry);
            } else if (GovernanceConstants.SCHEMA_MEDIA_TYPE
                    .equals(artifactResource.getMediaType())) {
                return new Schema(artifactId, registry);
            } else if (GovernanceConstants.POLICY_XML_MEDIA_TYPE
                    .equals(artifactResource.getMediaType())) {
                return new Policy(artifactId, registry);
            } else if (GovernanceConstants.ENDPOINT_MEDIA_TYPE
                    .equals(artifactResource.getMediaType())) {
                return new Endpoint(artifactId, registry);
            }
            /*else if (GovernanceConstants.PEOPLE_MEDIA_TYPE.
                    equals(artifactResource.getMediaType())) {
                // it is a peopleArtifact
                byte[] contentBytes = (byte[]) artifactResource.getContent();
                OMElement contentElement = null;
                if (contentBytes != null) {
                    contentElement = buildOMElement(contentBytes);
                }
                String peopleGroup = CommonUtil.getPeopleGroup(contentElement);
                PeopleArtifact peopleArtifact = null;
                switch (PeopleGroup.valueOf(peopleGroup.toUpperCase())) {
                    case ORGANIZATION:
                        peopleArtifact = new Organization(artifactId, contentElement);
                        break;
                    case DEPARTMENT:
                        peopleArtifact = new Department(artifactId, contentElement);
                        break;
                    case PROJECT_GROUP:
                        peopleArtifact = new ProjectGroup(artifactId, contentElement);
                        break;
                    case PERSON:
                        peopleArtifact = new Person(artifactId, contentElement);
                        break;
                    default:
                        assert false;
                }
                peopleArtifact.associateRegistry(registry);
                return peopleArtifact;
            }*/

        } catch (RegistryException e) {
            String msg =
                    "Error in retrieving governance artifact by path. path: " + artifactPath + ".";
            log.error(msg, e);
            throw new GovernanceException(msg, e);
        }
        return null;
    }

    /*public static String retrieveGovernanceArtifactPath(Registry registry,
                                                      String artifactId) throws GovernanceException {
        try {
            Resource govIndexResource = registry.get(GovernanceConstants.GOVERNANCE_ARTIFACT_INDEX_PATH);
            return govIndexResource.getProperty(artifactId);
        } catch (RegistryException e) {
            String msg = "Error in adding an entry for the governance artifact. uuid: " + artifactId + ".";
            log.error(msg);
            throw new GovernanceException(msg, e);
        }
    }*/

    /**
     * Method to register a governance artifact.
     *
     * @param registry     the registry instance.
     * @param artifactId   the identifier of the artifact.
     * @param artifactPath the path of the artifact.
     * @throws GovernanceException if the operation failed.
     */
    public static void addGovernanceArtifactEntry(Registry registry,
                                                  String artifactId,
                                                  String artifactPath) throws GovernanceException {
        try {
            Registry systemGovernanceRegistry = getGovernanceSystemRegistry(registry);
            if (systemGovernanceRegistry == null) {
                systemGovernanceRegistry = registry;
            }
            Resource govIndexResource;
            if (systemGovernanceRegistry.resourceExists(
                    GovernanceConstants.GOVERNANCE_ARTIFACT_INDEX_PATH)) {
                govIndexResource = systemGovernanceRegistry.get(
                        GovernanceConstants.GOVERNANCE_ARTIFACT_INDEX_PATH);
            } else {
                govIndexResource = systemGovernanceRegistry.newResource();
            }
            govIndexResource.setProperty(artifactId, artifactPath);
            ((ResourceImpl) govIndexResource).setVersionableChange(false);
            systemGovernanceRegistry.put(GovernanceConstants.GOVERNANCE_ARTIFACT_INDEX_PATH,
                    govIndexResource);
        } catch (RegistryException e) {
            String msg =
                    "Error in adding an entry for the governance artifact. path: " + artifactPath +
                            ", uuid: " + artifactId + ".";
            log.error(msg);
            throw new GovernanceException(msg, e);
        }
    }

    /**
     * Method to build an AXIOM element from a byte stream.
     *
     * @param content the stream of bytes.
     * @return the AXIOM element.
     * @throws GovernanceException if the operation failed.
     */
    public static OMElement buildOMElement(byte[] content) throws GovernanceException {
        InputStream inputStream = new ByteArrayInputStream(content);
        XMLStreamReader parser;
        try {
            parser = XMLInputFactory.newInstance().createXMLStreamReader(inputStream);
        } catch (XMLStreamException e) {
            String msg = "Error in initializing the parser to build the OMElement.";
            log.error(msg, e);
            throw new GovernanceException(msg, e);
        }

        //create the builder
        StAXOMBuilder builder = new StAXOMBuilder(parser);
        //get the root element (in this case the envelope)

        return builder.getDocumentElement();
    }

    /**
     * Method to serialize an XML element into a string.
     *
     * @param element the XML element.
     * @return the corresponding String representation
     * @throws GovernanceException if the operation failed.
     */
    public static String serializeOMElement(OMElement element) throws GovernanceException {
        try {
            return element.toStringWithConsume();
        } catch (XMLStreamException e) {
            String msg = "Error in serializing the OMElement.";
            log.error(msg, e);
            throw new GovernanceException(msg, e);
        }
    }

    /**
     * Method to obtain a path from a qualified name.
     *
     * @param qName the qualified name.
     * @return the corresponding path.
     */
    public static String derivePathFromQName(QName qName) {
        String serviceName = qName.getLocalPart();
        String serviceNamespace = qName.getNamespaceURI();
        return (serviceNamespace == null ?
                "" : CommonUtil.derivePathFragmentFromNamespace(serviceNamespace)) + serviceName;
    }

    /**
     * Method to obtain a list of paths having resources of the given media type.
     *
     * @param registry  the registry instance to run query on.
     * @param mediaType the media type.
     * @return an array of resource paths.
     * @throws GovernanceException if the operation failed.
     */
    public static String[] getResultPaths(Registry registry,
                                          String mediaType) throws GovernanceException {
        String sql = "SELECT REG_PATH_ID, REG_NAME FROM REG_RESOURCE WHERE REG_MEDIA_TYPE=?";
        String path = RegistryConstants.QUERIES_COLLECTION_PATH + "/governance/searchMetaData";
        String[] result;
        try {
            Map<String, String> parameter = new HashMap<String, String>();
            parameter.put("1", mediaType);
            parameter.put("query", sql);
            result = (String[]) registry.executeQuery(null, parameter).getContent();
        } catch (RegistryException e) {
            String msg = "Error in getting the result for media type: " + mediaType + ".";
            log.error(msg, e);
            throw new GovernanceException(msg, e);
        }
        return result;
    }

    public static String getNameFromUrl(String url) {
        int slashIndex = url.lastIndexOf('/');
        if (slashIndex == -1) {
            return url;
        }
        if (slashIndex == url.length() - 1) {
            return url.substring(0, url.length() - 1);
        }
        return url.substring(slashIndex + 1);
    }

    @SuppressWarnings("unchecked")
    public static List<OMElement> evaluateXPathToElements(String expression,
                                                          OMElement root) throws JaxenException {

        String[] wsdlPrefixes = {
                "wsdl", "http://schemas.xmlsoap.org/wsdl/",
                "wsdl2", "http://www.w3.org/ns/wsdl",
                "xsd", "http://www.w3.org/2001/XMLSchema",
                "soap", "http://schemas.xmlsoap.org/wsdl/soap/",
                "soap12", "http://schemas.xmlsoap.org/wsdl/soap12/",
                "http", "http://schemas.xmlsoap.org/wsdl/http/",
        };
        AXIOMXPath xpathExpression = new AXIOMXPath(expression);

        for (int j = 0; j < wsdlPrefixes.length; j++) {
            xpathExpression.addNamespace(wsdlPrefixes[j++], wsdlPrefixes[j]);
        }
        return (List<OMElement>) xpathExpression.selectNodes(root);
    }

    /*
     * This method is used to retrieve departments attached to a given artifact. Applicable to
     * ProjectGroup and Person artifacts
     *
     * @param registry - Registry associated with <code>artifact</code>
     * @param artifact - ProjectGroup or Person artifact to which Departments are attached
     * @return Department artifacts attached to <code>artifact</code>
     * @throws GovernanceException If operation fails
     */
   /* public static Department[] getAffiliatedDepartments(Registry registry, PeopleArtifact artifact)
                                        throws GovernanceException {
        List<Department> list = new ArrayList<Department>();
        PeopleManager manager = new PeopleManager(registry);
        String[] affiliations = artifact.getAttributes(GovernanceConstants.AFFILIATIONS_ATTRIBUTE);

        if (affiliations != null) {
            for (String deptText : affiliations) {
                String deptName = deptText.split(GovernanceConstants.ENTRY_VALUE_SEPARATOR)[1];
                *//* We are assuming data consistency at this point and hence, not checking the 0th
                   element of the above returned array *//*
                PeopleArtifact pa = manager.getPeopleArtifactByName(deptName);
                if (pa instanceof Department) {
                    list.add((Department) pa);
                }
            }
        }
        return list.toArray(new Department[list.size()]);
    }*/

    /*
     * This method is used to retrieve organizations attached to a given artifact. Applicable to
     * ProjectGroup and Person artifacts
     *
     * @param registry - Registry associated with <code>artifact</code>
     * @param artifact - ProjectGroup or Person artifact to which Organizations are attached
     * @return Organization artifacts attached to <code>artifact</code>
     * @throws GovernanceException If operation fails
     */
    /*public static Organization[] getAffiliatedOrganizations(Registry registry,
                                                            PeopleArtifact artifact)
                                        throws GovernanceException {
        List<Organization> list = new ArrayList<Organization>();
        PeopleManager manager = new PeopleManager(registry);

        String[] affiliations = artifact.getAttributes(GovernanceConstants.AFFILIATIONS_ATTRIBUTE);
        if (affiliations != null) {
            for (String orgText : affiliations) {
                String orgName = orgText.split(GovernanceConstants.ENTRY_VALUE_SEPARATOR)[1];
                *//* We are assuming data consistency at this point and hence, not checking the 0th
                   element of the above returned array *//*
                PeopleArtifact pa = manager.getPeopleArtifactByName(orgName);
                if (pa instanceof Organization) {
                    list.add((Organization) pa);
                }
            }
        }
        return list.toArray(new Organization[list.size()]);
    }*/

    /*
     * This method is used to retrieve project groups attached to a given artifact. Applicable to
     * Person artifacts
     *
     * @param registry - Registry associated with <code>artifact</code>
     * @param artifact - Person artifact to which project groups are attached
     * @return ProjectGroup artifacts attached to <code>artifact</code>
     * @throws GovernanceException If operation fails
     */
    /*public static ProjectGroup[] getAffiliatedProjectGroups(Registry registry,
                                                            PeopleArtifact artifact)
                                        throws GovernanceException {
        List<ProjectGroup> list = new ArrayList<ProjectGroup>();
        PeopleManager manager = new PeopleManager(registry);
        String[] affiliations = artifact.getAttributes(GovernanceConstants.AFFILIATIONS_ATTRIBUTE);
        if (affiliations != null) {
            for (String pgText : affiliations) {
                String pgName = pgText.split(GovernanceConstants.ENTRY_VALUE_SEPARATOR)[1];
                *//* We are assuming data consistency at this point and hence, not checking the 0th
          element of the above returned array *//*
                PeopleArtifact pa = manager.getPeopleArtifactByName(pgName);
                if (pa instanceof ProjectGroup) {
                    list.add((ProjectGroup) pa);
                }
            }
        }
        return list.toArray(new ProjectGroup[list.size()]);
    }*/

    /*
     * This method is used to retrieve project groups that have the given artifact (Organization or
     * Department) as an affiliation
     *
     * @param registry - Registry associated with <code>artifact</code>
     * @param artifact - Organization/Department artifact
     * @return ProjectGroups that have <code>artifact</code> as an affiliation
     * @throws GovernanceException
     */
/*
    public static ProjectGroup[] getAttachedProjectGroups(Registry registry, PeopleArtifact artifact)
                                               throws GovernanceException {
        ProjectGroup[] pgs = new PeopleManager(registry).getAllProjectGroups();
        List<ProjectGroup> list = new ArrayList<ProjectGroup>();
        for (ProjectGroup pg : pgs) {
            for (Department department : pg.getDepartments()) {
                if (artifact.getName().equals(department.getName())) {
                    list.add(pg);
                }
            }
        }
        return list.toArray(new ProjectGroup[list.size()]);
    }
*/

    /*
     * This method is used to retrieve persons that have the given artifact (Organization or
     * Department) as an affiliation
     *
     * @param registry - Registry associated with <code>artifact</code>
     * @param artifact - Organization/Department artifact
     * @return Person artifacts that have <code>artifact</code> as an affiliation
     * @throws GovernanceException
     */
/*
    public static Person[] getAttachedPersons(Registry registry, PeopleArtifact artifact)
                                      throws GovernanceException {
        Person[] persons = new PeopleManager(registry).getAllPersons();
        List<Person> list = new ArrayList<Person>();
        for (Person person : persons) {
            for (Department department : person.getDepartments()) {
                if (artifact.getName().equals(department.getName())) {
                    list.add(person);
                }
            }
        }
        return list.toArray(new Person[list.size()]);
    }
*/

    /*
     * This method writes sub-group associations contained within the given ProjectGroup to the
     * registry. Existence of all the sub groups must be validated before calling this method.
     *
     * @param registry
     * @param projectGroup
     * @throws GovernanceException
     */
/*
    public static void writeSubGroupAssociations(Registry registry, ProjectGroup projectGroup)
                                          throws GovernanceException {
        try {
            if (!registry.resourceExists(projectGroup.getPath())) {
                return;
            }
            ProjectGroup[] subGroups = projectGroup.getSubGroups();
            // Get the existing association list which is related to the current operation
            Set<String> existingSet = new HashSet<String>();
            for (Association asso : registry.getAllAssociations(projectGroup.getPath())) {
                if ((GovernanceConstants.SUB_GROUP.equals(asso.getAssociationType()) &&
                        asso.getSourcePath().equals(projectGroup.getPath()))
                        ||
                        (GovernanceConstants.IS_PART_OF.equals(asso.getAssociationType()) &&
                                asso.getDestinationPath().equals(projectGroup.getPath()))) {
                    existingSet.add(asso.getSourcePath() + SEPARATOR + asso.getDestinationPath() +
                            SEPARATOR + asso.getAssociationType());
                }
            }

            // Get the updated association list from the projectGroup object
            Set<String> updatedSet = new HashSet<String>();
            for (ProjectGroup subGroup : subGroups) {
                updatedSet.add(projectGroup.getPath() + SEPARATOR + subGroup.getPath() +
                        SEPARATOR + GovernanceConstants.SUB_GROUP);
                updatedSet.add(subGroup.getPath() + SEPARATOR + projectGroup.getPath() + SEPARATOR +
                        GovernanceConstants.IS_PART_OF);
            }
            updateAssociations(registry, existingSet, updatedSet);
        } catch (RegistryException e) {
            String msg = "Error in writing sub group associations, parent project-group id: " +
                    projectGroup.getId() + ", path: " + projectGroup.getPath();
            log.error(msg, e);
            throw new GovernanceException(msg, e);
        }
    }
*/

    /*
     * This method writes owner associations contained within the service object to the registry.
     * Existence of all the owners as people artifacts must be validated before calling this method.
     *
     * @param registry
     * @param service
     * @throws GovernanceException
     */
/*
    public static void writeOwnerAssociations(Registry registry, Service service)
                                       throws GovernanceException {
        try {
            if (!registry.resourceExists(service.getPath())) {
                return;
            }
            PeopleArtifact[] owners = service.getOwners();
            // Remove associations that are not there anymore and add any new associations
            Association[] oldAssociations = registry.getAllAssociations(service.getPath());
            Set<String> oldSet = new HashSet<String>();
            for (Association association : oldAssociations) {
                if (GovernanceConstants.OWNED_BY.equals(association.getAssociationType()) ||
                        GovernanceConstants.OWNS.equals(association.getAssociationType())) {
                    oldSet.add(association.getSourcePath() + SEPARATOR +
                            association.getDestinationPath() + SEPARATOR +
                            association.getAssociationType());
                }
            }
            Set<String> updatedSet = new HashSet<String>();
            for (PeopleArtifact owner : owners) {
                updatedSet.add(service.getPath() + SEPARATOR + owner.getPath() + SEPARATOR +
                        GovernanceConstants.OWNED_BY);
                updatedSet.add(owner.getPath() + SEPARATOR + service.getPath() + SEPARATOR +
                        GovernanceConstants.OWNS);
            }
            updateAssociations(registry, oldSet, updatedSet);
        } catch (RegistryException e) {
            String msg = "Error in associating owners to service. Id: " + service.getId() +
                    ", path: " + service.getPath();
            log.error(msg, e);
            throw new GovernanceException(msg, e);
        }
    }
*/

    /*
     * This method writes consumer associations contained within the service object to the registry.
     * Existence of all the consumers as people artifacts must be validated before calling this
     * method.
     *
     * @param registry
     * @param service
     * @throws GovernanceException
     */
/*
    public static void writeConsumerAssociations(Registry registry, Service service)
                                         throws GovernanceException {
        try {
            if (!registry.resourceExists(service.getPath())) {
                return;
            }
            PeopleArtifact[] consumers = service.getConsumers();
            // Remove associations that are not there anymore and add any new associations
            Association[] oldAssociations = registry.getAllAssociations(service.getPath());
            Set<String> oldSet = new HashSet<String>();
            for (Association association : oldAssociations) {
                if (GovernanceConstants.CONSUMED_BY.equals(association.getAssociationType()) ||
                        GovernanceConstants.CONSUMES.equals(association.getAssociationType())) {
                    oldSet.add(association.getSourcePath() + SEPARATOR +
                            association.getDestinationPath() + SEPARATOR +
                            association.getAssociationType());
                }
            }
            Set<String> updatedSet = new HashSet<String>();
            for (PeopleArtifact consumer : consumers) {
                updatedSet.add(service.getPath() + SEPARATOR + consumer.getPath() + SEPARATOR +
                        GovernanceConstants.CONSUMED_BY);
                updatedSet.add(consumer.getPath() + SEPARATOR + service.getPath() + SEPARATOR +
                        GovernanceConstants.CONSUMES);
            }
            updateAssociations(registry, oldSet, updatedSet);
        } catch (RegistryException e) {
            String msg = "Error in associating owners to service. Id: " + service.getId() +
                    ", path: " + service.getPath();
            log.error(msg, e);
            throw new GovernanceException(msg, e);
        }
    }
*/

    /*
     * This method extracts people names from the given attribute of the given artifact and returns
     * an array containing PeopleArtifacts represented by those names.
     * Existence of people artifacts listed under the atrribute name must be validated before
     * calling this method.
     *
     * @param registry      Associated registry
     * @param artifact      GovernanceArtifact which stores people list as an attribute
     * @param attributeName Name of the attribute which stores people names
     * @throws GovernanceException
     */
/*
    public static PeopleArtifact[] extractPeopleFromAttribute(Registry registry,
                                                              GovernanceArtifact artifact,
                                                              String attributeName)
                                                throws GovernanceException {
        String[] peopleTexts = artifact.getAttributes(attributeName);
        PeopleManager manager = new PeopleManager(registry);
        List<PeopleArtifact> list = new ArrayList<PeopleArtifact>();
        if (peopleTexts != null) {
            for (String peopleText : peopleTexts) {
                String name = peopleText.split(GovernanceConstants.ENTRY_VALUE_SEPARATOR)[1];
                PeopleArtifact pa = manager.getPeopleArtifactByName(name);
                if (pa == null) {
                    String msg = "Invalid people artifact name is found within the governance " +
                            "artifact. Path: " + artifact.getPath() + ", Invalid people artifact " +
                            "name:" + name;
                    log.error(msg);
                    throw new GovernanceException(msg);
                } else {
                    list.add(pa);
                }
            }
        }
        return list.toArray(new PeopleArtifact[list.size()]);
    }
*/

/*
    private static void updateAssociations(Registry registry, Set<String> existingAssociationSet,
                                           Set<String> updatedAssociationSet)
                                    throws RegistryException {
        Set<String> removedAssociations = new HashSet<String>(existingAssociationSet);
        removedAssociations.removeAll(updatedAssociationSet);

        Set<String> newAssociations = new HashSet<String>(updatedAssociationSet);
        newAssociations.removeAll(existingAssociationSet);

        for (String removedAssociation : removedAssociations) {
            String[] params = removedAssociation.split(SEPARATOR);
            try {
                for (int i = 0; i < 2; i++) {
                    if (GovernanceUtils.retrieveGovernanceArtifactByPath(registry, params[i])
                            instanceof PeopleArtifact) {
                        registry.removeAssociation(params[0], params[1], params[2]);
                        break;
                    }
                }
            } catch (GovernanceException ignored) {
            }
        }

        for (String newAssociation : newAssociations) {
            String[] params = newAssociation.split(SEPARATOR);
            registry.addAssociation(params[0], params[1], params[2]);
        }
    }
*/
TOP

Related Classes of org.wso2.carbon.governance.api.util.GovernanceUtils

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.