Example usage for java.util TreeMap containsKey

List of usage examples for java.util TreeMap containsKey

Introduction

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

Prototype

public boolean containsKey(Object key) 

Source Link

Document

Returns true if this map contains a mapping for the specified key.

Usage

From source file:org.languagetool.gui.LanguageToolSupport.java

private void addDisabledRulesToMenu(List<Rule> disabledRules, JMenu menu) {
    if (disabledRules.size() <= MAX_RULES_NO_CATEGORY_MENU) {
        createRulesMenu(menu, disabledRules);
        return;//  www . jav  a 2  s  .  com
    }

    TreeMap<String, ArrayList<Rule>> categories = new TreeMap<>();
    for (Rule rule : disabledRules) {
        if (!categories.containsKey(rule.getCategory().getName())) {
            categories.put(rule.getCategory().getName(), new ArrayList<>());
        }
        categories.get(rule.getCategory().getName()).add(rule);
    }

    JMenu parent = menu;
    int count = 0;
    for (String category : categories.keySet()) {
        count++;
        JMenu submenu = new JMenu(category);
        parent.add(submenu);
        createRulesMenu(submenu, categories.get(category));

        if (categories.keySet().size() <= MAX_CATEGORIES_PER_MENU) {
            continue;
        }

        //if menu contains MAX_CATEGORIES_PER_MENU-1, add a `more` menu
        //but only if the remain entries are more than one
        if ((count % (MAX_CATEGORIES_PER_MENU - 1) == 0) && (categories.keySet().size() - count > 1)) {
            JMenu more = new JMenu(messages.getString("guiActivateRuleMoreCategories"));
            parent.add(more);
            parent = more;
        }
    }
}

From source file:org.jahia.ajax.gwt.helper.PublicationHelper.java

public Map<PublicationWorkflow, WorkflowDefinition> createPublicationWorkflows(
        List<GWTJahiaPublicationInfo> all) {
    final TreeMap<String, List<GWTJahiaPublicationInfo>> infosListByWorflowGroup = new TreeMap<String, List<GWTJahiaPublicationInfo>>();

    Map<String, String> workflowGroupToKey = new HashMap<String, String>();
    List<String> keys = new ArrayList<String>();

    for (GWTJahiaPublicationInfo info : all) {
        String workflowGroup = info.getWorkflowGroup();
        if (!infosListByWorflowGroup.containsKey(workflowGroup)) {
            infosListByWorflowGroup.put(workflowGroup, new ArrayList<GWTJahiaPublicationInfo>());
        }/*from  ww  w  .  ja  v a  2 s.  c om*/
        infosListByWorflowGroup.get(workflowGroup).add(info);
        if (info.getWorkflowDefinition() != null) {
            workflowGroupToKey.put(info.getWorkflowGroup(), info.getWorkflowDefinition());
            if (!keys.contains(info.getWorkflowDefinition())) {
                keys.add(info.getWorkflowDefinition());
            }
        }
    }

    Map<PublicationWorkflow, WorkflowDefinition> result = new LinkedHashMap<PublicationWorkflow, WorkflowDefinition>();

    Map<String, WorkflowDefinition> workflows = new HashMap<String, WorkflowDefinition>();
    for (String wf : keys) {
        WorkflowDefinition w = workflowService.getWorkflowDefinition(StringUtils.substringBefore(wf, ":"),
                StringUtils.substringAfter(wf, ":"), null);
        workflows.put(wf, w);
    }

    for (Map.Entry<String, List<GWTJahiaPublicationInfo>> entry : infosListByWorflowGroup.entrySet()) {
        result.put(new PublicationWorkflow(entry.getValue()),
                workflows.get(workflowGroupToKey.get(entry.getKey())));
    }

    return result;
}

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

/**
 * Gets the grouped relationships./*from ww w.  ja v  a 2  s .c  o m*/
 *
 * @return the grouped relationships
 */
public final TreeMap<String, Collection<RelationshipBean>> getGroupedRelationships() {

    TreeMap<String, Collection<RelationshipBean>> groupedRelationships = new TreeMap<String, Collection<RelationshipBean>>();

    if (this.getRelationships() != null) {
        for (RelationshipBean relationship : this.getRelationships()) {
            String key = "Unnamed";
            Collection<RelationshipBean> rels = new ArrayList<RelationshipBean>();

            if (relationship.getRelatedPerson() != null) {
                PersonBean person = relationship.getRelatedPerson();
                key = person.getLastName() + " " + person.getFirstName() + " " + person.getPersonIdentifier();
            }
            if (groupedRelationships.containsKey(key)) {
                rels = groupedRelationships.get(key);
            }
            rels.add(relationship);

            groupedRelationships.put(key, rels);
        }
    }
    return groupedRelationships;
}

From source file:com.eurelis.opencms.workflows.ui.toolobject.WorkflowMenuItemLoader.java

/**
 * Get the list of all collected Menu items, sorted by the index position
 * /*  w w  w  . j a  va  2 s.c  o  m*/
 * @return the list of WorkflowMenuItem that must be displayed
 */
public List<WorkflowMenuItem> getMenuItems() {
    // Create the map that will store the WorkflowMenuItem by position
    TreeMap<Float, WorkflowMenuItem> sortedMapByPosition = new TreeMap<Float, WorkflowMenuItem>();

    LOGGER.debug(ErrorFormatter.formatMap(_mapOfItems, "WF | _mapOfItems"));

    /*
     * add the map elements into the sorted map if none object with the same
     * position exists
     */
    Iterator<WorkflowMenuItem> mapOfItemIterator = this._mapOfItems.values().iterator();
    while (mapOfItemIterator.hasNext()) {
        WorkflowMenuItem workflowMenuItem = mapOfItemIterator.next();
        Float position = new Float(workflowMenuItem.get_position());
        // check if an object with such position exist
        if (!sortedMapByPosition.containsKey(position)) {
            sortedMapByPosition.put(position, workflowMenuItem);
        } else {
            // if two object with same position exists, then the second one
            // is not added into the map of object to display and a warning
            // message is return to the user.
            LOGGER.warn("WF | Two objects with position " + position + " exists. The menu "
                    + workflowMenuItem.get_name() + " will not be displayed");
        }
    }

    // return the list of menu item sorted by position
    return new ArrayList<WorkflowMenuItem>(sortedMapByPosition.values());
}

From source file:se.trixon.mapollage.Operation.java

private void addPath() {
    Collections.sort(mLineNodes, (LineNode o1, LineNode o2) -> o1.getDate().compareTo(o2.getDate()));

    mPathFolder = KmlFactory.createFolder().withName(Dict.PATH_GFX.toString());
    mPathGapFolder = KmlFactory.createFolder().withName(Dict.PATH_GAP_GFX.toString());

    String pattern = getPattern(mProfilePath.getSplitBy());
    SimpleDateFormat dateFormat = new SimpleDateFormat(pattern);

    TreeMap<String, ArrayList<LineNode>> map = new TreeMap<>();

    mLineNodes.forEach((node) -> {//from www . ja va  2 s. c o  m
        String key = dateFormat.format(node.getDate());
        if (!map.containsKey(key)) {
            map.put(key, new ArrayList<>());
        }
        map.get(key).add(node);
    });

    //Add paths
    for (ArrayList<LineNode> nodes : map.values()) {
        if (nodes.size() > 1) {
            Placemark path = mPathFolder.createAndAddPlacemark().withName(LineNode.getName(nodes));

            Style pathStyle = path.createAndAddStyle();
            pathStyle.createAndSetLineStyle().withColor("ff0000ff").withWidth(mProfilePath.getWidth());

            LineString line = path.createAndSetLineString().withExtrude(false).withTessellate(true);

            nodes.forEach((node) -> {
                line.addToCoordinates(node.getLon(), node.getLat());
            });
        }
    }

    //Add path gap
    ArrayList<LineNode> previousNodes = null;
    for (ArrayList<LineNode> nodes : map.values()) {
        if (previousNodes != null) {
            Placemark path = mPathGapFolder.createAndAddPlacemark()
                    .withName(LineNode.getName(previousNodes, nodes));

            Style pathStyle = path.createAndAddStyle();
            pathStyle.createAndSetLineStyle().withColor("ff00ffff").withWidth(mProfilePath.getWidth());

            LineString line = path.createAndSetLineString().withExtrude(false).withTessellate(true);

            LineNode prevLast = previousNodes.get(previousNodes.size() - 1);
            LineNode currentFirst = nodes.get(0);

            line.addToCoordinates(prevLast.getLon(), prevLast.getLat());
            line.addToCoordinates(currentFirst.getLon(), currentFirst.getLat());
        }
        previousNodes = nodes;
    }
}

From source file:ark.model.SupervisedModelCreg.java

@Override
protected AssignmentList toParseInternalHelper(AssignmentList internalAssignments) {
    TreeMap<Double, List<String>> sortedWeights = new TreeMap<Double, List<String>>();
    File modelFile = new File(this.modelPath.getValue());

    if (!modelFile.exists())
        return internalAssignments;

    try {//from ww  w . j  a  v  a 2 s  .c o  m
        BufferedReader br = new BufferedReader(new FileReader(modelFile));
        String line = null;

        while ((line = br.readLine()) != null) {
            String[] lineParts = line.split("\t");
            Double value = null;
            if (lineParts.length < 3)
                continue;
            try {
                value = Math.abs(Double.parseDouble(lineParts[2]));
            } catch (NumberFormatException e) {
                continue;
            }

            if (!sortedWeights.containsKey(value))
                sortedWeights.put(value, new ArrayList<String>());
            sortedWeights.get(value).add(line);
        }

        br.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

    NavigableMap<Double, List<String>> descendingWeights = sortedWeights.descendingMap();
    int i = 0;
    for (List<String> lines : descendingWeights.values()) {
        for (String line : lines) {
            internalAssignments
                    .add(Assignment.assignmentTyped(null, Context.ARRAY_STR, "w-" + i, Obj.stringValue(line)));

            i++;
        }
    }

    return internalAssignments;
}

From source file:org.jasig.portlet.proxy.mvc.portlet.gateway.GatewayPortletEditController.java

/**
 * Return a map of GatewayPreferences for each field whose value is replaced with a portlet preference value.
 * @param entry GatewayEntry/*from  w w w .  j  av a  2s  . c o  m*/
 * @param prefs Portlet Preferences
 * @return Map of <porlet preference name, GatewayPreference>
 */
private TreeMap<String, GatewayPreference> getPreferencesForEntry(final GatewayEntry entry,
        final PortletPreferences prefs) {

    TreeMap<String, GatewayPreference> rslt = new TreeMap<String, GatewayPreference>();

    for (Map.Entry<HttpContentRequestImpl, List<IPreInterceptor>> requestEntry : entry.getContentRequests()
            .entrySet()) {
        final HttpContentRequestImpl contentRequest = requestEntry.getKey();
        Map<String, IFormField> parameters = contentRequest.getParameters();
        for (String logicalFieldName : parameters.keySet()) {
            IFormField parameter = parameters.get(logicalFieldName);
            for (String parameterValue : parameter.getValues()) {
                if (parameterValue.matches(preferencesRegex)) {
                    String preferenceName = parameterValue;

                    // If there are multiple entries with the same preference name, just use the first one
                    if (!rslt.containsKey(preferenceName)) {
                        // retrieve the preference and stuff the value here....
                        String preferredValue = prefs.getValue(preferenceName, "");
                        if (parameter.getSecured() && StringUtils.isNotBlank(preferredValue)
                                && stringEncryptionService != null) {
                            preferredValue = stringEncryptionService.decrypt(preferredValue);
                        }
                        rslt.put(preferenceName, new GatewayPreference(entry.getName(), logicalFieldName,
                                preferenceName, preferredValue, parameter.getSecured()));
                    }
                }
            }
        }
    }

    return rslt;

}

From source file:org.motechproject.mobile.omi.manager.SMSMessageFormatter.java

public String formatDefaulterMessage(Care[] cares, CareMessageGroupingStrategy groupingStrategy) {
    String result = "";

    // Map of patient to the care the defaulted for
    TreeMap<String, List<String>> patientDefaulters = new TreeMap<String, List<String>>();

    // Map of community to the defaulted patients in that community
    TreeMap<String, TreeMap<String, List<String>>> communityDefaulterMap = new TreeMap<String, TreeMap<String, List<String>>>();

    if (cares != null) {
        for (Care c : cares) {
            for (Patient p : c.getPatients()) {
                String lastName = (p.getLastName() == null) ? "" : p.getLastName();
                String preferredName = checkPreferredName(p);

                String patient = String.format("%s %s, %s", preferredName, lastName, p.getMotechId());

                if (!patientDefaulters.containsKey(patient)) {
                    patientDefaulters.put(patient, new ArrayList<String>());
                }//from   w w w  .j  a v  a  2s.c  o m

                List<String> defaultedFor = patientDefaulters.get(patient);
                defaultedFor.add(c.getName());

                if (p.getCommunity() != null) {
                    if (!communityDefaulterMap.containsKey(p.getCommunity())) {
                        communityDefaulterMap.put(p.getCommunity(), new TreeMap<String, List<String>>());
                    }

                    TreeMap<String, List<String>> communityDefaulters = communityDefaulterMap
                            .get(p.getCommunity());
                    communityDefaulters.put(patient, defaultedFor);
                }
            }
        }
    }

    if (groupingStrategy == CareMessageGroupingStrategy.NONE) {
        result = formatDefaulterMessage(patientDefaulters);
    } else {
        result = formatCommunityDefaulterMessage(communityDefaulterMap);
    }

    return ("Defaulter Alerts" + result).trim();
}

From source file:com.redhat.rhn.taskomatic.task.DailySummary.java

/**
 * DO NOT CALL FROM OUTSIDE THIS CLASS. Renders the actions email message
 * @param actions list of recent actions
 * @return the actions email message/*from w  w  w  . j  a  v a2 s  . c  o m*/
 */
public String renderActionsMessage(List<ActionMessage> actions) {

    int longestActionLength = HEADER_SPACER;
    int longestStatusLength = 0;
    StringBuilder hdr = new StringBuilder();
    StringBuilder body = new StringBuilder();
    StringBuilder legend = new StringBuilder();
    StringBuilder msg = new StringBuilder();
    LinkedHashSet<String> statusSet = new LinkedHashSet();
    TreeMap<String, Map<String, Integer>> nonErrataActions = new TreeMap();
    TreeMap<String, Map<String, Integer>> errataActions = new TreeMap();
    TreeMap<String, String> errataSynopsis = new TreeMap();

    legend.append(LocalizationService.getInstance().getMessage("taskomatic.daily.errata"));
    legend.append("\n\n");

    for (ActionMessage am : actions) {

        if (!statusSet.contains(am.getStatus())) {
            statusSet.add(am.getStatus());
            if (am.getStatus().length() > longestStatusLength) {
                longestStatusLength = am.getStatus().length();
            }
        }

        if (am.getType().equals(ERRATA_UPDATE)) {
            String advisoryKey = ERRATA_INDENTION + am.getAdvisory();

            if (!errataActions.containsKey(advisoryKey)) {
                errataActions.put(advisoryKey, new HashMap());
                if (advisoryKey.length() + HEADER_SPACER > longestActionLength) {
                    longestActionLength = advisoryKey.length() + HEADER_SPACER;
                }
            }
            Map<String, Integer> counts = errataActions.get(advisoryKey);
            counts.put(am.getStatus(), am.getCount());

            if (am.getAdvisory() != null && !errataSynopsis.containsKey(am.getAdvisory())) {
                errataSynopsis.put(am.getAdvisory(), am.getSynopsis());
            }
        } else {
            if (!nonErrataActions.containsKey(am.getType())) {
                nonErrataActions.put(am.getType(), new HashMap());
                if (am.getType().length() + HEADER_SPACER > longestActionLength) {
                    longestActionLength = am.getType().length() + HEADER_SPACER;
                }
            }
            Map<String, Integer> counts = nonErrataActions.get(am.getType());
            counts.put(am.getStatus(), am.getCount());
        }

    }

    hdr.append(StringUtils.repeat(" ", longestActionLength));
    for (String status : statusSet) {
        hdr.append(status + StringUtils.repeat(" ", (longestStatusLength + ERRATA_SPACER) - status.length()));
    }

    if (!errataActions.isEmpty()) {
        body.append(ERRATA_UPDATE + ":" + "\n");
    }
    StringBuffer formattedErrataActions = renderActionTree(longestActionLength, longestStatusLength, statusSet,
            errataActions);
    body.append(formattedErrataActions);

    for (String advisory : errataSynopsis.keySet()) {
        legend.append(ERRATA_INDENTION + advisory + ERRATA_INDENTION + errataSynopsis.get(advisory) + "\n");
    }

    StringBuffer formattedNonErrataActions = renderActionTree(longestActionLength, longestStatusLength,
            statusSet, nonErrataActions);
    body.append(formattedNonErrataActions);

    // finally put all this together
    msg.append(hdr.toString());
    msg.append("\n");
    msg.append(body.toString());
    msg.append("\n\n");
    if (!errataSynopsis.isEmpty()) {
        msg.append(legend.toString());
    }
    return msg.toString();
}

From source file:org.openecomp.sdc.validation.impl.validators.EcompGuideLineValidator.java

@SuppressWarnings("unchecked")
private void validateNovaServerResourceMetaData(String fileName, String resourceId, Resource resource,
        GlobalValidationContext globalValidationContext) {
    Map<String, Object> novaServerProp = resource.getProperties();
    Object novaServerPropMetadata;
    if (MapUtils.isNotEmpty(novaServerProp)) {
        novaServerPropMetadata = novaServerProp.get("metadata");
        if (novaServerPropMetadata == null) {
            globalValidationContext.addMessage(fileName, ErrorLevel.WARNING,
                    ErrorMessagesFormatBuilder.getErrorWithParameters(
                            Messages.MISSING_NOVA_SERVER_METADATA.getErrorMessage(), resourceId));
        } else if (novaServerPropMetadata instanceof Map) {
            TreeMap<String, Object> propertyMap = new TreeMap(new Comparator<String>() {

                @Override//from   ww w. ja va2  s.c  om
                public int compare(String o1, String o2) {
                    return o1.compareToIgnoreCase(o2);
                }

                @Override
                public boolean equals(Object obj) {
                    return false;
                }
            });
            propertyMap.putAll((Map) novaServerPropMetadata);
            if (!propertyMap.containsKey("vf_module_id")) {
                globalValidationContext.addMessage(fileName, ErrorLevel.WARNING,
                        ErrorMessagesFormatBuilder.getErrorWithParameters(
                                Messages.MISSING_NOVA_SERVER_VF_MODULE_ID.getErrorMessage(), resourceId));
            }
            if (!propertyMap.containsKey("vnf_id")) {
                globalValidationContext.addMessage(fileName, ErrorLevel.WARNING,
                        ErrorMessagesFormatBuilder.getErrorWithParameters(
                                Messages.MISSING_NOVA_SERVER_VNF_ID.getErrorMessage(), resourceId));
            }
        }
    }
}