Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
Copyright 2005-2013 The Kuali Foundation Licensed under the Educational Community 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.opensource.org/licenses/ecl2.php 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.kuali.rice.kew.xml;
 
 
 import java.util.List;
 import java.util.Map;
 
 import static org.kuali.rice.core.api.impex.xml.XmlConstants.*;


Parses groups from XML.

Author(s):
Kuali Rice Team (rice.collab@kuali.org)
See also:
org.kuali.rice.kim.api.group.Group
 
 public class GroupXmlParser {
     private static final org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(GroupXmlParser.class);
     private static final boolean DEFAULT_ACTIVE_VALUE = true;
     private static final String DEFAULT_GROUP_DESCRIPTION = "";
     private HashMap<StringList<String>> memberGroupIds = new HashMap<StringList<String>>();
     private HashMap<StringList<String>> memberGroupNames = new HashMap<StringList<String>>();
     private HashMap<StringList<String>> memberPrincipalIds = new HashMap<StringList<String>>();
     private Map<StringStringgroupAttributes = new HashMap<StringString>();
 
     public List<GroupparseGroups(InputStream inputthrows IOExceptionXmlException {
         try {
             Document doc = XmlHelper.trimSAXXml(input);
             Element root = doc.getRootElement();
             return parseGroups(root);
         } catch (JDOMException e) {
             throw new XmlException("Parse error."e);
         } catch (SAXException e){
             throw new XmlException("Parse error.",e);
         } catch(ParserConfigurationException e){
             throw new XmlException("Parse error.",e);
         }
     }


    
Parses and saves groups

Parameters:
element top-level 'data' element which should contain a <groups> child element
Returns:
a list of parsed and saved, current, groups;
Throws:
org.kuali.rice.core.api.util.xml.XmlException
 
     @SuppressWarnings("unchecked")
 	public List<GroupparseGroups(Element elementthrows XmlException {
         List<Groupgroups = new ArrayList<Group>();
         for (Element groupsElement: (List<Element>) element.getChildren()) {
 
             for (Element groupElement: (List<Element>) groupsElement.getChildren()) {
                 groups.add(parseGroup(groupElement));
             }
         }
         for (Group group : groups) {
             GroupService groupService = KimApiServiceLocator.getGroupService();
             // check if group already exists
             Group foundGroup = groupService.getGroupByNamespaceCodeAndName(group.getNamespaceCode(), group.getName());
 
             if (foundGroup == null) {
                 if ( .isInfoEnabled() ) {
                	.info("Group named '" + group.getName() + "' not found, creating new group named '" + group.getName() + "'");
                }
                try {
                    Group newGroup =  groupService.createGroup(group);
                    String key = newGroup.getNamespaceCode().trim() + . + newGroup.getName().trim();
                    addGroupMembers(newGroupkey);
                } catch (Exception e) {
                    throw new RuntimeException("Error creating group with name '" + group.getName() + "'"e);
                }
            } else {
            	if ( .isInfoEnabled() ) {
            		.info("Group named '" + group.getName() + "' found, creating a new version");
            	}
                try {
                    Group.Builder builder = Group.Builder.create(foundGroup);
                    builder.setActive(group.isActive());
                    builder.setDescription(group.getDescription());
                    builder.setKimTypeId(group.getKimTypeId());
                    //builder.setVersionNumber(foundGroup.getVersionNumber());
                    group = builder.build();
                    groupService.updateGroup(foundGroup.getId(), group);
                    //delete existing group members and replace with new
                    groupService.removeAllMembers(foundGroup.getId());
                    String key = group.getNamespaceCode().trim() + . + group.getName().trim();
                    addGroupMembers(groupkey);
                } catch (Exception e) {
                    throw new RuntimeException("Error updating group."e);
                }
            }
        }
        return groups;
    }
    @SuppressWarnings("unchecked")
	private Group parseGroup(Element elementthrows XmlException {
        // Type element and children (namespace and name)
        String typeId = null;
        KimType kimTypeInfo;
        List<KimTypeAttributekimTypeAttributes = new ArrayList<KimTypeAttribute>();
        if (element.getChild() != null) {
            Element typeElement = element.getChild();
            String typeNamespace = typeElement.getChildText();
            String typeName = typeElement.getChildText();
            kimTypeInfo = KimApiServiceLocator.getKimTypeInfoService().findKimTypeByNameAndNamespace(typeNamespacetypeName);
            if (kimTypeInfo != null) {
            	typeId = kimTypeInfo.getId();
                kimTypeAttributes = kimTypeInfo.getAttributeDefinitions();
            } else  {
                throw new XmlException("Invalid type name and namespace specified.");
            }
        } else { //set to default type
            if (kimTypeInfo != null) {
            	typeId = kimTypeInfo.getId();
                kimTypeAttributes = kimTypeInfo.getAttributeDefinitions();
            } else {
            	throw new RuntimeException("Failed to locate the 'Default' group type!  Please ensure that it's in your database.");
            }
        }
        //groupInfo.setKimTypeId(typeId);
        String groupNamespace = element.getChildText();
        if (groupNamespace == null) {
            throw new XmlException("Namespace must have a value.");
        }
        String groupName = element.getChildText();
        if (groupName == null) {
            throw new XmlException("Name must have a value.");
        }
        Group.Builder groupInfo = Group.Builder.create(groupNamespacegroupNametypeId);
        IdentityService identityService = KimApiServiceLocator.getIdentityService();
        //groupInfo.setGroupName(element.getChildText(NAME, GROUP_NAMESPACE));
        String id = element.getChildText();
        if (id != null) {
            groupInfo.setId(id.trim());
        } else {
        	
        }
        String description = element.getChildText();
        if (description != null && !description.trim().equals("")) {
            groupInfo.setDescription(description);
        }
        //Active Indicator
        groupInfo.setActive();
        if (element.getChildText() != null) {
            String active = element.getChildText().trim();
            if (active.toUpperCase().equals("N") || active.toUpperCase().equals("FALSE")) {
                groupInfo.setActive(false);
            }
        }
        //Get list of attribute keys
        List<StringvalidAttributeKeys = new ArrayList<String>();
        for (KimTypeAttribute attribute : kimTypeAttributes) {
            validAttributeKeys.add(attribute.getKimAttribute().getAttributeName());
        }
        //Group attributes
        if (element.getChild() != null) {
            List<Elementattributes = element.getChild().getChildren();
            Map<StringStringattrMap = new HashMap<StringString>();
            for (Element attr : attributes ) {
                attrMap.put(attr.getAttributeValue(), attr.getAttributeValue());
                if (!validAttributeKeys.contains(attr.getAttributeValue())) {
                    throw new XmlException("Invalid attribute specified.");
                }
            }
            Map<StringStringgroupAttributes = attrMap;
            if (!groupAttributes.isEmpty()) {
                groupInfo.setAttributes(groupAttributes);
            }
        }
        //Group members
        List<Elementmembers = null;
        if(element.getChild() == null) {
            members = new ArrayList<Element>();
        }
        else {
            members = element.getChild().getChildren();
        }
        for (Element member : members) {
            String elementName = member.getName().trim();
            if (elementName.equals()) {
                String principalName = member.getText().trim();
                Principal principal = identityService.getPrincipalByPrincipalName(principalName);
                if (principal != null) {
                    addPrincipalToGroup(groupInfo.getNamespaceCode(), groupInfo.getName(), principal.getPrincipalId());
                } else {
                    throw new XmlException("Principal Name "+principalName+" cannot be found.");
                }
            } else if (elementName.equals()) {
                String xmlPrincipalId = member.getText().trim();
                Principal principal = identityService.getPrincipal(xmlPrincipalId);
                if (principal != null) {
                    addPrincipalToGroup(groupInfo.getNamespaceCode(), groupInfo.getName(), principal.getPrincipalId());
                } else {
                    throw new XmlException("Principal Id "+xmlPrincipalId+" cannot be found.");
                }
            // Groups are handled differently since the member group may not be saved yet.  Therefore they need to be validated after the groups are saved.
            } else if (elementName.equals()) {
                String xmlGroupId = member.getText().trim();
                addGroupToGroup(groupInfo.getNamespaceCode(), groupInfo.getName(), xmlGroupId);
            } else if (elementName.equals()) {
                String xmlGroupName = member.getChildText().trim();
                String xmlGroupNamespace = member.getChildText().trim();
                addGroupNameToGroup(groupInfo.getNamespaceCode(), groupInfo.getName(), xmlGroupNamespacexmlGroupName);
            } else {
                .error("Unknown member element: " + elementName);
            }
        }
        return groupInfo.build();
    }
    private void addPrincipalToGroup(String groupNamespaceString groupNameString principalId) {
        String key = groupNamespace.trim() + . + groupName.trim();
        List<StringprincipalIds = .get(key);
        if (principalIds == null) {
            principalIds = new ArrayList<String>();
        }
        principalIds.add(principalId);
        .put(keyprincipalIds);
    }
    private void addGroupToGroup(String groupNamespaceString groupNameString groupId) {
        String key = groupNamespace.trim() + . + groupName.trim();
        List<StringgroupIds = .get(key);
        if (groupIds == null) {
            groupIds = new ArrayList<String>();
        }
        groupIds.add(groupId);
        .put(keygroupIds);
    }
    private void addGroupNameToGroup(String groupNamespaceString groupNameString memberGroupNamespaceString memberGroupName) {
        String key = groupNamespace.trim() + . + groupName.trim();
        List<StringgroupNames = .get(key);
        if (groupNames == null) {
            groupNames = new ArrayList<String>();
        }
        groupNames.add(memberGroupNamespace.trim() + . + memberGroupName.trim());
        .put(keygroupNames);
    }
    private void addGroupMembers(Group groupInfoString keythrows XmlException {
        GroupService groupService = KimApiServiceLocator.getGroupService();
        List<StringgroupIds = .get(key);
        if (groupIds != null) {
            for (String groupId : groupIds) {
                Group group = groupService.getGroup(groupId);
                if (group != null) {
                    groupService.addGroupToGroup(group.getId(), groupInfo.getId());
                } else {
                    throw new XmlException("Group Id "+groupId+" cannot be found.");
                }
            }
        }
        List<StringgroupNames = .get(key);
        if (groupNames != null) {
            for (String groupName : groupNames) {
                Group group = groupService.getGroupByNamespaceCodeAndName(Utilities.parseGroupNamespaceCode(groupName),
                        Utilities.parseGroupName(groupName));
                if (group != null) {
                	groupService.addGroupToGroup(group.getId(), groupInfo.getId());
                } else {
                    throw new XmlException("Group "+groupName+" cannot be found.");
                }
            }
        }
        List<StringprincipalIds = .get(key);
        if (principalIds != null) {
            for (String principalId : principalIds) {
            	groupService.addPrincipalToGroup(principalIdgroupInfo.getId());
            }
        }
    }
New to GrepCode? Check out our FAQ X