Example usage for java.util NavigableMap values

List of usage examples for java.util NavigableMap values

Introduction

In this page you can find the example usage for java.util NavigableMap values.

Prototype

Collection<V> values();

Source Link

Document

Returns a Collection view of the values contained in this map.

Usage

From source file:edu.oregonstate.eecs.mcplan.domains.voyager.policies.DefensePolicy.java

@Override
public VoyagerAction getAction() {
    final ArrayList<Planet> friendly = Voyager.playerPlanets(s_, self_);
    final NavigableMap<Planet, ArrayList<Spaceship>> incoming = new TreeMap<Planet, ArrayList<Spaceship>>();
    for (final Spaceship ship : s_.spaceships) {
        ArrayList<Spaceship> ships = incoming.get(ship.dest);
        if (ships == null) {
            ships = new ArrayList<Spaceship>();
            incoming.put(ship.dest, ships);
        }/*from   w  w  w. j  a v  a  2 s .  c  om*/
        ships.add(ship);
    }
    for (final ArrayList<Spaceship> ships : incoming.values()) {
        Collections.sort(ships, Spaceship.ArrivalTimeComparator);
    }
    final ArrayList<Pair<Integer, Planet>> events = new ArrayList<Pair<Integer, Planet>>();
    for (final Map.Entry<Planet, ArrayList<Spaceship>> ships : incoming.entrySet()) {
        int t = 0;
        int strength_balance = Voyager.defense_strength(ships.getKey().population());
        for (final Spaceship ship : ships.getValue()) {
            if (ship.owner == ships.getKey().owner()) {
                strength_balance += Voyager.defense_strength(ship.population);
            } else {
                // TODO: 2.0 is "safety margin"; should be a parameter
                strength_balance -= 2.0 * Voyager.attack_strength(ship.population);
                if (strength_balance <= 0) {
                    t = ship.arrival_time;
                    break;
                }
            }
        }
        if (t > 0) {
            events.add(Pair.makePair(t, ships.getKey()));
            friendly.remove(ships.getKey());
        }
    }
    Collections.sort(events, new Pair.Comparator<Integer, Planet>());
    for (final Pair<Integer, Planet> e : events) {
        for (final Planet src : friendly) {
            // TODO: Need to account for ship speed
            if (Voyager.distance(src, e.second) < e.first) {
                // TODO: Garrison 1 should be parameter
                final int spare_soldiers = src.population(Unit.Soldier) - 1;
                if (spare_soldiers > 0) {
                    final int[] pop = new int[Unit.values().length];
                    pop[Unit.Soldier.ordinal()] = spare_soldiers;
                    return new LaunchAction(src, e.second, pop);
                }
            }
        }
    }

    return new NothingAction();
}

From source file:com.ikon.servlet.admin.PropertyGroupsServlet.java

/**
 * Puts the parameterMap into the NavigableMap. The map is polled first twice to save action and label. Then the resulting
 * array values is saved as a linkedHashMap to save order.
 * @param request/*from  www .j  av a 2 s.  co  m*/
 * @param response
 * @throws Exception
 */
private void writeToPropertyGroupsXML(HttpServletRequest request, HttpServletResponse response)
        throws Exception {

    //get values from form and sort it using navigableSet
    NavigableMap<String, String[]> propertyGroupMap = new TreeMap<String, String[]>(request.getParameterMap());
    String action = propertyGroupMap.pollFirstEntry().getValue()[0];
    String propertyGroupLabel = propertyGroupMap.pollFirstEntry().getValue()[0];

    Map<String, String> propertyMap = new LinkedHashMap<String, String>();
    for (String[] values : propertyGroupMap.values()) {
        propertyMap.put(values[0], values[1]);
    }

    XMLUtils xmlUtils = new XMLUtils(PROPERTY_GROUPS_XML);
    if (action.equals("register")) {
        xmlUtils.addPropertyGroup(propertyGroupLabel, propertyMap);
    } else if (action.equals("edit")) {
        xmlUtils.editPropertyGroup(propertyGroupLabel, propertyMap);
    }
}

From source file:starnubserver.connections.player.session.PlayerSession.java

public void loadPermissions() {
    Account account = playerCharacter.getAccount();
    LinkedHashSet<String> permissions = new LinkedHashSet<>();
    if (account == null) {
        GroupsManagement.getInstance().getGROUPS().values().stream()
                .filter(group -> group.getType().equalsIgnoreCase("noaccount")).forEach(group -> {
                    permissions.addAll(group.getGROUP_PERMISSIONS());
                });/*from w w w.ja  v  a 2 s.c  o m*/
    } else {
        List<AccountPermission> accountPermissions = AccountPermission.getAccountPermissionsByAccount(account);
        permissions.addAll(
                accountPermissions.stream().map(AccountPermission::getPermission).collect(Collectors.toList()));
        TreeMap<Integer, Group> allGroups = account.getAllGroupsOrderedByRank();
        NavigableMap<Integer, Group> navigableMap = allGroups.descendingMap();
        for (Group group : navigableMap.values()) {
            permissions.addAll(group.getGROUP_PERMISSIONS());
        }
    }
    permissions.forEach(this::addPermissionToMap);
    System.out.println(PERMISSIONS);
}

From source file:org.structnetalign.merge.BronKerboschMergeJob.java

@Override
public List<NavigableSet<Integer>> call() throws Exception {

    logger.info("Searching for cliques on job " + index + " containing " + graph.getVertexCount()
            + " vertices and " + graph.getHomologyCount() + " homology edges");

    // find the cliques
    BronKerboschCliqueFinder<Integer, HomologyEdge> finder = new BronKerboschCliqueFinder<>();

    // these cliques are ordered from largest to smallest
    Collection<Set<Integer>> cliques = finder.transform(graph.getHomology());

    // just report the cliques we're using
    logger.info("Job " + index + ": " + "Found " + cliques.size() + " maximal cliques");
    int i = 1;// w w w. j a v a2 s . c  om
    for (Set<Integer> clique : cliques) {
        logger.debug("Job " + index + ": " + "Clique " + i + ": " + clique);
        i++;
    }

    // partition the cliques by sets of interactions
    // we call these (maximal) degenerate sets
    List<NavigableSet<Integer>> simpleDegenerateSets = new ArrayList<NavigableSet<Integer>>();
    for (Set<Integer> clique : cliques) {
        NavigableMap<String, NavigableSet<Integer>> degenerateSetMap = new TreeMap<>();
        for (int v : clique) {
            Collection<Integer> neighbors = graph.getInteractionNeighbors(v);
            String hash = hashVertexInteractions(neighbors);
            NavigableSet<Integer> degenerateSet = degenerateSetMap.get(hash);
            if (degenerateSet == null) {
                degenerateSet = new TreeSet<>();
                degenerateSetMap.put(hash, degenerateSet);
            }
            degenerateSet.add(v);
            logger.trace("Job " + index + ": " + "Found " + hash + " --> " + degenerateSetMap.get(hash));
        }
        for (NavigableSet<Integer> set : degenerateSetMap.values()) {
            simpleDegenerateSets.add(set);
        }
    }

    /*
     * Now sort the degenerate sets from largest to smallest.
     * Take into account the edge case where the sizes are the same.
     */
    Comparator<NavigableSet<Integer>> comparator = new Comparator<NavigableSet<Integer>>() {
        @Override
        public int compare(NavigableSet<Integer> clique1, NavigableSet<Integer> clique2) {
            if (CollectionUtils.isEqualCollection(clique1, clique2))
                return 0;
            if (clique1.size() < clique2.size()) {
                return 1;
            } else if (clique1.size() > clique2.size()) {
                return -1;
            } else {
                Iterator<Integer> iter1 = clique1.iterator();
                Iterator<Integer> iter2 = clique2.iterator();
                while (iter1.hasNext()) { // we know they're the same size
                    int v1 = iter1.next();
                    int v2 = iter2.next();
                    if (v1 < v2) {
                        return 1;
                    } else if (v1 > v2) {
                        return -1;
                    }
                }
            }
            // they're the same throughout, so they're equal
            return 0;
        }
    };
    List<NavigableSet<Integer>> sortedDegenerateSets = new ArrayList<>(simpleDegenerateSets.size());
    sortedDegenerateSets.addAll(simpleDegenerateSets);
    Collections.sort(sortedDegenerateSets, comparator);

    /*
     * Now we want to return only the maximal maximal degenerate sets.
     */

    TreeSet<String> verticesAlreadyUsed = new TreeSet<String>();

    List<NavigableSet<Integer>> finalDegenerateSets = new ArrayList<>(sortedDegenerateSets.size());

    int nTrivial = 0;
    int nWeak = 0; // a degenerate set is weak if it contains a vertex that is added first

    forcliques: for (NavigableSet<Integer> set : sortedDegenerateSets) {

        // discard trivial degenerate sets
        if (set.size() < 2) {
            nTrivial++;
            continue;
        }

        // verify that we haven't already used any vertex in this degenerate set
        for (int v : set) {
            String hash = NetworkUtils.hash(v); // use MD5 for safety
            if (verticesAlreadyUsed.contains(hash)) {
                // discard this degenerate set and do NOT say we've used any of these vertices
                nWeak++;
                continue forcliques;
            }
        }

        // we haven't used any vertex in this degenerate set
        // now add all of these vertices
        // do NOT add before, or we'll add vertices we haven't used yet
        for (int v : set) {
            String hash = NetworkUtils.hash(v);
            verticesAlreadyUsed.add(hash);
        }
        finalDegenerateSets.add(set); // keep this degenerate set
    }

    logger.info("Job " + index + ": " + "Found " + finalDegenerateSets.size()
            + " strong nontrivial maximal degenerate sets found (" + nTrivial + " trivial and " + nWeak
            + " weak)");

    return finalDegenerateSets;
}

From source file:org.starnub.starnubserver.connections.player.session.PlayerSession.java

public void loadPermissions() {
    Account account = playerCharacter.getAccount();
    LinkedHashSet<String> permissions = new LinkedHashSet<>();
    if (account == null) {
        GroupsManagement.getInstance().getGROUPS().values().stream()
                .filter(group -> group.getType().equalsIgnoreCase("noaccount")).forEach(group -> {
                    permissions.addAll(group.getGROUP_PERMISSIONS());
                });/*from ww w  . j av a2s.  c  o m*/
    } else {
        List<AccountPermission> accountPermissions = AccountPermission.getAccountPermissionsByAccount(account);
        permissions.addAll(
                accountPermissions.stream().map(AccountPermission::getPermission).collect(Collectors.toList()));
        TreeMap<Integer, Group> allGroups = account.getAllGroupsOrderedByRank();
        NavigableMap<Integer, Group> navigableMap = allGroups.descendingMap();
        for (Group group : navigableMap.values()) {
            permissions.addAll(group.getGROUP_PERMISSIONS());
        }
    }
    permissions.forEach(this::addPermissionToMap);
}

From source file:org.sleuthkit.autopsy.experimental.autoingest.FileExporterSettingsPanel.java

/**
 * Find all MIME types from existing rules
 *
 * @return a Set of Strings with existing rule MIME types
 *//*from   w w w  .  jav a  2  s .  c  o  m*/
Set<String> scanRulesForMimetypes() {
    Set<String> mimeTypes = new HashSet<>();
    NavigableMap<String, Rule> nmp = exportRuleSet.getRules();
    for (Rule rule : nmp.values()) {
        if (rule.getFileMIMETypeCondition() != null) {
            mimeTypes.add(rule.getFileMIMETypeCondition().getMIMEType());
        }
    }
    return mimeTypes;
}

From source file:org.sleuthkit.autopsy.experimental.autoingest.FileExporterSettingsPanel.java

/**
 * Find all artifact types from existing rules
 *
 * @return a Set of Strings with existing rule artifact types
 *//*from www  .  j  av a  2  s  .co  m*/
Set<String> scanRulesForArtifacts() {
    Set<String> artifacts = new HashSet<>();

    NavigableMap<String, Rule> nmp = exportRuleSet.getRules();
    for (Rule rule : nmp.values()) {
        for (ArtifactCondition ac : rule.getArtifactConditions()) {
            artifacts.add(ac.getArtifactTypeName());
        }
    }
    return artifacts;
}

From source file:org.sleuthkit.autopsy.experimental.autoingest.FileExporterSettingsPanel.java

/**
 * Find all attribute types from existing rules
 *
 * @return a Set of Strings with existing rule attribute types
 *//*ww  w .  j a  v  a 2  s  .co m*/
Set<String> scanRulesForAttributes() {
    Set<String> attributes = new HashSet<>();
    NavigableMap<String, Rule> nmp = exportRuleSet.getRules();
    for (Rule rule : nmp.values()) {
        for (ArtifactCondition ac : rule.getArtifactConditions()) {
            attributes.add(ac.getAttributeTypeName());
            attributeTypeMap.put(ac.getAttributeTypeName(), ac.getAttributeValueType());
        }
    }
    return attributes;
}

From source file:org.apache.tajo.storage.hbase.HBaseScanner.java

private Datum getDatum(Result result, int fieldId) throws IOException {
    byte[] value = null;
    if (isRowKeyMappings[fieldId]) {
        value = result.getRow();//from  w  w w . j  a v a  2s.com
        if (!isBinaryColumns[fieldId] && rowKeyFieldIndexes[fieldId] >= 0) {
            int rowKeyFieldIndex = rowKeyFieldIndexes[fieldId];

            byte[][] rowKeyFields = BytesUtils.splitPreserveAllTokens(value, rowKeyDelimiter,
                    columnMapping.getNumColumns());

            if (rowKeyFields.length < rowKeyFieldIndex) {
                return NullDatum.get();
            } else {
                value = rowKeyFields[rowKeyFieldIndex];
            }
        }
    } else {
        if (isColumnKeys[fieldId]) {
            NavigableMap<byte[], byte[]> cfMap = result.getFamilyMap(mappingColumnFamilies[fieldId][0]);
            if (cfMap != null) {
                Set<byte[]> keySet = cfMap.keySet();
                if (keySet.size() == 1) {
                    try {
                        return HBaseTextSerializerDeserializer.deserialize(schemaColumns[fieldId],
                                keySet.iterator().next());
                    } catch (Exception e) {
                        LOG.error(e.getMessage(), e);
                        throw new RuntimeException(e.getMessage(), e);
                    }
                } else {
                    StringBuilder sb = new StringBuilder();
                    sb.append("[");
                    int count = 0;
                    for (byte[] eachKey : keySet) {
                        if (count > 0) {
                            sb.append(", ");
                        }
                        Datum datum = HBaseTextSerializerDeserializer.deserialize(schemaColumns[fieldId],
                                eachKey);
                        sb.append("\"").append(datum.asChars()).append("\"");
                        count++;
                        if (count > MAX_LIST_SIZE) {
                            break;
                        }
                    }
                    sb.append("]");
                    return new TextDatum(sb.toString());
                }
            }
        } else if (isColumnValues[fieldId]) {
            NavigableMap<byte[], byte[]> cfMap = result.getFamilyMap(mappingColumnFamilies[fieldId][0]);
            if (cfMap != null) {
                Collection<byte[]> valueList = cfMap.values();
                if (valueList.size() == 1) {
                    try {
                        return HBaseTextSerializerDeserializer.deserialize(schemaColumns[fieldId],
                                valueList.iterator().next());
                    } catch (Exception e) {
                        LOG.error(e.getMessage(), e);
                        throw new RuntimeException(e.getMessage(), e);
                    }
                } else {
                    StringBuilder sb = new StringBuilder();
                    sb.append("[");
                    int count = 0;
                    for (byte[] eachValue : valueList) {
                        if (count > 0) {
                            sb.append(", ");
                        }
                        Datum datum = HBaseTextSerializerDeserializer.deserialize(schemaColumns[fieldId],
                                eachValue);
                        sb.append("\"").append(datum.asChars()).append("\"");
                        count++;
                        if (count > MAX_LIST_SIZE) {
                            break;
                        }
                    }
                    sb.append("]");
                    return new TextDatum(sb.toString());
                }
            }
        } else {
            if (mappingColumnFamilies[fieldId][1] == null) {
                NavigableMap<byte[], byte[]> cfMap = result.getFamilyMap(mappingColumnFamilies[fieldId][0]);
                if (cfMap != null && !cfMap.isEmpty()) {
                    int count = 0;
                    String delim = "";

                    if (cfMap.size() == 0) {
                        return NullDatum.get();
                    } else if (cfMap.size() == 1) {
                        // If a column family is mapped without column name like "cf1:" and the number of cells is one,
                        // return value is flat format not json format.
                        NavigableMap.Entry<byte[], byte[]> entry = cfMap.entrySet().iterator().next();
                        byte[] entryKey = entry.getKey();
                        byte[] entryValue = entry.getValue();
                        if (entryKey == null || entryKey.length == 0) {
                            try {
                                if (isBinaryColumns[fieldId]) {
                                    return HBaseBinarySerializerDeserializer.deserialize(schemaColumns[fieldId],
                                            entryValue);
                                } else {
                                    return HBaseTextSerializerDeserializer.deserialize(schemaColumns[fieldId],
                                            entryValue);
                                }
                            } catch (Exception e) {
                                LOG.error(e.getMessage(), e);
                                throw new RuntimeException(e.getMessage(), e);
                            }
                        }
                    }
                    StringBuilder sb = new StringBuilder();
                    sb.append("{");
                    for (NavigableMap.Entry<byte[], byte[]> entry : cfMap.entrySet()) {
                        byte[] entryKey = entry.getKey();
                        byte[] entryValue = entry.getValue();

                        String keyText = new String(entryKey);
                        String valueText = null;
                        if (entryValue != null) {
                            try {
                                if (isBinaryColumns[fieldId]) {
                                    valueText = HBaseBinarySerializerDeserializer
                                            .deserialize(schemaColumns[fieldId], entryValue).asChars();
                                } else {
                                    valueText = HBaseTextSerializerDeserializer
                                            .deserialize(schemaColumns[fieldId], entryValue).asChars();
                                }
                            } catch (Exception e) {
                                LOG.error(e.getMessage(), e);
                                throw new RuntimeException(e.getMessage(), e);
                            }
                        }
                        sb.append(delim).append("\"").append(keyText).append("\":\"").append(valueText)
                                .append("\"");
                        delim = ", ";
                        count++;
                        if (count > MAX_LIST_SIZE) {
                            break;
                        }
                    } //end of for
                    sb.append("}");
                    return new TextDatum(sb.toString());
                } else {
                    value = null;
                }
            } else {
                value = result.getValue(mappingColumnFamilies[fieldId][0], mappingColumnFamilies[fieldId][1]);
            }
        }
    }

    if (value == null) {
        return NullDatum.get();
    } else {
        try {
            if (isBinaryColumns[fieldId]) {
                return HBaseBinarySerializerDeserializer.deserialize(schemaColumns[fieldId], value);
            } else {
                return HBaseTextSerializerDeserializer.deserialize(schemaColumns[fieldId], value);
            }
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            throw new RuntimeException(e.getMessage(), e);
        }
    }
}

From source file:org.alfresco.repo.imap.ImapServiceImpl.java

/**
 * Search for emails in specified folder depending on view mode.
 * /*from  w w w  .ja  v a2 s  .co m*/
 * Shallow list of files
 * 
 * @param contextNodeRef context folder for search
 * @param viewMode context folder view mode
 * @return list of emails that context folder contains.
 */
public FolderStatus getFolderStatus(final String userName, final NodeRef contextNodeRef,
        ImapViewMode viewMode) {
    if (logger.isDebugEnabled()) {
        logger.debug("getFolderStatus contextNodeRef=" + contextNodeRef + ", viewMode=" + viewMode);
    }

    // No need to ACL check the change token read
    String changeToken = AuthenticationUtil.runAs(new RunAsWork<String>() {
        @Override
        public String doWork() throws Exception {
            return (String) nodeService.getProperty(contextNodeRef, ImapModel.PROP_CHANGE_TOKEN);
        }
    }, AuthenticationUtil.getSystemUserName());

    Pair<String, String> cacheKey = null;
    if (changeToken != null) {
        cacheKey = new Pair<String, String>(userName, changeToken);
        this.folderCacheLock.readLock().lock();
        try {
            FolderStatus result = this.folderCache.get(cacheKey);
            if (result != null) {
                return result;
            }
        } finally {
            this.folderCacheLock.readLock().unlock();
        }
    }

    List<FileInfo> fileInfos = null;
    FileFilterMode.setClient(Client.imap);
    try {
        fileInfos = fileFolderService.listFiles(contextNodeRef);
    } finally {
        FileFilterMode.clearClient();
    }

    final NavigableMap<Long, FileInfo> currentSearch = new TreeMap<Long, FileInfo>();

    switch (viewMode) {
    case MIXED:
        for (FileInfo fileInfo : fileInfos) {
            currentSearch.put((Long) fileInfo.getProperties().get(ContentModel.PROP_NODE_DBID), fileInfo);
        }
        break;
    case ARCHIVE:
        for (FileInfo fileInfo : fileInfos) {
            if (nodeService.hasAspect(fileInfo.getNodeRef(), ImapModel.ASPECT_IMAP_CONTENT)) {
                currentSearch.put((Long) fileInfo.getProperties().get(ContentModel.PROP_NODE_DBID), fileInfo);
            }
        }
        break;
    case VIRTUAL:
        for (FileInfo fileInfo : fileInfos) {
            if (!nodeService.hasAspect(fileInfo.getNodeRef(), ImapModel.ASPECT_IMAP_CONTENT)) {
                currentSearch.put((Long) fileInfo.getProperties().get(ContentModel.PROP_NODE_DBID), fileInfo);
            }
        }
        break;
    }

    int messageCount = currentSearch.size(), recentCount = 0, unseenCount = 0, firstUnseen = 0;
    int i = 1;
    for (FileInfo fileInfo : currentSearch.values()) {
        Flags flags = getFlags(fileInfo);
        if (flags.contains(Flags.Flag.RECENT)) {
            recentCount++;
        }
        if (!flags.contains(Flags.Flag.SEEN)) {
            if (firstUnseen == 0) {
                firstUnseen = i;
            }
            unseenCount++;
        }
        i++;
    }
    // Add the IMAP folder aspect with appropriate initial values if it is not already there
    if (changeToken == null) {
        changeToken = GUID.generate();
        cacheKey = new Pair<String, String>(userName, changeToken);
        final String finalToken = changeToken;
        doAsSystem(new RunAsWork<Void>() {
            @Override
            public Void doWork() throws Exception {
                nodeService.setProperty(contextNodeRef, ImapModel.PROP_CHANGE_TOKEN, finalToken);
                nodeService.setProperty(contextNodeRef, ImapModel.PROP_MAXUID,
                        currentSearch.isEmpty() ? 0 : currentSearch.lastKey());
                return null;
            }
        });
    }
    Long uidValidity = (Long) nodeService.getProperty(contextNodeRef, ImapModel.PROP_UIDVALIDITY);
    FolderStatus result = new FolderStatus(messageCount, recentCount, firstUnseen, unseenCount,
            uidValidity == null ? 0 : uidValidity, changeToken, currentSearch);
    this.folderCacheLock.writeLock().lock();
    try {
        FolderStatus oldResult = this.folderCache.get(cacheKey);
        if (oldResult != null) {
            if (logger.isDebugEnabled()) {
                logger.debug("At end of getFolderStatus. Found info in cache, changeToken:" + changeToken);
            }

            return oldResult;
        }
        this.folderCache.put(cacheKey, result);

        if (logger.isDebugEnabled()) {
            logger.debug("At end of getFolderStatus. Found files:" + currentSearch.size() + ", changeToken:"
                    + changeToken);
        }
        return result;
    } finally {
        this.folderCacheLock.writeLock().unlock();
    }
}