Example usage for java.util TreeMap values

List of usage examples for java.util TreeMap values

Introduction

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

Prototype

public Collection<V> values() 

Source Link

Document

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

Usage

From source file:org.jenkins_ci.update_center.Main.java

/**
 * Identify the latest core, populates the htaccess redirect file, optionally download the core wars and build the
 * index.html//from  w  w w.j  av  a  2s. c  o  m
 *
 * @return the JSON for the core Jenkins
 */
protected JSONObject buildCore(MavenRepository repository, PrintWriter redirect) throws Exception {
    TreeMap<VersionNumber, HudsonWar> wars = repository.getHudsonWar();
    if (wars.isEmpty()) {
        return null;
    }

    HudsonWar latest = wars.get(wars.firstKey());
    latest.file = repository.resolve(latest.artifact);
    JSONObject core = latest.toJSON("core");
    System.out.println("core\n=> " + core);

    redirect.printf("Redirect 302 /latest/jenkins.war %s\n", latest.getURL().getPath());
    redirect.printf(
            "Redirect 302 /latest/debian/jenkins.deb http://pkg.jenkins-ci.org/debian/binary/jenkins_%s_all.deb\n",
            latest.getVersion());
    redirect.printf(
            "Redirect 302 /latest/redhat/jenkins.rpm http://pkg.jenkins-ci.org/redhat/RPMS/noarch/jenkins-%s-1.1.noarch.rpm\n",
            latest.getVersion());
    redirect.printf(
            "Redirect 302 /latest/opensuse/jenkins.rpm http://pkg.jenkins-ci.org/opensuse/RPMS/noarch/jenkins-%s-1.1.noarch.rpm\n",
            latest.getVersion());

    if (latestCoreTxt != null) {
        writeToFile(latest.getVersion().toString(), latestCoreTxt);
    }

    if (download != null) {
        // build the download server layout
        for (HudsonWar w : wars.values()) {
            stage(w, new File(download, "war/" + w.version + "/" + w.getFileName()));
        }
    }

    if (www != null) {
        buildIndex(new File(www, "download/war/"), "jenkins.war", wars.values(), "/latest/jenkins.war");
    }

    return core;
}

From source file:com.espertech.esper.rowregex.EventRowRegexNFAView.java

private List<RegexNFAStateEntry> rankEndStatesWithinPartitionByStart(List<RegexNFAStateEntry> endStates) {
    if (endStates.isEmpty()) {
        return endStates;
    }//w  ww.  java2  s.c o  m
    if (endStates.size() == 1) {
        return endStates;
    }

    TreeMap<Integer, Object> endStatesPerBeginEvent = new TreeMap<Integer, Object>();
    for (RegexNFAStateEntry entry : endStates) {
        Integer endNum = entry.getMatchBeginEventSeqNo();
        Object value = endStatesPerBeginEvent.get(endNum);
        if (value == null) {
            endStatesPerBeginEvent.put(endNum, entry);
        } else if (value instanceof List) {
            List<RegexNFAStateEntry> entries = (List<RegexNFAStateEntry>) value;
            entries.add(entry);
        } else {
            List<RegexNFAStateEntry> entries = new ArrayList<RegexNFAStateEntry>();
            entries.add((RegexNFAStateEntry) value);
            entries.add(entry);
            endStatesPerBeginEvent.put(endNum, entries);
        }
    }

    if (endStatesPerBeginEvent.size() == 1) {
        List<RegexNFAStateEntry> endStatesUnranked = (List<RegexNFAStateEntry>) endStatesPerBeginEvent.values()
                .iterator().next();
        if (matchRecognizeSpec.isAllMatches()) {
            return endStatesUnranked;
        }
        RegexNFAStateEntry chosen = rankEndStates(endStatesUnranked);
        return Collections.singletonList(chosen);
    }

    List<RegexNFAStateEntry> endStatesRanked = new ArrayList<RegexNFAStateEntry>();
    Set<Integer> keyset = endStatesPerBeginEvent.keySet();
    Integer[] keys = keyset.toArray(new Integer[keyset.size()]);
    for (Integer key : keys) {
        Object value = endStatesPerBeginEvent.remove(key);
        if (value == null) {
            continue;
        }

        RegexNFAStateEntry entryTaken;
        if (value instanceof List) {
            List<RegexNFAStateEntry> endStatesUnranked = (List<RegexNFAStateEntry>) value;
            if (endStatesUnranked.isEmpty()) {
                continue;
            }
            entryTaken = rankEndStates(endStatesUnranked);

            if (matchRecognizeSpec.isAllMatches()) {
                endStatesRanked.addAll(endStatesUnranked); // we take all matches and don't rank except to determine skip-past
            } else {
                endStatesRanked.add(entryTaken);
            }
        } else {
            entryTaken = (RegexNFAStateEntry) value;
            endStatesRanked.add(entryTaken);
        }
        // could be null as removals take place

        if (entryTaken != null) {
            if (matchRecognizeSpec.getSkip().getSkip() == MatchRecognizeSkipEnum.PAST_LAST_ROW) {
                int skipPastRow = entryTaken.getMatchEndEventSeqNo();
                removeSkippedEndStates(endStatesPerBeginEvent, skipPastRow);
            } else if (matchRecognizeSpec.getSkip().getSkip() == MatchRecognizeSkipEnum.TO_NEXT_ROW) {
                int skipPastRow = entryTaken.getMatchBeginEventSeqNo();
                removeSkippedEndStates(endStatesPerBeginEvent, skipPastRow);
            }
        }
    }

    return endStatesRanked;
}

From source file:website.openeng.anki.DeckPicker.java

public void confirmDeckDeletion(DialogFragment parent) {
    Resources res = getResources();
    if (!colIsOpen()) {
        return;/*from  ww  w  .java 2  s. com*/
    }
    if (mContextMenuDid == 1) {
        showSimpleSnackbar(R.string.delete_deck_default_deck, true);
        dismissAllDialogFragments();
        return;
    }
    // Get the number of cards contained in this deck and its subdecks
    TreeMap<String, Long> children = getCol().getDecks().children(mContextMenuDid);
    long[] dids = new long[children.size() + 1];
    dids[0] = mContextMenuDid;
    int i = 1;
    for (Long l : children.values()) {
        dids[i++] = l;
    }
    String ids = Utils.ids2str(dids);
    int cnt = getCol().getDb()
            .queryScalar("select count() from cards where did in " + ids + " or odid in " + ids);
    // Delete empty decks without warning
    if (cnt == 0) {
        deleteContextMenuDeck();
        dismissAllDialogFragments();
        return;
    }
    // Otherwise we show a warning and require confirmation
    String msg;
    String deckName = "\'" + getCol().getDecks().name(mContextMenuDid) + "\'";
    boolean isDyn = getCol().getDecks().isDyn(mContextMenuDid);
    if (isDyn) {
        msg = String.format(res.getString(R.string.delete_cram_deck_message), deckName);
    } else {
        msg = res.getQuantityString(R.plurals.delete_deck_message, cnt, deckName, cnt);
    }
    showDialogFragment(DeckPickerConfirmDeleteDeckDialog.newInstance(msg));
}

From source file:net.smart_json_database.JSONDatabase.java

private ArrayList<JSONEntity> fetchByRawSQL(SQLiteDatabase db, String sql, String[] params, Order order) {

    ArrayList<JSONEntity> list = null;
    TreeMap<String, JSONEntity> map = null;
    if (order != null && order.sortDataField()) {
        map = new TreeMap<String, JSONEntity>();
    } else {/*  ww w  .  ja v  a  2 s  .co  m*/
        list = new ArrayList<JSONEntity>();
    }

    if (order != null && order.sortDatabaseField()) {
        sql += order.sql();
    }

    Cursor c = db.rawQuery(sql, params);
    if (c.getCount() > 0) {

        c.moveToFirst();
        do {
            try {
                JSONEntity entity = JSONEntity.loadFromCursor(c);
                getTagsForJSONEntity(entity, db);
                getHasManyRelationsForJSONEntity(entity, db);
                getBelongsToRelationsForJSONEntity(entity, db);
                if (list != null) {
                    list.add(entity);
                } else {
                    map.put(entity.getString(order.collation()), entity);
                }
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                //e.printStackTrace();
            }
        } while (c.moveToNext());
    }
    c.close();
    if (map != null) {
        list = new ArrayList<JSONEntity>(map.values());
    }
    return list;
}

From source file:org.ejbca.ui.web.admin.services.EditServiceManagedBean.java

/**
 * // ww w  .  j  a  v a 2s.co m
 * 
 * @return a {@link List} of {@link SelectItem}s containing the ID's and names of all ENDENTITY, ROOTCA and SUBCA 
 * (and HARDTOKEN if available) certificate profiles current admin is authorized to.
 */
public Collection<SelectItem> getCertificateProfiles() {
    TreeMap<String, SelectItem> certificateProfiles = new TreeMap<String, SelectItem>();

    final Integer[] certificateProfileTypes = new Integer[] { CertificateConstants.CERTTYPE_ENDENTITY,
            CertificateConstants.CERTTYPE_ROOTCA, CertificateConstants.CERTTYPE_SUBCA };

    for (Integer certificateProfileType : certificateProfileTypes) {
        Collection<Integer> profiles = ejb.getCertificateProfileSession()
                .getAuthorizedCertificateProfileIds(getAdmin(), certificateProfileType);
        for (Integer certificateProfile : profiles) {
            String profileName = ejb.getCertificateProfileSession()
                    .getCertificateProfileName(certificateProfile);
            certificateProfiles.put(profileName.toLowerCase(),
                    new SelectItem(certificateProfile.toString(), profileName));
        }
    }
    //Only add hardprofile certificate profiles if enabled. 
    if (((GlobalConfiguration) ejb.getGlobalConfigurationSession()
            .getCachedConfiguration(GlobalConfiguration.GLOBAL_CONFIGURATION_ID)).getIssueHardwareTokens()) {
        Collection<Integer> profiles = ejb.getCertificateProfileSession()
                .getAuthorizedCertificateProfileIds(getAdmin(), CertificateConstants.CERTTYPE_HARDTOKEN);
        for (Integer certificateProfile : profiles) {
            String profileName = ejb.getCertificateProfileSession()
                    .getCertificateProfileName(certificateProfile);
            certificateProfiles.put(profileName.toLowerCase(),
                    new SelectItem(certificateProfile.toString(), profileName));
        }
    }

    return certificateProfiles.values();
}

From source file:de.tudarmstadt.ukp.uby.integration.alignment.xml.transform.sensealignments.FnWnSenseAlignmentXml.java

/**
 * Collect UBY SenseIds for the aligned senses based on synsetId and lemma
 * for WordNet and based on lexical unit id for FrameNet
 *
 * @throws IOException//  w w w . j av  a2s . com
 */
@Override
public void toAlignmentXml(XmlMeta metadata) throws IOException {
    System.err.println("to Alignment Xml");
    TreeMap<String, Source> sourceMap = new TreeMap<>();
    List<String[]> data = null;
    data = readAlignmentFile();
    int counter = 0; // input sense pairs
    int found = 0; // output sense pairs

    // iterate over alignment entries
    for (String[] d : data) {
        counter++;
        // show progress:
        if ((counter % 1000) == 0) {
            logger.info("# processed alignments: " + counter);
        }

        // use FrameNet sense externalReference (lexical unit Id)
        String fnSenseId = d[0]; // SOURCE

        Source source = null;
        if (sourceMap.containsKey(fnSenseId)) {
            source = sourceMap.get(fnSenseId);
        } else {
            source = new Source();
        }
        source.ref = fnSenseId;
        List<Target> targets = new LinkedList<Target>();
        // get WordNet sense by Synset Offset and Lemma
        List<Sense> wnSenses = uby.getSensesByWNSynsetId(d[1]);
        // List<Sense> wnSenses = uby.wordNetSenses(partOfSpeech, offset);

        for (Sense wnSense : wnSenses) {
            Target target = new Target();
            target.ref = wnSense.getId();
            Decision decision = new Decision();
            decision.confidence = SenseAlignmentGenericXml.DEFAULTCONFSCORE;
            decision.value = true;
            // decision.src = metadata.decisiontypes.get(0).name;
            target.decision = decision;
            targets.add(target);
            found++;
        }
        if (targets.size() > 0) {
            source.targets = targets;
            sourceMap.put(source.ref, source);
        }
    }

    writer.writeMetaData(metadata);
    Alignments alignments = new Alignments();
    alignments.source = new LinkedList<>();
    alignments.source.addAll(sourceMap.values());
    writer.writeAlignments(alignments);
    writer.close();
    System.err.println("Alignments in: " + counter + " OUT" + found);

    logger.info("Alignments in: " + counter + "Alignments out: " + found);
}

From source file:org.openmicroscopy.shoola.agents.measurement.view.MeasurementViewerModel.java

/**
 * Sets the ROI for the pixels set. Returns <code>true</code>
 * if the ROI are compatible with the image, <code>false</code> otherwise.
 *
 * @param input   The value to set.// w w w .  j a v a2  s  .c o  m
 * @return See above.
 * @throws ROICreationException If the ROI cannot be created.
 * @throws NoSuchROIException    If the ROI does not exist.
 * @throws ParsingException      Thrown when an error occurred
 *                         while parsing the stream.
 */
boolean setROI(InputStream input) throws ROICreationException, NoSuchROIException, ParsingException {
    state = MeasurementViewer.READY;
    if (input == null)
        return false;
    List<ROI> roiList = roiComponent.loadROI(input);
    if (roiList == null)
        return false;
    Iterator<ROI> i = roiList.iterator();
    ROI roi;
    TreeMap<Coord3D, ROIShape> shapeList;
    Iterator<ROIShape> shapeIterator;
    ROIShape shape;
    Coord3D c;
    int sizeZ = pixels.getSizeZ();
    int sizeT = pixels.getSizeT();

    boolean b = true;
    while (i.hasNext()) {
        roi = i.next();
        shapeList = roi.getShapes();
        shapeIterator = shapeList.values().iterator();
        while (shapeIterator.hasNext()) {
            shape = shapeIterator.next();
            c = shape.getCoord3D();
            if (c.getTimePoint() > sizeT) {
                b = false;
                break;
            }
            if (c.getZSection() > sizeZ) {
                b = false;
                break;
            }
        }
    }
    if (!b) {
        i = roiList.iterator();
        while (i.hasNext()) {
            roi = i.next();
            roiComponent.deleteROI(roi.getID());
        }
        return false;
    }
    notifyDataChanged(true);
    return true;
}

From source file:org.apache.hadoop.yarn.server.timeline.RollingLevelDBTimelineStore.java

@Override
public TimelinePutResponse put(TimelineEntities entities) {
    if (LOG.isDebugEnabled()) {
        LOG.debug("Starting put");
    }/*from   ww  w.j a v a 2 s.c o  m*/
    TimelinePutResponse response = new TimelinePutResponse();
    TreeMap<Long, RollingWriteBatch> entityUpdates = new TreeMap<Long, RollingWriteBatch>();
    TreeMap<Long, RollingWriteBatch> indexUpdates = new TreeMap<Long, RollingWriteBatch>();

    long entityCount = 0;
    long indexCount = 0;

    try {

        for (TimelineEntity entity : entities.getEntities()) {
            entityCount += putEntities(entityUpdates, indexUpdates, entity, response);
        }

        for (RollingWriteBatch entityUpdate : entityUpdates.values()) {
            entityUpdate.write();
        }

        for (RollingWriteBatch indexUpdate : indexUpdates.values()) {
            indexUpdate.write();
        }

    } finally {

        for (RollingWriteBatch entityRollingWriteBatch : entityUpdates.values()) {
            entityRollingWriteBatch.close();
        }
        for (RollingWriteBatch indexRollingWriteBatch : indexUpdates.values()) {
            indexRollingWriteBatch.close();
        }
    }
    if (LOG.isDebugEnabled()) {
        LOG.debug("Put " + entityCount + " new leveldb entity entries and " + indexCount
                + " new leveldb index entries from " + entities.getEntities().size() + " timeline entities");
    }
    return response;
}

From source file:net.dv8tion.jda.core.entities.EntityBuilder.java

public Message createMessage(JSONObject jsonObject, MessageChannel chan, boolean exceptionOnMissingUser) {
    final long id = jsonObject.getLong("id");
    String content = !jsonObject.isNull("content") ? jsonObject.getString("content") : "";

    JSONObject author = jsonObject.getJSONObject("author");
    final long authorId = author.getLong("id");
    boolean fromWebhook = jsonObject.has("webhook_id");

    MessageImpl message = new MessageImpl(id, chan, fromWebhook).setContent(content)
            .setTime(!jsonObject.isNull("timestamp") ? OffsetDateTime.parse(jsonObject.getString("timestamp"))
                    : OffsetDateTime.now())
            .setMentionsEveryone(/*from  w w w. ja  v a2 s . co  m*/
                    !jsonObject.isNull("mention_everyone") && jsonObject.getBoolean("mention_everyone"))
            .setTTS(!jsonObject.isNull("tts") && jsonObject.getBoolean("tts"))
            .setPinned(!jsonObject.isNull("pinned") && jsonObject.getBoolean("pinned"));
    if (chan instanceof PrivateChannel) {
        if (authorId == api.getSelfUser().getIdLong())
            message.setAuthor(api.getSelfUser());
        else
            message.setAuthor(((PrivateChannel) chan).getUser());
    } else if (chan instanceof Group) {
        UserImpl user = (UserImpl) api.getUserMap().get(authorId);
        if (user == null)
            user = (UserImpl) api.getFakeUserMap().get(authorId);
        if (user == null && fromWebhook)
            user = (UserImpl) createFakeUser(author, false);
        if (user == null) {
            if (exceptionOnMissingUser)
                throw new IllegalArgumentException(MISSING_USER); //Specifically for MESSAGE_CREATE
            else
                user = (UserImpl) createFakeUser(author, false); //Any message creation that isn't MESSAGE_CREATE
        }
        message.setAuthor(user);

        //If the message was sent by a cached fake user, lets update it.
        if (user.isFake() && !fromWebhook) {
            user.setName(author.getString("username")).setDiscriminator(author.get("discriminator").toString())
                    .setAvatarId(author.isNull("avatar") ? null : author.getString("avatar"))
                    .setBot(author.has("bot") && author.getBoolean("bot"));
        }
    } else {
        GuildImpl guild = (GuildImpl) ((TextChannel) chan).getGuild();
        Member member = guild.getMembersMap().get(authorId);
        User user = member != null ? member.getUser() : null;
        if (user != null)
            message.setAuthor(user);
        else if (fromWebhook || !exceptionOnMissingUser)
            message.setAuthor(createFakeUser(author, false));
        else
            throw new IllegalArgumentException(MISSING_USER);
    }

    List<Message.Attachment> attachments = new LinkedList<>();
    if (!jsonObject.isNull("attachments")) {
        JSONArray jsonAttachments = jsonObject.getJSONArray("attachments");
        for (int i = 0; i < jsonAttachments.length(); i++) {
            JSONObject jsonAttachment = jsonAttachments.getJSONObject(i);
            attachments.add(new Message.Attachment(jsonAttachment.getString("id"),
                    jsonAttachment.getString("url"), jsonAttachment.getString("proxy_url"),
                    jsonAttachment.getString("filename"), jsonAttachment.getInt("size"),
                    jsonAttachment.has("height") ? jsonAttachment.getInt("height") : 0,
                    jsonAttachment.has("width") ? jsonAttachment.getInt("width") : 0, api));
        }
    }
    message.setAttachments(attachments);

    List<MessageEmbed> embeds = new LinkedList<>();
    JSONArray jsonEmbeds = jsonObject.getJSONArray("embeds");
    for (int i = 0; i < jsonEmbeds.length(); i++) {
        embeds.add(createMessageEmbed(jsonEmbeds.getJSONObject(i)));
    }
    message.setEmbeds(embeds);

    if (!jsonObject.isNull("edited_timestamp"))
        message.setEditedTime(OffsetDateTime.parse(jsonObject.getString("edited_timestamp")));

    if (jsonObject.has("reactions")) {
        JSONArray reactions = jsonObject.getJSONArray("reactions");
        List<MessageReaction> list = new LinkedList<>();
        for (int i = 0; i < reactions.length(); i++) {
            JSONObject obj = reactions.getJSONObject(i);
            JSONObject emoji = obj.getJSONObject("emoji");

            final Long emojiId = emoji.isNull("id") ? null : emoji.getLong("id");
            String emojiName = emoji.getString("name");

            boolean self = obj.has("self") && obj.getBoolean("self");
            int count = obj.getInt("count");
            Emote emote = null;
            if (emojiId != null) {
                emote = api.getEmoteById(emojiId);
                if (emote == null)
                    emote = new EmoteImpl(emojiId, api).setName(emojiName);
            }
            MessageReaction.ReactionEmote reactionEmote;
            if (emote == null)
                reactionEmote = new MessageReaction.ReactionEmote(emojiName, null, api);
            else
                reactionEmote = new MessageReaction.ReactionEmote(emote);
            list.add(new MessageReaction(chan, reactionEmote, message.getIdLong(), self, count));
        }
        message.setReactions(list);
    }

    if (message.isFromType(ChannelType.TEXT)) {
        TextChannel textChannel = message.getTextChannel();
        TreeMap<Integer, User> mentionedUsers = new TreeMap<>();
        if (!jsonObject.isNull("mentions")) {
            JSONArray mentions = jsonObject.getJSONArray("mentions");
            for (int i = 0; i < mentions.length(); i++) {
                JSONObject mention = mentions.getJSONObject(i);
                User u = api.getUserById(mention.getLong("id"));
                if (u != null) {
                    //We do this to properly order the mentions. The array given by discord is out of order sometimes.

                    String mentionId = mention.getString("id");
                    int index = content.indexOf("<@" + mentionId + ">");
                    if (index < 0)
                        index = content.indexOf("<@!" + mentionId + ">");
                    mentionedUsers.put(index, u);
                }
            }
        }
        message.setMentionedUsers(new LinkedList<User>(mentionedUsers.values()));

        TreeMap<Integer, Role> mentionedRoles = new TreeMap<>();
        if (!jsonObject.isNull("mention_roles")) {
            JSONArray roleMentions = jsonObject.getJSONArray("mention_roles");
            for (int i = 0; i < roleMentions.length(); i++) {
                String roleId = roleMentions.getString(i);
                Role r = textChannel.getGuild().getRoleById(roleId);
                if (r != null) {
                    int index = content.indexOf("<@&" + roleId + ">");
                    mentionedRoles.put(index, r);
                }
            }
        }
        message.setMentionedRoles(new LinkedList<Role>(mentionedRoles.values()));

        List<TextChannel> mentionedChannels = new LinkedList<>();
        TLongObjectMap<TextChannel> chanMap = ((GuildImpl) textChannel.getGuild()).getTextChannelsMap();
        Matcher matcher = channelMentionPattern.matcher(content);
        while (matcher.find()) {
            TextChannel channel = chanMap.get(Long.parseLong(matcher.group(1)));
            if (channel != null && !mentionedChannels.contains(channel)) {
                mentionedChannels.add(channel);
            }
        }
        message.setMentionedChannels(mentionedChannels);
    }
    return message;
}

From source file:org.kuali.kra.common.committee.bo.CommitteeScheduleBase.java

public List<PS> getLatestProtocolSubmissions() {
    TreeMap<String, PS> latestSubmissions = new TreeMap<String, PS>();
    List<PS> returnList = new ArrayList<PS>();
    for (PS submission : protocolSubmissions) {
        // gonna do something a little hacktacular here... in some cases, protocol and/or protocol number might not be set.
        // in that case, go ahead and pass submissions on to caller
        if (submission.getProtocol() == null
                || StringUtils.isEmpty(submission.getProtocol().getProtocolNumber())) {
            returnList.add(submission);/*from w ww  .ja  v a2 s . c  om*/
        } else {
            String key = submission.getProtocol().getProtocolNumber();
            if (submission.getProtocol().isActive()) {
                PS existingSubmission = latestSubmissions.get(key);
                if (existingSubmission == null) {
                    latestSubmissions.put(key, submission);
                } else {
                    int newInt = submission.getSequenceNumber().intValue();
                    int existInt = existingSubmission.getSequenceNumber().intValue();
                    int newSubNum = submission.getSubmissionNumber().intValue();
                    int existSubNum = existingSubmission.getSubmissionNumber().intValue();
                    if ((newInt > existInt) || ((newInt == existInt) && (newSubNum > existSubNum))) {
                        latestSubmissions.put(key, submission);
                    }
                }
            }
        }
    }
    returnList.addAll(latestSubmissions.values());
    return returnList;
}