Example usage for java.util NavigableMap descendingMap

List of usage examples for java.util NavigableMap descendingMap

Introduction

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

Prototype

NavigableMap<K, V> descendingMap();

Source Link

Document

Returns a reverse order view of the mappings contained in this map.

Usage

From source file:org.jahia.modules.tagcloud.taglibs.TagCloudTag.java

/**
 * Generates the tag cloud associated with the specified bound component, including only tags with a cardinality above the specified minimum cardinality for inclusion, up to
 * the specified maximum number of tags.
 *
 * @param boundComponent                 the component for which we want to generate a tag cloud.
 * @param minimumCardinalityForInclusion minimum cardinality (i.e. number of tagged elements) for a tag to be included in the tag cloud
 * @param maxNumberOfTags                maximum number of tags included in the cloud, keeping most numerous tags first (i.e. tags with lower cardinality will be excluded from
 *                                       the cloud first)
 * @param currentQuery                   the currently applied facet query
 * @param renderContext                  the {@link org.jahia.services.render.RenderContext} in which this tag cloud is being generated
 * @throws RepositoryException if something went wrong accessing the JCR repository while processing the bound component's tags
 *//*from  w  w  w  .  j  av a2 s  . co m*/
public void generateTagCloud(JCRNodeWrapper boundComponent, int minimumCardinalityForInclusion,
        int maxNumberOfTags, String currentQuery, RenderContext renderContext) throws RepositoryException {

    // applied facets
    final Map<String, List<KeyValue>> appliedFacets = Functions.getAppliedFacetFilters(currentQuery);

    // query
    QueryResultWrapper filteredTags = getNodesWithFacets(boundComponent, minimumCardinalityForInclusion,
            maxNumberOfTags, appliedFacets);

    if (!filteredTags.isFacetResultsEmpty()) {
        // map recording which unapplied tags have which cardinality, sorted in reverse cardinality order (most numerous tags first, being more important)
        final NavigableMap<Integer, Set<Tag>> tagCounts = new TreeMap<Integer, Set<Tag>>();
        // applied tags facets
        final List<KeyValue> appliedTagsValues = appliedFacets.get(Constants.TAGS);
        // list of applied tags
        List<Tag> appliedTagsList = Collections.emptyList();
        if (appliedTagsValues != null) {
            appliedTagsList = new ArrayList<Tag>(appliedTagsValues.size());
        }

        // action URL start
        final String facetURLParameterName = getFacetURLParameterName(boundComponent.getName());
        final String url = renderContext.getURLGenerator().getMainResource();
        final String actionURLStart = url + "?" + facetURLParameterName + "=";

        // process the query results
        final FacetField tags = filteredTags.getFacetField(Constants.TAGS);
        final List<FacetField.Count> values = tags.getValues();
        int totalCardinality = 0;
        for (FacetField.Count value : values) {
            // facet query should only return tags with a cardinality greater than the one we specified
            final int count = (int) value.getCount();

            // facets return value of the j:tags property which is a weak reference to a node so we need to load it to get its name
            final String tagUUID = value.getName();
            final JCRNodeWrapper tagNode = boundComponent.getSession().getNodeByUUID(tagUUID);
            final String name = tagNode.getDisplayableName();

            // create tag
            final Tag tag = new Tag(name, count, tagUUID, value);

            if (!Functions.isFacetValueApplied(value, appliedFacets)) {
                // only add tag to cloud if it's not applied

                // increase totalCardinality with the current tag's count, this is used to compute the tag's weight in the cloud
                totalCardinality += count;

                // add tag to tag counts
                Set<Tag> associatedTags = tagCounts.get(count);
                if (associatedTags == null) {
                    associatedTags = new HashSet<Tag>();
                    tagCounts.put(count, associatedTags);
                }
                associatedTags.add(tag);
            } else {
                // get KeyValue for current tag
                KeyValue current = null;
                for (KeyValue tagsValue : appliedTagsValues) {
                    if (tagUUID.equals(tagsValue.getKey())) {
                        current = tagsValue;
                        break;
                    }
                }

                tag.setDeleteActionURL(
                        getActionURL(actionURLStart, Functions.getDeleteFacetUrl(current, currentQuery)));
                appliedTagsList.add(tag);
            }
        }
        Tag.setTotalCardinality(totalCardinality);

        // extract only the maxNumberOfTags most numerous tags
        final Map<String, Tag> tagCloud = new LinkedHashMap<String, Tag>(maxNumberOfTags);
        boolean stop = false;
        for (Set<Tag> tags1 : tagCounts.descendingMap().values()) {
            if (stop) {
                break;
            }

            for (Tag tag : tags1) {
                if (tagCloud.size() < maxNumberOfTags) {
                    String result = getActionURL(actionURLStart,
                            Functions.getFacetDrillDownUrl(tag.getFacetValue(), currentQuery));
                    tag.setActionURL(result);
                    tagCloud.put(tag.getName(), tag);
                } else {
                    stop = true;
                    break;
                }
            }
        }

        // put cloud and applied tags in their respective page context variables
        pageContext.setAttribute(cloudVar, tagCloud, PageContext.REQUEST_SCOPE);
        pageContext.setAttribute(appliedTags, appliedTagsList, PageContext.REQUEST_SCOPE);
    }
}

From source file:com.google.gwt.emultest.java.util.TreeMapTest.java

public void testDescendingMap() {
    K[] keys = getSortedKeys();//from   ww w.  ja  va  2s .com
    V[] values = getSortedValues();
    NavigableMap<K, V> map = createNavigableMap();
    map.put(keys[0], values[0]);

    NavigableMap<K, V> descendingMap = map.descendingMap();
    _assertEquals(descendingMap, map.descendingMap());

    map.put(keys[1], values[1]);
    _assertEquals(map, descendingMap.descendingMap());
    _assertEquals(reverseCollection(map.entrySet()), descendingMap.entrySet());

    descendingMap.put(keys[2], values[2]);
    _assertEquals(reverseCollection(map.entrySet()), descendingMap.entrySet());
    _assertEquals(map.entrySet(), descendingMap.descendingMap().entrySet());

    descendingMap.remove(keys[1]);
    _assertEquals(reverseCollection(map.entrySet()), descendingMap.entrySet());

    descendingMap.clear();
    assertEquals(0, descendingMap.size());
    assertEquals(0, map.size());

    map.put(keys[0], values[0]);
    map.put(keys[1], values[1]);
    map.put(keys[2], values[2]);
    assertEquals(3, descendingMap.size());

    NavigableMap<K, V> headMap = descendingMap.headMap(keys[1], false);
    assertEquals(1, headMap.size());
    assertTrue(headMap.containsKey(keys[2]));

    NavigableMap<K, V> subMap = descendingMap.subMap(keys[2], true, keys[1], true);
    assertEquals(2, subMap.size());
    assertTrue(subMap.containsKey(keys[1]));
    assertTrue(subMap.containsKey(keys[2]));

    NavigableMap<K, V> tailMap = descendingMap.tailMap(keys[1], false);
    assertEquals(1, tailMap.size());
    assertTrue(tailMap.containsKey(keys[0]));
}

From source file:com.mirth.connect.connectors.http.HttpReceiver.java

@Override
public void onStart() throws ConnectorTaskException {
    String channelId = getChannelId();
    String channelName = getChannel().getName();
    host = replacer.replaceValues(connectorProperties.getListenerConnectorProperties().getHost(), channelId,
            channelName);/* w ww . j  av  a2 s  . c om*/
    port = NumberUtils.toInt(replacer.replaceValues(
            connectorProperties.getListenerConnectorProperties().getPort(), channelId, channelName));
    timeout = NumberUtils
            .toInt(replacer.replaceValues(connectorProperties.getTimeout(), channelId, channelName), 0);

    // Initialize contextPath to "" or its value after replacements
    String contextPath = (connectorProperties.getContextPath() == null ? ""
            : replacer.replaceValues(connectorProperties.getContextPath(), channelId, channelName)).trim();

    /*
     * Empty string and "/" are both valid and equal functionally. However if there is a
     * resource defined, we need to make sure that the context path starts with a slash and
     * doesn't end with one.
     */
    if (!contextPath.startsWith("/")) {
        contextPath = "/" + contextPath;
    }
    if (contextPath.endsWith("/")) {
        contextPath = contextPath.substring(0, contextPath.length() - 1);
    }

    try {
        server = new Server();
        configuration.configureReceiver(this);

        HandlerCollection handlers = new HandlerCollection();
        Handler serverHandler = handlers;

        // Add handlers for each static resource
        if (connectorProperties.getStaticResources() != null) {
            NavigableMap<String, List<HttpStaticResource>> staticResourcesMap = new TreeMap<String, List<HttpStaticResource>>();

            // Add each static resource to a map first to allow sorting and deduplication
            for (HttpStaticResource staticResource : connectorProperties.getStaticResources()) {
                String resourceContextPath = replacer.replaceValues(staticResource.getContextPath(), channelId,
                        channelName);
                Map<String, List<String>> queryParameters = new HashMap<String, List<String>>();

                // If query parameters were specified, extract them here
                int queryIndex = resourceContextPath.indexOf('?');
                if (queryIndex >= 0) {
                    String query = resourceContextPath.substring(queryIndex + 1);
                    resourceContextPath = resourceContextPath.substring(0, queryIndex);

                    for (NameValuePair param : URLEncodedUtils.parse(query, Charset.defaultCharset())) {
                        List<String> currentValue = queryParameters.get(param.getName());
                        String value = StringUtils.defaultString(param.getValue());

                        if (currentValue == null) {
                            currentValue = new ArrayList<String>();
                            queryParameters.put(param.getName(), currentValue);
                        }
                        currentValue.add(value);
                    }
                }

                // We always want to append resources starting with "/" to the base context path
                if (resourceContextPath.endsWith("/")) {
                    resourceContextPath = resourceContextPath.substring(0, resourceContextPath.length() - 1);
                }
                if (!resourceContextPath.startsWith("/")) {
                    resourceContextPath = "/" + resourceContextPath;
                }
                resourceContextPath = contextPath + resourceContextPath;

                List<HttpStaticResource> staticResourcesList = staticResourcesMap.get(resourceContextPath);
                if (staticResourcesList == null) {
                    staticResourcesList = new ArrayList<HttpStaticResource>();
                    staticResourcesMap.put(resourceContextPath, staticResourcesList);
                }
                staticResourcesList
                        .add(new HttpStaticResource(resourceContextPath, staticResource.getResourceType(),
                                staticResource.getValue(), staticResource.getContentType(), queryParameters));
            }

            // Iterate through each context path in reverse so that more specific contexts take precedence
            for (List<HttpStaticResource> staticResourcesList : staticResourcesMap.descendingMap().values()) {
                for (HttpStaticResource staticResource : staticResourcesList) {
                    logger.debug("Adding static resource handler for context path: "
                            + staticResource.getContextPath());
                    ContextHandler resourceContextHandler = new ContextHandler();
                    resourceContextHandler.setContextPath(staticResource.getContextPath());
                    // This allows resources to be requested without a relative context path (e.g. "/")
                    resourceContextHandler.setAllowNullPathInfo(true);
                    resourceContextHandler.setHandler(new StaticResourceHandler(staticResource));
                    handlers.addHandler(resourceContextHandler);
                }
            }
        }

        // Add the main request handler
        ContextHandler contextHandler = new ContextHandler();
        contextHandler.setContextPath(contextPath);
        contextHandler.setHandler(new RequestHandler());
        handlers.addHandler(contextHandler);

        // Wrap the handler collection in a security handler if needed
        if (authenticatorProvider != null) {
            serverHandler = createSecurityHandler(handlers);
        }
        server.setHandler(serverHandler);

        logger.debug("starting HTTP server with address: " + host + ":" + port);
        server.start();
        eventController.dispatchEvent(new ConnectionStatusEvent(getChannelId(), getMetaDataId(),
                getSourceName(), ConnectionStatusEventType.IDLE));
    } catch (Exception e) {
        eventController.dispatchEvent(new ConnectionStatusEvent(getChannelId(), getMetaDataId(),
                getSourceName(), ConnectionStatusEventType.FAILURE));
        throw new ConnectorTaskException("Failed to start HTTP Listener", e);
    }
}

From source file:com.mirth.connect.client.ui.LoadedExtensions.java

public void initialize() {
    // Remove all existing extensions from the maps in case they are being
    // initialized again
    clearExtensionMaps();/*from   w ww  .j a v  a 2s  .  c om*/

    // Order all the plugins by their weight before loading any of them.
    Map<String, String> pluginNameMap = new HashMap<String, String>();
    NavigableMap<Integer, List<String>> weightedPlugins = new TreeMap<Integer, List<String>>();
    for (PluginMetaData metaData : PlatformUI.MIRTH_FRAME.getPluginMetaData().values()) {
        try {
            if (PlatformUI.MIRTH_FRAME.mirthClient.isExtensionEnabled(metaData.getName())) {
                extensionVersions.put(metaData.getName(), metaData.getPluginVersion());
                if (metaData.getClientClasses() != null) {
                    for (PluginClass pluginClass : metaData.getClientClasses()) {
                        String clazzName = pluginClass.getName();
                        int weight = pluginClass.getWeight();
                        pluginNameMap.put(clazzName, metaData.getName());

                        List<String> classList = weightedPlugins.get(weight);
                        if (classList == null) {
                            classList = new ArrayList<String>();
                            weightedPlugins.put(weight, classList);
                        }

                        classList.add(clazzName);
                    }
                }

                if (StringUtils.isNotEmpty(metaData.getTemplateClassName())) {
                    Class<?> clazz = Class.forName(metaData.getTemplateClassName());

                    for (Constructor<?> constructor : clazz.getDeclaredConstructors()) {
                        if (constructor.getParameterTypes().length == 1) {
                            CodeTemplatePlugin codeTemplatePlugin = (CodeTemplatePlugin) constructor
                                    .newInstance(new Object[] { metaData.getName() });
                            addPluginPoints(codeTemplatePlugin);
                            break;
                        }
                    }
                }
            }
        } catch (Exception e) {
            PlatformUI.MIRTH_FRAME.alertThrowable(PlatformUI.MIRTH_FRAME, e);
        }
    }

    // Load connector code template plugins before anything else
    for (ConnectorMetaData metaData : PlatformUI.MIRTH_FRAME.getConnectorMetaData().values()) {
        try {
            if (PlatformUI.MIRTH_FRAME.mirthClient.isExtensionEnabled(metaData.getName())) {
                extensionVersions.put(metaData.getName(), metaData.getPluginVersion());
                if (StringUtils.isNotEmpty(metaData.getTemplateClassName())) {
                    Class<?> clazz = Class.forName(metaData.getTemplateClassName());

                    for (Constructor<?> constructor : clazz.getDeclaredConstructors()) {
                        if (constructor.getParameterTypes().length == 1) {
                            CodeTemplatePlugin codeTemplatePlugin = (CodeTemplatePlugin) constructor
                                    .newInstance(new Object[] { metaData.getName() });
                            addPluginPoints(codeTemplatePlugin);
                            break;
                        }
                    }
                }
            }
        } catch (Exception e) {
            PlatformUI.MIRTH_FRAME.alertThrowable(PlatformUI.MIRTH_FRAME, e,
                    "Could not load code template plugin: " + metaData.getTemplateClassName());
        }
    }

    // Signal the reference list factory that code template plugins have been loaded
    ReferenceListFactory.getInstance().loadPluginReferences();

    // Load the plugins in order of their weight
    for (List<String> classList : weightedPlugins.descendingMap().values()) {
        for (String clazzName : classList) {
            try {
                String pluginName = pluginNameMap.get(clazzName);
                Class<?> clazz = Class.forName(clazzName);
                Constructor<?>[] constructors = clazz.getDeclaredConstructors();

                for (int i = 0; i < constructors.length; i++) {
                    Class<?> parameters[];
                    parameters = constructors[i].getParameterTypes();
                    // load plugin if the number of parameters
                    // in the constructor is 1.
                    if (parameters.length == 1) {
                        ClientPlugin clientPlugin = (ClientPlugin) constructors[i]
                                .newInstance(new Object[] { pluginName });
                        addPluginPoints(clientPlugin);
                        i = constructors.length;
                    }
                }
            } catch (Exception e) {
                PlatformUI.MIRTH_FRAME.alertThrowable(PlatformUI.MIRTH_FRAME, e,
                        "Could not load plugin class: " + clazzName);
            }
        }
    }

    for (ConnectorMetaData metaData : PlatformUI.MIRTH_FRAME.getConnectorMetaData().values()) {
        try {
            if (PlatformUI.MIRTH_FRAME.mirthClient.isExtensionEnabled(metaData.getName())) {

                String connectorName = metaData.getName();
                ConnectorSettingsPanel connectorSettingsPanel = (ConnectorSettingsPanel) Class
                        .forName(metaData.getClientClassName()).newInstance();

                if (metaData.getType() == ConnectorMetaData.Type.SOURCE) {
                    connectors.put(connectorName, connectorSettingsPanel);
                    sourceConnectors.put(connectorName, connectorSettingsPanel);
                } else if (metaData.getType() == ConnectorMetaData.Type.DESTINATION) {
                    connectors.put(connectorName, connectorSettingsPanel);
                    destinationConnectors.put(connectorName, connectorSettingsPanel);
                } else {
                    // type must be SOURCE or DESTINATION
                    throw new Exception();
                }
            }
        } catch (Exception e) {
            PlatformUI.MIRTH_FRAME.alertThrowable(PlatformUI.MIRTH_FRAME, e,
                    "Could not load connector class: " + metaData.getClientClassName());
        }
    }

    // Signal the reference list factory that all other plugins have been loaded
    ReferenceListFactory.getInstance().loadReferencesAfterPlugins();
}

From source file:com.google.gwt.emultest.java.util.TreeMapTest.java

/**
 * Test method for 'java.util.Map.values()'.
 *
 * @see java.util.Map#values()/* w  ww .  j  av  a 2s  . c  om*/
 */
public void testValues() {
    K[] keys = getSortedKeys();
    V[] values = getSortedValues();
    NavigableMap<K, V> map = createNavigableMap();

    map.put(keys[0], values[0]);

    Collection<V> mapValues = map.values();
    assertNotNull(mapValues);
    assertEquals(1, mapValues.size());

    Iterator<V> valueIter = mapValues.iterator();
    assertEquals(values[0], valueIter.next());

    _assertEquals(mapValues, map.values());

    mapValues.clear();
    _assertEmpty(map);

    for (int i = 0; i < keys.length; i++) {
        map.put(keys[i], values[i]);
    }

    mapValues.iterator();
    assertEquals(map.size(), mapValues.size());
    for (V value : values) {
        assertTrue(mapValues.contains(value));
    }
    assertEquals(values.length, mapValues.size());
    int size = 0;
    for (Iterator iter = mapValues.iterator(); iter.hasNext(); iter.next()) {
        size++;
    }
    assertEquals(values.length, size);

    mapValues = map.descendingMap().values();
    mapValues.iterator();
    assertEquals(map.size(), mapValues.size());
    for (V value : values) {
        assertTrue(mapValues.contains(value));
    }
    assertEquals(values.length, mapValues.size());
    size = 0;
    for (Iterator iter = mapValues.iterator(); iter.hasNext(); iter.next()) {
        size++;
    }
    assertEquals(values.length, size);

    mapValues = map.values();
    mapValues.remove(values[0]);
    assertTrue(!map.containsValue(values[0]));
    assertEquals(values.length - 1, mapValues.size());
    size = 0;
    for (Iterator iter = mapValues.iterator(); iter.hasNext(); iter.next()) {
        size++;
    }
    assertEquals(values.length - 1, size);
}