Example usage for java.util TreeMap values

List of usage examples for java.util TreeMap values

Introduction

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

Prototype

public Collection<V> values() 

Source Link

Document

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

Usage

From source file:jenkins.model.lazy.AbstractLazyLoadRunMap.java

/**
 * Replaces all the current loaded Rs with the given ones.
 */// w  w w.  ja v a2s  .c  o m
public synchronized void reset(TreeMap<Integer, R> builds) {
    Index index = new Index();
    for (R r : builds.values()) {
        String id = getIdOf(r);
        BuildReference<R> ref = createReference(r);
        index.byId.put(id, ref);
        index.byNumber.put(getNumberOf(r), ref);
    }

    this.index = index;
}

From source file:org.polymap.core.data.image.RasterRenderProcessor.java

protected Image getMap(Set<ILayer> layers, int width, int height, ReferencedEnvelope bbox) {
    // mapContext
    synchronized (this) {
        // check style objects
        boolean needsNewContext = false;

        // create mapContext
        if (mapContext == null || needsNewContext) {
            // sort z-priority
            TreeMap<String, ILayer> sortedLayers = new TreeMap();
            for (ILayer layer : layers) {
                String uniqueOrderKey = String.valueOf(layer.getOrderKey()) + layer.id();
                sortedLayers.put(uniqueOrderKey, layer);
            }/*from  www .j a  v a  2  s  .c om*/
            // add to mapContext
            mapContext = new DefaultMapContext(bbox.getCoordinateReferenceSystem());
            for (ILayer layer : sortedLayers.values()) {
                try {
                    IGeoResource res = layer.getGeoResource();
                    if (res == null) {
                        throw new IllegalStateException("Unable to find geo resource of layer: " + layer);
                    }
                    AbstractRasterService service = (AbstractRasterService) res.service(null);
                    log.debug("    service: " + service);

                    log.debug("    CRS: " + layer.getCRS());
                    AbstractGridCoverage2DReader reader = service.getReader(layer.getCRS(), null);

                    Style style = createRGBStyle(reader);
                    if (style == null) {
                        log.warn("Error creating RGB style, trying greyscale...");
                        style = createGreyscaleStyle(1);
                    }
                    mapContext.addLayer(reader, style);
                    styles.put(layer, style);
                } catch (IOException e) {
                    log.warn(e);
                    // FIXME set layer status and statusMessage
                }
            }
        } else {
        }
    }

    // render
    BufferedImage result = new BufferedImage(width, height, BufferedImage.TYPE_4BYTE_ABGR);
    final Graphics2D g = result.createGraphics();
    try {
        StreamingRenderer renderer = new StreamingRenderer();

        // error handler
        renderer.addRenderListener(new RenderListener() {
            public void featureRenderer(SimpleFeature feature) {
            }

            public void errorOccurred(Exception e) {
                log.error("Renderer error: ", e);
                drawErrorMsg(g, "Fehler bei der Darstellung.", e);
            }
        });

        // rendering hints
        RenderingHints hints = new RenderingHints(RenderingHints.KEY_RENDERING,
                RenderingHints.VALUE_RENDER_QUALITY);
        hints.add(new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON));
        hints.add(new RenderingHints(RenderingHints.KEY_TEXT_ANTIALIASING,
                RenderingHints.VALUE_TEXT_ANTIALIAS_ON));

        renderer.setJava2DHints(hints);
        //            g.setRenderingHints( hints );

        // render params
        Map rendererParams = new HashMap();
        rendererParams.put("optimizedDataLoadingEnabled", Boolean.TRUE);
        renderer.setRendererHints(rendererParams);

        renderer.setContext(mapContext);
        Rectangle paintArea = new Rectangle(width, height);
        renderer.paint(g, paintArea, bbox);
        return result;
    } catch (Throwable e) {
        log.error("Renderer error: ", e);
        drawErrorMsg(g, null, e);
        return result;
    } finally {
        if (g != null) {
            g.dispose();
        }
    }
}

From source file:org.rhwlab.dispim.nucleus.NucleusData.java

public RealVector[] getAxes() {
    TreeMap<Double, RealVector> map = new TreeMap<>();
    for (int d = 0; d < this.getCenter().length; ++d) {
        map.put(this.getRadius(d), this.adjustedEigenA.getEigenvector(d));
    }//from w  w w .j  av a 2s  .com
    return map.values().toArray(new RealVector[0]);
}

From source file:com.cyclopsgroup.tornado.ui.view.user.UserProfile.java

/**
 * Override method execute in class UserProfile
 *
 * @see com.cyclopsgroup.waterview.Module#execute(com.cyclopsgroup.waterview.RuntimeData, com.cyclopsgroup.waterview.Context)
 *///from   ww w . j a va2s  . c  o m
public void execute(RuntimeData data, Context context) throws Exception {
    RuntimeUser user = RuntimeUser.getInstance(data);
    PersistenceManager persist = (PersistenceManager) lookup(PersistenceManager.ROLE);
    User u = (User) persist.load(User.class, user.getId());
    context.put("userObject", u);

    TreeMap languages = new TreeMap();
    TreeMap countries = new TreeMap();
    Locale[] availableLocales = Locale.getAvailableLocales();
    for (int i = 0; i < availableLocales.length; i++) {
        Locale locale = availableLocales[i];
        DefaultSelectOption lang = new DefaultSelectOption(locale.getLanguage(),
                locale.getDisplayLanguage(data.getLocale()) + '(' + locale.getLanguage() + ')');
        languages.put(locale.getLanguage(), lang);

        if (StringUtils.isNotEmpty(locale.getCountry())) {
            DefaultSelectOption cout = new DefaultSelectOption(locale.getCountry(),
                    locale.getDisplayCountry(data.getLocale()) + '(' + locale.getCountry() + ')');
            countries.put(locale.getCountry(), cout);
        }
    }
    context.put("countries", countries.values());
    context.put("languages", languages.values());
}

From source file:disAMS.AMRMClient.Impl.AMRMClientImpl.java

/**
 * ContainerRequests with locality relaxation cannot be made at the same
 * priority as ContainerRequests without locality relaxation.
 *//*from www  .ja va  2  s  . c  o m*/
private void checkLocalityRelaxationConflict(Priority priority, Collection<String> locations,
        boolean relaxLocality) {
    Map<String, TreeMap<Resource, ResourceRequestInfo>> remoteRequests = this.remoteRequestsTable.get(priority);
    if (remoteRequests == null) {
        return;
    }
    // Locality relaxation will be set to relaxLocality for all implicitly
    // requested racks. Make sure that existing rack requests match this.
    for (String location : locations) {
        TreeMap<Resource, ResourceRequestInfo> reqs = remoteRequests.get(location);
        if (reqs != null && !reqs.isEmpty()) {
            boolean existingRelaxLocality = reqs.values().iterator().next().remoteRequest.getRelaxLocality();
            if (relaxLocality != existingRelaxLocality) {
                throw new InvalidContainerRequestException(
                        "Cannot submit a " + "ContainerRequest asking for location " + location
                                + " with locality relaxation " + relaxLocality + " when it has "
                                + "already been requested with locality relaxation " + existingRelaxLocality);
            }
        }
    }
}

From source file:org.apache.hadoop.hbase.TestSplit.java

private void basicSplit(final HRegion region) throws Exception {
    addContent(region, COLFAMILY_NAME3);
    region.internalFlushcache();/*from   www  .ja  v a  2  s.co  m*/
    Text midkey = new Text();
    assertTrue(region.needsSplit(midkey));
    HRegion[] regions = split(region);
    // Assert can get rows out of new regions.  Should be able to get first
    // row from first region and the midkey from second region.
    byte[] b = new byte[] { FIRST_CHAR, FIRST_CHAR, FIRST_CHAR };
    assertGet(regions[0], COLFAMILY_NAME3, new Text(b));
    assertGet(regions[1], COLFAMILY_NAME3, midkey);
    // Test I can get scanner and that it starts at right place.
    assertScan(regions[0], COLFAMILY_NAME3, new Text(b));
    assertScan(regions[1], COLFAMILY_NAME3, midkey);
    // Now prove can't split regions that have references.
    Text[] midkeys = new Text[regions.length];
    for (int i = 0; i < regions.length; i++) {
        midkeys[i] = new Text();
        // Even after above splits, still needs split but after splits its
        // unsplitable because biggest store file is reference.  References
        // make the store unsplittable, until something bigger comes along.
        assertFalse(regions[i].needsSplit(midkeys[i]));
        // Add so much data to this region, we create a store file that is > than
        // one of our unsplitable references.
        // it will.
        for (int j = 0; j < 2; j++) {
            addContent(regions[i], COLFAMILY_NAME3);
        }
        addContent(regions[i], COLFAMILY_NAME2);
        addContent(regions[i], COLFAMILY_NAME1);
        regions[i].internalFlushcache();
    }

    // Assert that even if one store file is larger than a reference, the
    // region is still deemed unsplitable (Can't split region if references
    // presen).
    for (int i = 0; i < regions.length; i++) {
        midkeys[i] = new Text();
        // Even after above splits, still needs split but after splits its
        // unsplitable because biggest store file is reference.  References
        // make the store unsplittable, until something bigger comes along.
        assertFalse(regions[i].needsSplit(midkeys[i]));
    }

    // To make regions splitable force compaction.
    for (int i = 0; i < regions.length; i++) {
        assertTrue(regions[i].compactStores());
    }

    TreeMap<String, HRegion> sortedMap = new TreeMap<String, HRegion>();
    // Split these two daughter regions so then I'll have 4 regions.  Will
    // split because added data above.
    for (int i = 0; i < regions.length; i++) {
        HRegion[] rs = split(regions[i]);
        for (int j = 0; j < rs.length; j++) {
            sortedMap.put(rs[j].getRegionName().toString(), rs[j]);
        }
    }
    LOG.info("Made 4 regions");
    // The splits should have been even.  Test I can get some arbitrary row out
    // of each.
    int interval = (LAST_CHAR - FIRST_CHAR) / 3;
    for (HRegion r : sortedMap.values()) {
        assertGet(r, COLFAMILY_NAME3, new Text(new String(b, HConstants.UTF8_ENCODING)));
        b[0] += interval;
    }
}

From source file:com.facebook.tsdb.tsdash.server.model.Metric.java

public void alignAllTimeSeries() {
    long cycle = guessTimeCycle();
    // wrap the time stamps to a multiple of cycle
    for (ArrayList<DataPoint> points : timeSeries.values()) {
        for (DataPoint p : points) {
            p.ts -= p.ts % cycle;//from ww  w  .  j  a v a2  s .com
        }
    }
    // do the actual aligning
    TreeMap<TagsArray, ArrayList<DataPoint>> aligned = new TreeMap<TagsArray, ArrayList<DataPoint>>(
            Tag.arrayComparator());
    for (TagsArray header : timeSeries.keySet()) {
        aligned.put(header, TimeSeries.align(timeSeries.get(header), cycle));
    }
    // align the time series between each other
    long maxmin = Long.MIN_VALUE;
    long minmax = Long.MAX_VALUE;
    long maxmax = Long.MIN_VALUE;
    for (ArrayList<DataPoint> points : aligned.values()) {
        if (points.size() == 0) {
            logger.error("We have found an empty timeseries");
            continue;
        }
        DataPoint first = points.get(0);
        if (points.size() > 0 && points.get(0).ts > maxmin) {
            maxmin = first.ts;
        }
        DataPoint last = points.get(points.size() - 1);
        if (last.ts < minmax) {
            minmax = last.ts;
        }
        if (last.ts > maxmax) {
            maxmax = last.ts;
        }
    }
    if (maxmax - minmax > DATA_MISSING_THOLD) {
        // we've just detected missing data from this set of time series
        logger.error("Missing data detected");

        // add padding to maxmax
        for (ArrayList<DataPoint> points : aligned.values()) {
            if (points.size() == 0) {
                continue;
            }
            long max = points.get(points.size() - 1).ts;
            for (long ts = max + cycle; ts <= maxmax; ts += cycle) {
                points.add(new DataPoint(ts, 0.0));
            }
        }
    } else {
        // cut off the tail
        for (ArrayList<DataPoint> points : aligned.values()) {
            while (points.size() > 0 && points.get(points.size() - 1).ts > minmax) {
                points.remove(points.size() - 1);
            }
        }
    }
    // cut off the head
    for (ArrayList<DataPoint> points : aligned.values()) {
        while (points.size() > 0 && points.get(0).ts < maxmin) {
            points.remove(0);
        }
    }
    this.timeSeries = aligned;
}

From source file:com.bytelightning.opensource.pokerface.ScriptHelperImpl.java

/**
 * {@inheritDoc}//w w w .  j  a va  2  s  .com
 */
@Override
public String[] getAcceptableLocales() {
    ArrayList<String> retVal = new ArrayList<String>();
    Header[] hdrs = request.getHeaders("Accept-Language");
    if ((hdrs != null) && (hdrs.length > 0)) {
        // Store the accumulated languages that have been requested in a local collection, sorted by the quality value (so we can add Locales in descending order).
        // The values will be ArrayLists containing the corresponding Locales to be added
        TreeMap<Double, ArrayList<Locale>> locales = new TreeMap<Double, ArrayList<Locale>>();
        for (Header hdr : hdrs)
            parseLocalesHeader(hdr.getValue(), locales);
        // Process the quality values in highest->lowest order (due to negating the Double value when creating the key)
        for (ArrayList<Locale> list : locales.values())
            for (Locale locale : list)
                retVal.add(locale.toLanguageTag());
        Collections.reverse(retVal);
    }
    retVal.add(Locale.getDefault().toLanguageTag());
    return retVal.toArray(new String[retVal.size()]);
}

From source file:com.edgenius.wiki.render.handler.TOCHandler.java

@SuppressWarnings("unchecked")
public List<RenderPiece> handle(RenderContext renderContext, Map<String, String> values) {
    TreeMap<Integer, HeadingModel> tree = new TreeMap<Integer, HeadingModel>(new CompareToComparator());

    List<HeadingModel> list = (List<HeadingModel>) renderContext.getGlobalParam(TOCMacro.class.getName());
    //hi, here cannot simple return even list is null because the TOCMacro place holder need remove in following code.
    if (list != null) {
        for (HeadingModel headingModel : list) {
            //OK, find heading model, then put it into sorted list
            tree.put(headingModel.getOrder(), headingModel);
        }/*from ww w . jav  a2 s .c om*/
        //in buildTOCHTML() method, {toc} will replace to "no head exist" string
    }

    Collection<HeadingModel> headTree = tree.values();
    //replace all TOCMacro(GlobalFilter) object in renderPiece by TOC HTML string.
    int deep = 3;
    String align = null;
    boolean ordered = true;
    Map<String, String> map = new HashMap<String, String>();
    if (values != null) {
        //get back deep, order and align value.
        String deepStr = values.get(NameConstants.DEEP);
        String orderStr = values.get(NameConstants.ORDERED);
        align = values.get(NameConstants.ALIGN);
        map.put(NameConstants.DEEP, deepStr);
        map.put(NameConstants.ALIGN, align);
        map.put(NameConstants.ORDERED, orderStr);

        deep = NumberUtils.toInt(deepStr, 3);
        if (orderStr == null) {
            //default value is true! show ordered list
            ordered = true;
        } else {
            ordered = BooleanUtils.toBoolean(values.get(NameConstants.ORDERED));
        }
    }
    String wajax = "";
    if (map.size() > 0)
        wajax = RichTagUtil.buildWajaxAttributeString(this.getClass().getName(), map);

    List<RenderPiece> pieces = new ArrayList<RenderPiece>();
    pieces.addAll(buildTOCHTML(renderContext, headTree, deep, align, !ordered, wajax));
    return pieces;
}

From source file:org.eclipse.gyrex.cloud.internal.queue.ZooKeeperQueue.java

@Override
public IMessage consumeMessage(final long timeout, final TimeUnit unit)
        throws IllegalArgumentException, IllegalStateException, SecurityException, InterruptedException {
    /*//www.  j a  v a2s. co m
     * We want to get the node with the smallest sequence number. But
     * other clients may remove and add nodes concurrently. Thus, we
     * need to further check if the node can be returned. It might be
     * gone by the time we check. If that happens we just continue with
     * the next node.
     */
    if ((timeout > 0) && (unit == null)) {
        throw new IllegalArgumentException("unit must not be null when timeout is specified");
    }
    final long abortTime = timeout > 0 ? unit.toMillis(timeout) + System.currentTimeMillis() : 0;
    TreeMap<Long, String> queueChildren;
    while (true) {
        try {
            queueChildren = readQueueChildren(null);
        } catch (final Exception e) {
            if (e instanceof KeeperException.NoNodeException) {
                throw new IllegalStateException(String.format("queue '%s' does not exist", id));
            }
            throw new QueueOperationFailedException(id, "CONSUME_MESSAGES", e);
        }

        // iterate over all children
        if (queueChildren.size() > 0) {
            for (final String childName : queueChildren.values()) {
                if (childName != null) {
                    // read message
                    final Message message = readQueueMessage(childName);
                    // check if we have a valid message
                    if ((message == null) || message.isHidden()) {
                        continue;
                    }
                    // try to consume the message
                    if (!message.consume(false)) {
                        continue;
                    }
                    return message;
                }
            }
        }

        // at this point no children are available
        if (abortTime <= 0) {
            // abort
            return null;
        }

        // wait for the timeout
        final long diff = abortTime - System.currentTimeMillis();
        if (diff > 0) {
            Thread.sleep(Math.max(diff / 2, 250));
        } else {
            // wait time elapsed
            return null;
        }
    }
}