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> getNames(List> groupsIdPath) { Set allIdentifiers = new HashSet<>(); for (Map.Entry entry : groupsIdPath) { allIdentifiers.addAll(getIdentifiers(entry.getValue())); } Map groupSingleNamesMap = getGroupSingleNamesMap(allIdentifiers); Map> groupCompleteNamesMap = new HashMap<>(); for (Map.Entry entry : groupsIdPath) { List groupCompleteName = getGroupCompleteName(groupSingleNamesMap, entry.getValue()); groupCompleteNamesMap.put(entry.getKey(), groupCompleteName); } return groupCompleteNamesMap; } private Map getGroupSingleNamesMap(Set allIdentifiers) { Map groupNamesMap = new HashMap<>(); for (GroupEntity group : groupsDAO.findGroupsByIds(allIdentifiers)) { groupNamesMap.put(group.getId(), group.getName()); } return groupNamesMap; } private List getGroupCompleteName(Map groupNamesMap, String groupPath) { List names = new ArrayList<>(); if (groupPath.isEmpty()) { names.add("Root"); } else { List 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 getIdentifiers(String groupPath) { List identifiers = new ArrayList<>(); if (!groupPath.isEmpty()) { for (String id : groupPath.split(Pattern.quote("."))) { identifiers.add(id); } } return identifiers; } }