Example usage for java.util TreeMap keySet

List of usage examples for java.util TreeMap keySet

Introduction

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

Prototype

public Set<K> keySet() 

Source Link

Document

Returns a Set view of the keys contained in this map.

Usage

From source file:com.cloud.upgrade.DatabaseUpgradeChecker.java

protected void upgrade(CloudStackVersion dbVersion, CloudStackVersion currentVersion) {
    s_logger.info("Database upgrade must be performed from " + dbVersion + " to " + currentVersion);

    final DbUpgrade[] upgrades = calculateUpgradePath(dbVersion, currentVersion);

    boolean supportsRollingUpgrade = true;
    for (DbUpgrade upgrade : upgrades) {
        if (!upgrade.supportsRollingUpgrade()) {
            supportsRollingUpgrade = false;
            break;
        }/*  w  w  w  . ja  v a2s. c o  m*/
    }

    if (!supportsRollingUpgrade && false) { // FIXME: Needs to detect if there are management servers running
        // ClusterManagerImpl.arePeersRunning(null)) {
        String errorMessage = "Unable to run upgrade because the upgrade sequence does not support rolling update and there are other management server nodes running";
        s_logger.error(errorMessage);
        throw new CloudRuntimeException(errorMessage);
    }

    for (DbUpgrade upgrade : upgrades) {
        s_logger.debug("Running upgrade " + upgrade.getClass().getSimpleName() + " to upgrade from "
                + upgrade.getUpgradableVersionRange()[0] + "-" + upgrade.getUpgradableVersionRange()[1] + " to "
                + upgrade.getUpgradedVersion());
        TransactionLegacy txn = TransactionLegacy.open("Upgrade");
        txn.start();
        try {
            Connection conn;
            try {
                conn = txn.getConnection();
            } catch (SQLException e) {
                String errorMessage = "Unable to upgrade the database";
                s_logger.error(errorMessage, e);
                throw new CloudRuntimeException(errorMessage, e);
            }
            File[] scripts = upgrade.getPrepareScripts();
            if (scripts != null) {
                for (File script : scripts) {
                    runScript(conn, script);
                }
            }

            upgrade.performDataMigration(conn);
            boolean upgradeVersion = true;

            if (upgrade.getUpgradedVersion().equals("2.1.8")) {
                // we don't have VersionDao in 2.1.x
                upgradeVersion = false;
            } else if (upgrade.getUpgradedVersion().equals("2.2.4")) {
                try (PreparedStatement pstmt = conn
                        .prepareStatement("SELECT * FROM version WHERE version='2.2.4'");
                        ResultSet rs = pstmt.executeQuery();) {
                    // specifically for domain vlan update from 2.1.8 to 2.2.4
                    if (rs.next()) {
                        upgradeVersion = false;
                    }
                } catch (SQLException e) {
                    throw new CloudRuntimeException("Unable to update the version table", e);
                }
            }

            if (upgradeVersion) {
                VersionVO version = new VersionVO(upgrade.getUpgradedVersion());
                _dao.persist(version);
            }

            txn.commit();
        } catch (CloudRuntimeException e) {
            String errorMessage = "Unable to upgrade the database";
            s_logger.error(errorMessage, e);
            throw new CloudRuntimeException(errorMessage, e);
        } finally {
            txn.close();
        }
    }

    if (true) { // FIXME Needs to detect if management servers are running
        // !ClusterManagerImpl.arePeersRunning(trimmedCurrentVersion)) {
        s_logger.info("Cleaning upgrades because all management server are now at the same version");
        TreeMap<String, List<DbUpgrade>> upgradedVersions = new TreeMap<String, List<DbUpgrade>>();

        for (DbUpgrade upgrade : upgrades) {
            String upgradedVerson = upgrade.getUpgradedVersion();
            List<DbUpgrade> upgradeList = upgradedVersions.get(upgradedVerson);
            if (upgradeList == null) {
                upgradeList = new ArrayList<DbUpgrade>();
            }
            upgradeList.add(upgrade);
            upgradedVersions.put(upgradedVerson, upgradeList);
        }

        for (String upgradedVersion : upgradedVersions.keySet()) {
            List<DbUpgrade> versionUpgrades = upgradedVersions.get(upgradedVersion);
            VersionVO version = _dao.findByVersion(upgradedVersion, Step.Upgrade);
            s_logger.debug("Upgrading to version " + upgradedVersion + "...");

            TransactionLegacy txn = TransactionLegacy.open("Cleanup");
            try {
                if (version != null) {
                    for (DbUpgrade upgrade : versionUpgrades) {
                        s_logger.info("Cleanup upgrade " + upgrade.getClass().getSimpleName()
                                + " to upgrade from " + upgrade.getUpgradableVersionRange()[0] + "-"
                                + upgrade.getUpgradableVersionRange()[1] + " to "
                                + upgrade.getUpgradedVersion());

                        txn.start();

                        Connection conn;
                        try {
                            conn = txn.getConnection();
                        } catch (SQLException e) {
                            String errorMessage = "Unable to cleanup the database";
                            s_logger.error(errorMessage, e);
                            throw new CloudRuntimeException(errorMessage, e);
                        }

                        File[] scripts = upgrade.getCleanupScripts();
                        if (scripts != null) {
                            for (File script : scripts) {
                                runScript(conn, script);
                                s_logger.debug("Cleanup script " + script.getAbsolutePath()
                                        + " is executed successfully");
                            }
                        }
                        txn.commit();
                    }

                    txn.start();
                    version.setStep(Step.Complete);
                    s_logger.debug("Upgrade completed for version " + upgradedVersion);
                    version.setUpdated(new Date());
                    _dao.update(version.getId(), version);
                    txn.commit();
                }
            } finally {
                txn.close();
            }
        }
    }

}

From source file:com.netxforge.oss2.config.AmiPeerFactory.java

/**
 * Combine specific and range elements so that AMIPeerFactory has to spend
 * less time iterating all these elements.
 * TODO This really should be pulled up into PeerFactory somehow, but I'm not sure how (given that "Definition" is different for both
 * SNMP and AMI.  Maybe some sort of visitor methodology would work.  The basic logic should be fine as it's all IP address manipulation
 *
 * @throws UnknownHostException/*from  w  w w .j  av a 2 s  .  c  om*/
 */
void optimize() throws UnknownHostException {
    getWriteLock().lock();

    try {
        // First pass: Remove empty definition elements
        for (final Iterator<Definition> definitionsIterator = m_config.getDefinitionCollection()
                .iterator(); definitionsIterator.hasNext();) {
            final Definition definition = definitionsIterator.next();
            if (definition.getSpecificCount() == 0 && definition.getRangeCount() == 0) {
                LogUtils.debugf(this, "optimize: Removing empty definition element");
                definitionsIterator.remove();
            }
        }

        // Second pass: Replace single IP range elements with specific elements
        for (Definition definition : m_config.getDefinitionCollection()) {
            for (Iterator<Range> rangesIterator = definition.getRangeCollection().iterator(); rangesIterator
                    .hasNext();) {
                Range range = rangesIterator.next();
                if (range.getBegin().equals(range.getEnd())) {
                    definition.addSpecific(range.getBegin());
                    rangesIterator.remove();
                }
            }
        }

        // Third pass: Sort specific and range elements for improved XML
        // readability and then combine them into fewer elements where possible
        for (final Definition definition : m_config.getDefinitionCollection()) {
            // Sort specifics
            final TreeMap<InetAddress, String> specificsMap = new TreeMap<InetAddress, String>(
                    new InetAddressComparator());
            for (final String specific : definition.getSpecificCollection()) {
                specificsMap.put(InetAddressUtils.getInetAddress(specific), specific.trim());
            }

            // Sort ranges
            final TreeMap<InetAddress, Range> rangesMap = new TreeMap<InetAddress, Range>(
                    new InetAddressComparator());
            for (final Range range : definition.getRangeCollection()) {
                rangesMap.put(InetAddressUtils.getInetAddress(range.getBegin()), range);
            }

            // Combine consecutive specifics into ranges
            InetAddress priorSpecific = null;
            Range addedRange = null;
            for (final InetAddress specific : specificsMap.keySet()) {
                if (priorSpecific == null) {
                    priorSpecific = specific;
                    continue;
                }

                if (BigInteger.ONE.equals(InetAddressUtils.difference(specific, priorSpecific))
                        && InetAddressUtils.inSameScope(specific, priorSpecific)) {
                    if (addedRange == null) {
                        addedRange = new Range();
                        addedRange.setBegin(InetAddressUtils.toIpAddrString(priorSpecific));
                        rangesMap.put(priorSpecific, addedRange);
                        specificsMap.remove(priorSpecific);
                    }

                    addedRange.setEnd(InetAddressUtils.toIpAddrString(specific));
                    specificsMap.remove(specific);
                } else {
                    addedRange = null;
                }

                priorSpecific = specific;
            }

            // Move specifics to ranges
            for (final InetAddress specific : new ArrayList<InetAddress>(specificsMap.keySet())) {
                for (final InetAddress begin : new ArrayList<InetAddress>(rangesMap.keySet())) {

                    if (!InetAddressUtils.inSameScope(begin, specific)) {
                        continue;
                    }

                    if (InetAddressUtils.toInteger(begin).subtract(BigInteger.ONE)
                            .compareTo(InetAddressUtils.toInteger(specific)) > 0) {
                        continue;
                    }

                    final Range range = rangesMap.get(begin);

                    final InetAddress end = InetAddressUtils.getInetAddress(range.getEnd());

                    if (InetAddressUtils.toInteger(end).add(BigInteger.ONE)
                            .compareTo(InetAddressUtils.toInteger(specific)) < 0) {
                        continue;
                    }

                    if (InetAddressUtils.toInteger(specific).compareTo(InetAddressUtils.toInteger(begin)) >= 0
                            && InetAddressUtils.toInteger(specific)
                                    .compareTo(InetAddressUtils.toInteger(end)) <= 0) {
                        specificsMap.remove(specific);
                        break;
                    }

                    if (InetAddressUtils.toInteger(begin).subtract(BigInteger.ONE)
                            .equals(InetAddressUtils.toInteger(specific))) {
                        rangesMap.remove(begin);
                        rangesMap.put(specific, range);
                        range.setBegin(InetAddressUtils.toIpAddrString(specific));
                        specificsMap.remove(specific);
                        break;
                    }

                    if (InetAddressUtils.toInteger(end).add(BigInteger.ONE)
                            .equals(InetAddressUtils.toInteger(specific))) {
                        range.setEnd(InetAddressUtils.toIpAddrString(specific));
                        specificsMap.remove(specific);
                        break;
                    }
                }
            }

            // Combine consecutive ranges
            Range priorRange = null;
            InetAddress priorBegin = null;
            InetAddress priorEnd = null;
            for (final Iterator<InetAddress> rangesIterator = rangesMap.keySet().iterator(); rangesIterator
                    .hasNext();) {
                final InetAddress beginAddress = rangesIterator.next();
                final Range range = rangesMap.get(beginAddress);
                final InetAddress endAddress = InetAddressUtils.getInetAddress(range.getEnd());

                if (priorRange != null) {
                    if (InetAddressUtils.inSameScope(beginAddress, priorEnd) && InetAddressUtils
                            .difference(beginAddress, priorEnd).compareTo(BigInteger.ONE) <= 0) {
                        priorBegin = new InetAddressComparator().compare(priorBegin, beginAddress) < 0
                                ? priorBegin
                                : beginAddress;
                        priorRange.setBegin(InetAddressUtils.toIpAddrString(priorBegin));
                        priorEnd = new InetAddressComparator().compare(priorEnd, endAddress) > 0 ? priorEnd
                                : endAddress;
                        priorRange.setEnd(InetAddressUtils.toIpAddrString(priorEnd));

                        rangesIterator.remove();
                        continue;
                    }
                }

                priorRange = range;
                priorBegin = beginAddress;
                priorEnd = endAddress;
            }

            // Update changes made to sorted maps
            definition.setSpecific(specificsMap.values().toArray(new String[0]));
            definition.setRange(rangesMap.values().toArray(new Range[0]));
        }
    } finally {
        getWriteLock().unlock();
    }
}

From source file:com.sfs.whichdoctor.dao.RelationshipDAOImpl.java

/**
 * Builds the inherited map./*from  w  ww . j a v  a 2  s.c o m*/
 *
 * @param relationshipClass the relationship class
 * @param relationshipMap the relationship map
 * @return the tree map
 */
private TreeMap<Integer, RelationshipBean> buildInheritedMap(final String relationshipClass,
        final TreeMap<Integer, RelationshipBean> relationshipMap) {

    TreeMap<Integer, RelationshipBean> fullSupervisorMap = new TreeMap<Integer, RelationshipBean>();

    // Load the supervisor type map
    TreeMap<Integer, String> types = null;
    try {
        types = loadSupervisorRelationships(relationshipClass);
    } catch (WhichDoctorDaoException wde) {
        dataLogger.error("Error loading the supervisor object types: " + wde.getMessage());
    }

    int maxHierarchy = 0;
    if (types != null) {
        dataLogger.debug("Supervisor relationships: " + types.size());
        for (Integer hierarchy : types.keySet()) {
            // Set the maxiumum hierarchy value by getting the last key
            if (hierarchy > maxHierarchy) {
                maxHierarchy = hierarchy;
            }
        }
    }
    dataLogger.debug("Maximum hierarchy: " + maxHierarchy);

    for (Integer hierarchy : types.keySet()) {
        final String typeName = types.get(hierarchy);
        if (dataLogger.isDebugEnabled()) {
            dataLogger.debug("Hierarchy key is: " + hierarchy);
            dataLogger.debug("Type is: " + typeName);
        }
        if (!relationshipMap.containsKey(hierarchy)) {
            // If the relationship is missing we need to find one
            RelationshipBean newSup = null;

            for (int i = 1; i < maxHierarchy + 1; i++) {
                dataLogger.debug("Looking up key: " + i);
                if (newSup == null && relationshipMap.containsKey(i)) {
                    RelationshipBean exSup = relationshipMap.get(i);
                    newSup = exSup.clone();
                    newSup.setRelationshipType(typeName);
                }
            }
            if (newSup != null) {
                if (dataLogger.isDebugEnabled()) {
                    dataLogger.debug("Adding a new supervisor");
                    dataLogger.debug("GUID: " + newSup.getGUID());
                    dataLogger.debug("Identifier: " + newSup.getIdentifier());
                    dataLogger.debug("Relationship Class: " + newSup.getRelationshipClass());
                    dataLogger.debug("Relationship Type: " + newSup.getRelationshipType());
                }
                fullSupervisorMap.put(hierarchy, newSup);
            }
        } else {
            RelationshipBean extSup = relationshipMap.get(hierarchy);
            if (dataLogger.isDebugEnabled()) {
                dataLogger.debug("Adding an existing supervisor");
                dataLogger.debug("GUID: " + extSup.getGUID());
                dataLogger.debug("Identifier: " + extSup.getIdentifier());
                dataLogger.debug("Relationship Class: " + extSup.getRelationshipClass());
                dataLogger.debug("Relationship Type: " + extSup.getRelationshipType());
            }
            fullSupervisorMap.put(hierarchy, extSup);
        }
    }
    return fullSupervisorMap;
}

From source file:version1.Neo4jTest.Wiki2Neo4j.java

void addNodes2Db(String type, String string_to_parse, TreeMap<String, TreeMap> Object) {
    // START SNIPPET: startDb

    //        graphDb = new GraphDatabaseFactory().newEmbeddedDatabase(DB_PATH);
    //        registerShutdownHook(graphDb);

    org.neo4j.graphdb.Label label = DynamicLabel.label(type);

    try (Transaction tx = graphDb.beginTx()) {
        Index<Node> nodeIndex = graphDb.index().forNodes(type);
        //IndexManager indexMan = graphDb.index();
        //Index<Node> index = indexMan.forNodes("timeline1");

        //Node cube = graphDb.createNode((org.neo4j.graphdb.Label) DynamicLabel.label("BasicCube"));

        for (String key : Object.keySet()) {
            TreeMap<String, String> BCAttribut = Object.get(key);
            Node node = graphDb.createNode(label);

            //checking               

            String name = BCAttribut.get(string_to_parse);

            node.setProperty("name", key);

            addNodeProperty(BCAttribut, "ExcludeState", node);
            addNodeProperty(BCAttribut, "Datentyp", node);
            addNodeProperty(BCAttribut, "Feldlnge", node);
            addNodeProperty(BCAttribut, "Beschreibende Attribute", node);
            addNodeProperty(BCAttribut, "Algorithmus/Entstehung/Bildung", node);
            addNodeProperty(BCAttribut, "Bildung", node);

            //Smart Cubes
            addNodeProperty(BCAttribut, "Gesetzliche Grundlage", node);
            addNodeProperty(BCAttribut, "Melderkreis", node);
            addNodeProperty(BCAttribut, "Meldeperiodizitt", node);
            addNodeProperty(BCAttribut, "Meldetermin", node);
            addNodeProperty(BCAttribut, "Meldeperiode", node);
            addNodeProperty(BCAttribut, "Meldewhrung", node);
            addNodeProperty(BCAttribut, "Formale Beschreibung", node);
            addNodeProperty(BCAttribut, "Kommt vor in/wird verwendet fr", node);

            nodeIndex.add(node, type, "xyz");
            if (name != null)
                string_node.put(name, node);

            //System.out.println(":"+name+":");

            if (name != null)
                node.setProperty(string_to_parse, name);
            //Zu Testzwecken
            //relationship = cube.createRelationshipTo(node, RelTypes.MEMBER_OF );
            //relationship.setProperty( "message", "brave Neo4j " );
        }//from w  w w  . j  av a2 s .  co m
        tx.success();
    }

    //graphDb.shutdown();
}

From source file:hydrograph.ui.dataviewer.filter.FilterHelper.java

/**
 * Refresh group selections./*from w  ww . j  a  va 2s  . c o  m*/
 * 
 * @param tableViewer
 *            the table viewer
 * @param indexOfRow
 *            the index of row
 * @param addOrDeleteRow
 *            the add or delete row
 * @param groupSelectionMap
 *            the group selection map
 * @return true, if successful
 */
public boolean refreshGroupSelections(TableViewer tableViewer, int indexOfRow, String addOrDeleteRow,
        TreeMap<Integer, List<List<Integer>>> groupSelectionMap) {
    boolean isRemoveColumn = false;
    for (int key : groupSelectionMap.keySet()) {
        List<List<Integer>> groups = groupSelectionMap.get(key);
        boolean isNewIndexAddedorRemoved = false;
        for (List<Integer> grp : groups) {
            List<Integer> tempGrp = new ArrayList<>(grp);
            if ("ADD".equalsIgnoreCase(addOrDeleteRow)) {
                for (int i = 0; i < grp.size(); i++) {
                    if (grp.get(i) >= indexOfRow) {
                        grp.set(i, grp.get(i) + 1);
                    }
                }
                if (tempGrp.contains(indexOfRow)) {
                    if (!isNewIndexAddedorRemoved && tempGrp.get(0) != indexOfRow) {//other than starting index then add row.
                        grp.add(tempGrp.indexOf(indexOfRow), indexOfRow);
                        isNewIndexAddedorRemoved = true;
                    }
                }
            } else if ("DEL".equalsIgnoreCase(addOrDeleteRow)) {
                if (tempGrp.contains(indexOfRow)) {
                    if (!isNewIndexAddedorRemoved) {//other than starting index then add row.
                        grp.remove(grp.indexOf(indexOfRow));
                        if (grp.size() == 1) {
                            grp.clear();
                        }
                        if (rearrangeGroupsAfterDeleteRow(groupSelectionMap, grp)
                                && groupSelectionMap.lastKey() != key) {
                            grp.clear();
                        }
                        List tempList = new ArrayList<>();
                        for (List lst : groupSelectionMap.get(key)) {
                            tempList.addAll(lst);
                        }
                        if (tempList.isEmpty()) {
                            isRemoveColumn = true;
                        }
                    }
                    isNewIndexAddedorRemoved = true;
                }
                for (int i = 0; i < grp.size(); i++) {
                    if (grp.get(i) >= indexOfRow) {
                        grp.set(i, grp.get(i) - 1);
                    }
                }
            }
            tempGrp.clear();
        }
    }
    return isRemoveColumn;
}

From source file:org.rhq.enterprise.gui.admin.role.AddLdapGroupsFormPrepareAction.java

/** Method duplicates pageControl/pagination mechanism for LdapGroup data. This data has not been moved into the
 *  database yet so the PageList and PageControl mechanism does not yet work properly.
 *  There are only two columns so the pagination code uses Maps and Sorted Lists for efficient sorting.
 *
 * @param pagedGroupData Pagelist of Maps to be populated.
 * @param fullGroupData Full list of Maps available for paging
 * @param pc the pagination control from the web session reflecting user selections.
 * @return Pagelist includes datapoints matching pagination information passed in.
 *//* w w w. ja  v a2  s .c  om*/
private PageList<Map<String, String>> paginateLdapGroupData(PageList<Map<String, String>> pagedGroupData,
        PageList<Map<String, String>> fullGroupData, PageControl pc) {
    if (pagedGroupData == null) { //
        pagedGroupData = new PageList<Map<String, String>>();
    }
    if ((fullGroupData == null) || (fullGroupData.isEmpty())) {
        return pagedGroupData;
    }
    if (pc == null) {
        pc = new PageControl(0, 15);
    } //npe defense

    //determine count to return up to 15|30|45 and page index
    int returnAmount = pc.getPageSize();
    int returnIndex = pc.getPageNumber();

    //determine sort order
    PageOrdering sortOrder = pc.getPrimarySortOrder();
    if (sortOrder == null) {
        sortOrder = PageOrdering.ASC;
        pc.setPrimarySortOrder(sortOrder);//reset on pc
    }

    //determine which column to sort on
    String sortColumn = pc.getPrimarySortColumn();
    if (sortColumn == null) {
        sortColumn = "lg.name";
        pc.setPrimarySort(sortColumn, sortOrder);//reset on pc
    }

    //now sort based off these values and populate sizedAvailableGroups accordingly
    ArrayList<Map<String, String>> groupsValues = fullGroupData.getValues();

    //store maps based off the keys and sort()
    Map<Integer, Map> groupLookup = new HashMap<Integer, Map>();
    TreeMap<String, Integer> groupNames = new TreeMap<String, Integer>();
    TreeMap<String, Integer> groupDescriptions = new TreeMap<String, Integer>();
    for (int i = 0; i < groupsValues.size(); i++) {
        Map<String, String> entry = groupsValues.get(i);
        Integer key = Integer.valueOf(i);
        groupLookup.put(key, entry);
        groupNames.put(entry.get("name"), key);
        groupDescriptions.put(entry.get("description"), key);
    }

    //do calculations to determine how many sorted values to return.
    int start, end;
    start = (int) (returnIndex * returnAmount);
    end = start + returnAmount;
    //        PageList<Map<String, String>> sizedAvailableGroups = new PageList<Map<String, String>>();

    //detect sort order
    boolean descending = false;
    if (PageOrdering.DESC == sortOrder) {
        descending = true;
    }
    //use sort column to determine which list to use
    if (sortColumn.equalsIgnoreCase("lg.name")) {
        int i = 0;
        List<String> keyList;

        if (descending) {
            keyList = new ArrayList<String>(groupNames.keySet());
            Collections.reverse(keyList);
        } else {
            keyList = new ArrayList<String>(groupNames.keySet());
            Collections.sort(keyList);
        }
        for (String key : keyList) {
            if ((i >= start) && (i < end)) {
                pagedGroupData.add(groupLookup.get(groupNames.get(key)));
            }
            i++;
        }
    } else {
        int i = 0;
        List<String> keyList;
        if (descending) {
            keyList = new ArrayList<String>(groupDescriptions.keySet());
            Collections.reverse(keyList);
        } else {
            keyList = new ArrayList<String>(groupDescriptions.keySet());
            Collections.sort(keyList);
        }
        for (String key : keyList) {
            if ((i >= start) && (i < end)) {
                pagedGroupData.add(groupLookup.get(groupDescriptions.get(key)));
            }
            i++;
        }
    }

    return pagedGroupData;
}

From source file:net.spfbl.core.Core.java

public static String getSequence(TreeMap<String, Boolean> map, String demiliter) {
    if (map == null) {
        return null;
    } else if (demiliter == null) {
        return null;
    } else if (map.isEmpty()) {
        return null;
    } else {//w w  w . ja v a2  s  .co m
        StringBuilder builder = new StringBuilder();
        for (String key : map.keySet()) {
            boolean value = map.get(key);
            if (builder.length() > 0) {
                builder.append(demiliter);
            }
            builder.append(key);
            builder.append('=');
            builder.append(value);
        }
        return builder.toString();
    }
}

From source file:com.att.aro.core.packetanalysis.impl.VideoUsageAnalysisImpl.java

private void validateManifests() {
    if (videoUsage != null) {
        TreeMap<Double, AROManifest> manifestMap = videoUsage.getAroManifestMap();
        Set<Double> manifestKeySet = manifestMap.keySet();
        for (Double key : manifestKeySet) {
            AROManifest manifest = manifestMap.get(key);
            manifest.setValid(true);/*  w w  w . jav  a  2s. com*/
            if (manifest.getVideoEventList().isEmpty()) {
                manifest.setValid(false);
            }
            for (VideoEvent event : manifest.getVideoEventList().values()) {
                if (event.getSegment() < 0) {
                    manifest.setValid(false);
                }
            }
        }
    }
}

From source file:org.kuali.kfs.module.purap.document.web.struts.AccountsPayableActionBase.java

/**
 * Builds and asks questions which require text input by the user for a payment request or a credit memo.
 *
 * @param mapping An ActionMapping/*www . j  av a 2  s.c  o  m*/
 * @param form An ActionForm
 * @param request The HttpServletRequest
 * @param response The HttpServletResponse
 * @param questionType A String used to distinguish which question is being asked
 * @param notePrefix A String explaining what action was taken, to be prepended to the note containing the reason, which gets
 *        written to the document
 * @param operation A one-word String description of the action to be taken, to be substituted into the message. (Can be an
 *        empty String for some messages.)
 * @param messageKey A (whole) key to the message which will appear on the question screen
 * @param questionsAndCallbacks A TreeMap associating the type of question to be asked and the type of callback which should
 *        happen in that case
 * @param messagePrefix The most general part of a key to a message text to be retrieved from ConfigurationService,
 *        Describes a collection of questions.
 * @param redirect An ActionForward to return to if done with questions
 * @return An ActionForward
 * @throws Exception
 */
protected ActionForward askQuestionWithInput(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response, String questionType, String notePrefix, String operation,
        String messageKey, TreeMap<String, PurQuestionCallback> questionsAndCallbacks, String messagePrefix,
        ActionForward redirect) throws Exception {
    KualiDocumentFormBase kualiDocumentFormBase = (KualiDocumentFormBase) form;
    AccountsPayableDocumentBase apDocument = (AccountsPayableDocumentBase) kualiDocumentFormBase.getDocument();

    String question = request.getParameter(KFSConstants.QUESTION_INST_ATTRIBUTE_NAME);
    String reason = request.getParameter(KFSConstants.QUESTION_REASON_ATTRIBUTE_NAME);
    String noteText = "";

    ConfigurationService kualiConfiguration = SpringContext.getBean(ConfigurationService.class);
    String firstQuestion = questionsAndCallbacks.firstKey();
    PurQuestionCallback callback = null;
    Iterator questions = questionsAndCallbacks.keySet().iterator();
    String mapQuestion = null;
    String key = null;

    // Start in logic for confirming the close.
    if (question == null) {
        key = getQuestionProperty(messageKey, messagePrefix, kualiConfiguration, firstQuestion);
        String message = StringUtils.replace(key, "{0}", operation);

        // Ask question if not already asked.
        return this.performQuestionWithInput(mapping, form, request, response, firstQuestion, message,
                KFSConstants.CONFIRMATION_QUESTION, questionType, "");
    } else {
        // find callback for this question
        while (questions.hasNext()) {
            mapQuestion = (String) questions.next();

            if (StringUtils.equals(mapQuestion, question)) {
                callback = questionsAndCallbacks.get(mapQuestion);
                break;
            }
        }
        key = getQuestionProperty(messageKey, messagePrefix, kualiConfiguration, mapQuestion);

        Object buttonClicked = request.getParameter(KFSConstants.QUESTION_CLICKED_BUTTON);
        if (question.equals(mapQuestion) && buttonClicked.equals(ConfirmationQuestion.NO)) {
            // If 'No' is the button clicked, just reload the doc

            String nextQuestion = null;
            // ask another question if more left
            if (questions.hasNext()) {
                nextQuestion = (String) questions.next();
                key = getQuestionProperty(messageKey, messagePrefix, kualiConfiguration, nextQuestion);

                return this.performQuestionWithInput(mapping, form, request, response, nextQuestion, key,
                        KFSConstants.CONFIRMATION_QUESTION, questionType, "");
            } else {

                return mapping.findForward(KFSConstants.MAPPING_BASIC);
            }
        }
        // Have to check length on value entered.
        String introNoteMessage = notePrefix + KFSConstants.BLANK_SPACE;

        // Build out full message.
        noteText = introNoteMessage + reason;
        int noteTextLength = noteText.length();

        // Get note text max length from DD.
        int noteTextMaxLength = SpringContext.getBean(DataDictionaryService.class)
                .getAttributeMaxLength(Note.class, KFSConstants.NOTE_TEXT_PROPERTY_NAME).intValue();
        if (StringUtils.isBlank(reason) || (noteTextLength > noteTextMaxLength)) {
            // Figure out exact number of characters that the user can enter.
            int reasonLimit = noteTextMaxLength - noteTextLength;
            if (reason == null) {
                // Prevent a NPE by setting the reason to a blank string.
                reason = "";
            }

            return this.performQuestionWithInputAgainBecauseOfErrors(mapping, form, request, response,
                    mapQuestion, key, KFSConstants.CONFIRMATION_QUESTION, questionType, "", reason,
                    PurapKeyConstants.ERROR_PAYMENT_REQUEST_REASON_REQUIRED,
                    KFSConstants.QUESTION_REASON_ATTRIBUTE_NAME, new Integer(reasonLimit).toString());
        }
    }

    // make callback
    if (ObjectUtils.isNotNull(callback)) {
        AccountsPayableDocument refreshedApDocument = callback.doPostQuestion(apDocument, noteText);
        kualiDocumentFormBase.setDocument(refreshedApDocument);
    }
    String nextQuestion = null;
    // ask another question if more left
    if (questions.hasNext()) {
        nextQuestion = (String) questions.next();
        key = getQuestionProperty(messageKey, messagePrefix, kualiConfiguration, nextQuestion);

        return this.performQuestionWithInput(mapping, form, request, response, nextQuestion, key,
                KFSConstants.CONFIRMATION_QUESTION, questionType, "");
    }

    return redirect;
}

From source file:com.sfs.whichdoctor.beans.PersonBean.java

/**
 * Gets the curriculum year.// ww  w . j  a va2s  .  c  o  m
 *
 * @return the curriculum year
 */
public final String getCurriculumYear() {

    TreeMap<Integer, Integer> years = new TreeMap<Integer, Integer>();

    if (this.getSpecialtyList() != null) {
        for (SpecialtyBean specialty : this.getSpecialtyList()) {
            if (StringUtils.equalsIgnoreCase(specialty.getStatus(), "In training")
                    && specialty.getTrainingProgramYear() > 0) {
                years.put(specialty.getTrainingProgramYear(), 1);
            }
        }
    }

    String value = "";
    int count = 1;

    for (int year : years.keySet()) {
        if (count > 1) {
            if (count == years.size()) {
                value += " and ";
            } else {
                value += ", ";
            }
        }
        value += String.valueOf(year);
        ++count;
    }
    return value;
}