Example usage for java.util SortedMap lastKey

List of usage examples for java.util SortedMap lastKey

Introduction

In this page you can find the example usage for java.util SortedMap lastKey.

Prototype

K lastKey();

Source Link

Document

Returns the last (highest) key currently in this map.

Usage

From source file:org.apache.fop.afp.fonts.RasterFont.java

/**
 * Get the character set metrics for the specified point size.
 *
 * @param sizeInMpt the point size (in mpt)
 * @return the character set metrics//from   w ww .  ja va 2 s .c  o  m
 */
public CharacterSet getCharacterSet(int sizeInMpt) {

    Integer requestedSize = Integer.valueOf(sizeInMpt);
    CharacterSet csm = (CharacterSet) charSets.get(requestedSize);
    double sizeInPt = sizeInMpt / 1000.0;

    if (csm != null) {
        return csm;
    }

    if (substitutionCharSets != null) {
        //Check first if a substitution has already been added
        csm = (CharacterSet) substitutionCharSets.get(requestedSize);
    }

    if (csm == null && !charSets.isEmpty()) {
        // No match or substitution found, but there exist entries
        // for other sizes
        // Get char set with nearest, smallest font size
        SortedMap<Integer, CharacterSet> smallerSizes = charSets.headMap(requestedSize);
        SortedMap<Integer, CharacterSet> largerSizes = charSets.tailMap(requestedSize);
        int smallerSize = smallerSizes.isEmpty() ? 0 : ((Integer) smallerSizes.lastKey()).intValue();
        int largerSize = largerSizes.isEmpty() ? Integer.MAX_VALUE
                : ((Integer) largerSizes.firstKey()).intValue();

        Integer fontSize;
        if (!smallerSizes.isEmpty() && (sizeInMpt - smallerSize) <= (largerSize - sizeInMpt)) {
            fontSize = Integer.valueOf(smallerSize);
        } else {
            fontSize = Integer.valueOf(largerSize);
        }
        csm = (CharacterSet) charSets.get(fontSize);

        if (csm != null) {
            // Add the substitute mapping, so subsequent calls will
            // find it immediately
            if (substitutionCharSets == null) {
                substitutionCharSets = new HashMap<Integer, CharacterSet>();
            }
            substitutionCharSets.put(requestedSize, csm);
            // do not output the warning if the font size is closer to an integer less than 0.1
            if (!(Math.abs(fontSize.intValue() / 1000.0 - sizeInPt) < 0.1)) {
                String msg = "No " + sizeInPt + "pt font " + getFontName() + " found, substituted with "
                        + fontSize.intValue() / 1000f + "pt font";
                LOG.warn(msg);
            }
        }
    }

    if (csm == null) {
        // Still no match -> error
        String msg = "No font found for font " + getFontName() + " with point size " + sizeInPt;
        LOG.error(msg);
        throw new FontRuntimeException(msg);
    }

    return csm;

}

From source file:elw.web.AdminController.java

@RequestMapping(value = "approve", method = RequestMethod.GET)
public ModelAndView do_approve(final HttpServletRequest req, final HttpServletResponse resp)
        throws IOException {
    return wmScore(req, resp, true, false, new WebMethodScore() {
        public ModelAndView handleScore(HttpServletRequest req, HttpServletResponse resp, Ctx ctx,
                FileSlot slot, Solution file, Long stamp, Map<String, Object> model) {
            final SortedMap<Long, Score> allScores = core.getQueries().scores(ctx, slot, file);

            final long stampEff = stamp == null ? allScores.lastKey() : stamp;
            final Score score = allScores.get(stampEff);

            model.put("stamp", stamp);
            model.put("score", score);
            model.put("slot", slot);
            model.put("file", file);

            return new ModelAndView("a/approve", model);
        }/*from   ww w. j a  v  a 2 s  .c o m*/
    });
}

From source file:com.precioustech.fxtrading.tradingbot.strategies.FadeTheMoveStrategy.java

public void analysePrices() {
    for (Map.Entry<TradeableInstrument<T>, Cache<DateTime, MarketDataPayLoad<T>>> entry : instrumentRecentPricesCache
            .entrySet()) {/*from w  w  w.  j  a va2  s.  co m*/
        SortedMap<DateTime, MarketDataPayLoad<T>> sortedByDate = ImmutableSortedMap
                .copyOf(entry.getValue().asMap());
        if (sortedByDate.isEmpty()) {
            continue;
        }
        Double pipJump = calculatePipJump(sortedByDate.values(), entry.getKey());
        Double absPipJump = Math.abs(pipJump);
        if (absPipJump >= this.pipJumpCutOffCalculator.calculatePipJumpCutOff(entry.getKey())) {
            MarketDataPayLoad<T> lastPayLoad = sortedByDate.get(sortedByDate.lastKey());
            Double pip = this.instrumentService.getPipForInstrument(entry.getKey());
            double takeProfitPrice;
            double limitPrice;
            TradingSignal signal = null;
            if (Math.signum(pipJump) > 0) {// Short
                signal = TradingSignal.SHORT;
                limitPrice = lastPayLoad.getBidPrice() + tradingConfig.getFadeTheMoveDistanceToTrade() * pip;
                takeProfitPrice = limitPrice - tradingConfig.getFadeTheMovePipsDesired() * pip;
            } else {
                signal = TradingSignal.LONG;
                limitPrice = lastPayLoad.getAskPrice() - tradingConfig.getFadeTheMoveDistanceToTrade() * pip;
                takeProfitPrice = limitPrice + tradingConfig.getFadeTheMovePipsDesired() * pip;
            }
            this.orderQueue.offer(new TradingDecision<T>(entry.getKey(), signal, takeProfitPrice, 0.0,
                    limitPrice, TradingDecision.SRCDECISION.FADE_THE_MOVE));
            entry.getValue().asMap().clear();/*
                                              * clear the prices so that we do not keep
                                              * working on old decision
                                              */
        }
    }
}

From source file:org.opencms.workplace.editors.CmsWorkplaceEditorManager.java

/**
 * Returns the editor URI for the current resource type.<p>
 * /*from  ww  w.jav a  2 s . c  o m*/
 * @param context the request context
 * @param resourceType the current resource type
 * @param userAgent the user agent String that identifies the browser
 * @return a valid editor URI for the resource type or null, if no editor matches
 */
protected String getEditorUri(CmsRequestContext context, String resourceType, String userAgent) {

    // step 1: check if the user specified a preferred editor for the given resource type
    CmsUserSettings settings = new CmsUserSettings(context.getCurrentUser());
    String preferredEditorSetting = settings.getPreferredEditor(resourceType);
    if (preferredEditorSetting == null) {
        // no preferred editor setting found for this resource type, look for mapped resource type preferred editor
        Iterator i = m_editorConfigurations.iterator();
        while (i.hasNext()) {
            CmsWorkplaceEditorConfiguration currentConfig = (CmsWorkplaceEditorConfiguration) i.next();
            String mapping = currentConfig.getMappingForResourceType(resourceType);
            if (mapping != null) {
                preferredEditorSetting = settings.getPreferredEditor(mapping);
            }
            if (preferredEditorSetting != null) {
                break;
            }
        }
    }
    if (preferredEditorSetting != null) {
        CmsWorkplaceEditorConfiguration preferredConf = filterPreferredEditor(preferredEditorSetting);
        if ((preferredConf != null) && preferredConf.matchesBrowser(userAgent)) {
            // return preferred editor only if it matches the current users browser
            return preferredConf.getEditorUri();
        }
    }

    // step 2: filter editors for the given resoure type
    SortedMap filteredEditors = filterEditorsForResourceType(resourceType);

    // step 3: check if one of the editors matches the current users browser
    while (filteredEditors.size() > 0) {
        // check editor configuration with highest ranking 
        Float key = (Float) filteredEditors.lastKey();
        CmsWorkplaceEditorConfiguration conf = (CmsWorkplaceEditorConfiguration) filteredEditors.get(key);
        if (conf.matchesBrowser(userAgent)) {
            return conf.getEditorUri();
        }
        filteredEditors.remove(key);
    }

    // no valid editor found 
    return null;
}

From source file:org.opencms.workplace.editors.CmsWorkplaceEditorManager.java

/**
 * Returns the editor URI for the current resource type.<p>
 * /*from  w  w w .  j a va 2 s .  c om*/
 * @param context the request context
 * @param userAgent the user agent String that identifies the browser
 * @return a valid editor URI for the resource type or null, if no editor matches
 */
public String getWidgetEditor(CmsRequestContext context, String userAgent) {

    // step 1: check if the user specified a preferred editor for the resource type xmlpage
    CmsUserSettings settings = new CmsUserSettings(context.getCurrentUser());
    String resourceType = CmsResourceTypeXmlPage.getStaticTypeName();
    String preferredEditorSetting = settings.getPreferredEditor(resourceType);
    if (preferredEditorSetting == null) {
        // no preferred editor setting found for this resource type, look for mapped resource type preferred editor
        Iterator i = m_editorConfigurations.iterator();
        while (i.hasNext()) {
            CmsWorkplaceEditorConfiguration currentConfig = (CmsWorkplaceEditorConfiguration) i.next();
            String mapping = currentConfig.getMappingForResourceType(resourceType);
            if (mapping != null) {
                preferredEditorSetting = settings.getPreferredEditor(mapping);
            }
            if (preferredEditorSetting != null) {
                break;
            }
        }
    }
    if (preferredEditorSetting != null) {
        CmsWorkplaceEditorConfiguration preferredConf = filterPreferredEditor(preferredEditorSetting);
        if ((preferredConf != null) && preferredConf.isWidgetEditor()
                && preferredConf.matchesBrowser(userAgent)) {
            // return preferred editor only if it matches the current users browser
            return preferredConf.getWidgetEditor();
        }
    }

    // step 2: filter editors for the given resoure type
    SortedMap filteredEditors = filterEditorsForResourceType(resourceType);

    // step 3: check if one of the editors matches the current users browser
    while (filteredEditors.size() > 0) {
        // check editor configuration with highest ranking 
        Float key = (Float) filteredEditors.lastKey();
        CmsWorkplaceEditorConfiguration conf = (CmsWorkplaceEditorConfiguration) filteredEditors.get(key);
        if (conf.isWidgetEditor() && conf.matchesBrowser(userAgent)) {
            return conf.getWidgetEditor();
        }
        filteredEditors.remove(key);
    }

    // no valid editor found 
    return null;
}

From source file:viper.api.time.TimeEncodedList.java

/**
 * {@inheritDoc}/*w  w w . j  a  va 2s . co  m*/
 */
public Comparable firstBefore(Comparable c) {
    SortedMap head = values.headMap(c);
    if (!head.isEmpty()) {
        return (Comparable) head.lastKey();
    }
    return null;
}

From source file:org.apache.hadoop.yarn.util.Log4jWarningErrorMetricsAppender.java

private List<Map<String, Element>> getElementsAndCounts(Map<String, SortedMap<Long, Integer>> map,
        List<Long> cutoffs, SortedSet<PurgeElement> purgeInformation) {
    if (purgeInformation.size() > maxUniqueMessages) {
        ErrorAndWarningsCleanup cleanup = new ErrorAndWarningsCleanup();
        long cutoff = Time.now() - (messageAgeLimitSeconds * 1000);
        cutoff = (cutoff / 1000);/*from w w  w.j a v  a2 s .  c o m*/
        cleanup.cleanupMessages(map, purgeInformation, cutoff, maxUniqueMessages);
    }
    List<Map<String, Element>> ret = new ArrayList<>(cutoffs.size());
    for (int i = 0; i < cutoffs.size(); ++i) {
        ret.add(new HashMap<String, Element>());
    }
    synchronized (lock) {
        for (Map.Entry<String, SortedMap<Long, Integer>> element : map.entrySet()) {
            for (int i = 0; i < cutoffs.size(); ++i) {
                Map<String, Element> retMap = ret.get(i);
                SortedMap<Long, Integer> qualifyingTimes = element.getValue().tailMap(cutoffs.get(i));
                long count = 0;
                for (Map.Entry<Long, Integer> entry : qualifyingTimes.entrySet()) {
                    count += entry.getValue();
                }
                if (!qualifyingTimes.isEmpty()) {
                    retMap.put(element.getKey(), new Element(count, qualifyingTimes.lastKey()));
                }
            }
        }
    }
    return ret;
}

From source file:viper.api.time.TimeEncodedList.java

/**
 * Removes all values at the given range. Note that, like 
 * <code>SortedMap</code>, this means that value is set in the
 * range from start, inclusive, to stop, exclusive.
 * @param start the first index to remove
 * @param stop the first index that is not removed
 * @return <code>true</code> if any elements were removed
 *///from   w  ww. j  a  v  a 2  s  .  co  m
public boolean remove(Comparable start, Comparable stop) {
    boolean someFound = false;
    SortedMap head = values.headMap(start);
    if (!head.isEmpty()) {
        LelNode n = (LelNode) head.get(head.lastKey());
        if (n.getEnd().compareTo(start) > 0) {
            someFound = true;
            head.put(head.lastKey(), new LelNode((Instant) start, n.getValue()));
            if (n.getEnd().compareTo(stop) > 0) {
                // this object spans the whole removed range
                values.put(stop, new TimeEncodedList.LelNode(n.getEnd(), n.getValue()));
                return true;
            }
        }
    }

    // By now, will have removed anything coming in from the head
    // Just remove the stuff in the subMap, making sure to put back
    // the leftovers.
    SortedMap sub = values.subMap(start, stop);
    if (!sub.isEmpty()) {
        LelNode n = (LelNode) sub.get(sub.lastKey());
        if (n.getEnd().compareTo(stop) > 0) {
            values.put(stop, new LelNode(n.getEnd(), n.getValue()));
        }
        values.subMap(start, stop).clear();
        return true;
    }
    return someFound;
}

From source file:org.neo4j.gis.spatial.OsmAnalysisTest.java

public void testAnalysis(String osm, int years, int days) throws Exception {
    Node osmRoot = ReferenceNodes.getReferenceNode(graphDb(), "osm_root");
    Node osmImport = osmRoot.getSingleRelationship(OSMRelation.OSM, Direction.OUTGOING).getEndNode();
    Node usersNode = osmImport.getSingleRelationship(OSMRelation.USERS, Direction.OUTGOING).getEndNode();

    Map<String, User> userIndex = collectUserChangesetData(usersNode);
    SortedSet<User> topTen = getTopTen(userIndex);

    SpatialDatabaseService spatialService = new SpatialDatabaseService(graphDb());
    SortedMap<String, Layer> layers = exportPoints(osm, spatialService, topTen);

    layers = removeEmptyLayers(layers);//from   w  ww  . j a v  a 2  s. c  om
    ReferencedEnvelope bbox = getEnvelope(layers.values());

    StyledImageExporter imageExporter = new StyledImageExporter(graphDb());
    String exportDir = "target/export/" + osm + "/analysis";
    imageExporter.setExportDir(exportDir);
    imageExporter.setZoom(2.0);
    imageExporter.setOffset(-0.05, -0.05);
    imageExporter.setSize(1280, 800);

    for (String layerName : layers.keySet()) {
        SortedMap<String, Layer> layersSubset = new TreeMap<String, Layer>(layers.headMap(layerName));

        String[] to_render = new String[Math.min(10, layersSubset.size() + 1)];
        to_render[0] = layerName;
        if (layersSubset.size() > 0) {
            for (int i = 1; i < to_render.length; i++) {
                String name = layersSubset.lastKey();
                layersSubset.remove(name);
                to_render[i] = name;
            }
        }

        System.out.println("exporting " + layerName);
        imageExporter.saveLayerImage(to_render, // (String[])
                // layersSubset.keySet().toArray(new
                // String[] {}),
                "/Users/davidesavazzi/Desktop/amanzi/awe trial/osm_germany/germany_poi_small.sld",
                new File(layerName + ".png"), bbox);
    }
}

From source file:viper.api.time.TimeEncodedList.java

/**
 * Sets the value at the given range. Note that, like 
 * <code>SortedMap</code>, this means that value is set in the
 * range from start, inclusive, to stop, exclusive.
 * @param start the first index to set//from  w  w w.  j  av  a 2  s  . c  om
 * @param stop the first index that is not set
 * @param value all elements in the list in the range [start, stop)
 *   will take this value
 * @throws IllegalArgumentException if start is not less than stop
 */
public void set(Comparable start, Comparable stop, Object value) {
    if (start.compareTo(stop) >= 0) {
        throw new IllegalArgumentException("Start not strictly less than stop: " + start + " !< " + stop);
    }
    if (value == null) {
        remove(start, stop);
        return;
    }
    SortedMap head = values.headMap(start);
    if (!head.isEmpty()) {
        LelNode n = (LelNode) head.get(head.lastKey());
        if (n.getValue().equals(value)) {
            if (n.getEnd().compareTo(start) >= 0) {
                start = (Instant) head.lastKey();
            }
        } else if (n.getEnd().compareTo(start) > 0) {
            head.put(head.lastKey(), new LelNode((Instant) start, n.getValue()));
            if (n.getEnd().compareTo(stop) > 0) {
                values.put(start, new LelNode((Instant) stop, value));
                values.put(stop, new LelNode(n.getEnd(), n.getValue()));
                return;
            }
        }
    }
    SortedMap sub = values.subMap(start, stop);
    if (!sub.isEmpty()) {
        LelNode n = (LelNode) sub.get(sub.lastKey());
        if (n.getValue().equals(value)) {
            if (n.getEnd().compareTo(stop) > 0) {
                stop = n.getEnd();
            }
        } else if (n.getEnd().compareTo(stop) > 0) {
            values.put(stop, new LelNode(n.getEnd(), n.getValue()));
        }
    }
    values.subMap(start, stop).clear();
    values.put(start, new TimeEncodedList.LelNode((Instant) stop, value));
}