Skip to content
GroupNameService.java 2.67 KiB
Newer Older
Sonia Zorba's avatar
Sonia Zorba committed
package it.inaf.ia2.gms.service;

import it.inaf.ia2.gms.persistence.GroupsDAO;
import it.inaf.ia2.gms.persistence.model.GroupEntity;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Utility class for retrieving the complete names (including parents) from a
 * set of group paths.
 */
@Service
public class GroupNameService {

    @Autowired
    private GroupsDAO groupsDAO;

    /**
     * @param groupsIdPath map having group id as keys and group paths as values
     * @return map having group id as keys and group names as values
     */
    public Map<String, List<String>> getNames(List<Map.Entry<String, String>> groupsIdPath) {

        Set<String> allIdentifiers = new HashSet<>();
        for (Map.Entry<String, String> entry : groupsIdPath) {
            allIdentifiers.addAll(getIdentifiers(entry.getValue()));
        }

        Map<String, String> groupSingleNamesMap = getGroupSingleNamesMap(allIdentifiers);

        Map<String, List<String>> groupCompleteNamesMap = new HashMap<>();
        for (Map.Entry<String, String> entry : groupsIdPath) {
            List<String> groupCompleteName = getGroupCompleteName(groupSingleNamesMap, entry.getValue());
            groupCompleteNamesMap.put(entry.getKey(), groupCompleteName);
        }

        return groupCompleteNamesMap;
    }

    private Map<String, String> getGroupSingleNamesMap(Set<String> allIdentifiers) {
        Map<String, String> groupNamesMap = new HashMap<>();
        for (GroupEntity group : groupsDAO.findGroupsByIds(allIdentifiers)) {
            groupNamesMap.put(group.getId(), group.getName());
        }

        return groupNamesMap;
    }

    private List<String> getGroupCompleteName(Map<String, String> groupNamesMap, String groupPath) {
        List<String> names = new ArrayList<>();
        if (groupPath.isEmpty()) {
            names.add("Root");
        } else {
            List<String> identifiers = getIdentifiers(groupPath);
            for (String groupId : identifiers) {
                names.add(groupNamesMap.get(groupId));
            }
        }
        return names;
    }

    /**
     * Returns the list of all identifiers including parent ones.
     */
    private List<String> getIdentifiers(String groupPath) {
        List<String> identifiers = new ArrayList<>();
        if (!groupPath.isEmpty()) {
            for (String id : groupPath.split(Pattern.quote("."))) {
                identifiers.add(id);
            }
        }
        return identifiers;
    }
}