001/*
002 *  Copyright 2019 Anyware Services
003 *
004 *  Licensed under the Apache License, Version 2.0 (the "License");
005 *  you may not use this file except in compliance with the License.
006 *  You may obtain a copy of the License at
007 *
008 *      http://www.apache.org/licenses/LICENSE-2.0
009 *
010 *  Unless required by applicable law or agreed to in writing, software
011 *  distributed under the License is distributed on an "AS IS" BASIS,
012 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 *  See the License for the specific language governing permissions and
014 *  limitations under the License.
015 */
016package org.ametys.plugins.core.group;
017
018import java.util.HashMap;
019import java.util.List;
020import java.util.Map;
021import java.util.stream.Collectors;
022
023import org.apache.avalon.framework.component.Component;
024
025import org.ametys.core.group.Group;
026
027/**
028 * Helper class for groups, for common operations on {@link Group}
029 */
030public class GroupHelper implements Component
031{
032    /** The Avalon role */
033    public static final String ROLE = GroupHelper.class.getName();
034    
035    
036    /**
037     * Get group as JSON object
038     * @param group the group
039     * @param users true to get users' group
040     * @return the group as JSON object
041     */
042    public Map<String, Object> group2JSON(Group group, boolean users)
043    {
044        if (group == null)
045        {
046            return null;
047        }
048        
049        Map<String, Object> group2json = new HashMap<>();
050        group2json.put("id", group.getIdentity().getId());
051        group2json.put("groupDirectory", group.getIdentity().getDirectoryId());
052        group2json.put("groupDirectoryLabel", group.getGroupDirectory().getLabel());
053        group2json.put("label", group.getLabel());
054        if (users)
055        {
056            group2json.put("users", group.getUsers());
057        }
058        return group2json;
059    }
060    
061
062    /**
063     * Get groups as JSON object
064     * @param groups the groups
065     * @param users true to get users' group
066     * @return the group as JSON object
067     */
068    public List<Map<String, Object>> groups2JSON(List<Group> groups, boolean users)
069    {
070        return groups.stream()
071            .map(group -> this.group2JSON(group, users))
072            .collect(Collectors.toList());
073    }
074}