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:br.org.indt.mobisus.common.ResultWriter.java

public void write() throws ParserConfigurationException, Exception {
    logger.info("creatint result file in " + resultPath);
    Document xmldoc = null;//from   w w w .  j a v a  2  s. c  o  m
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    DOMImplementation impl = builder.getDOMImplementation();
    Element answerElement = null;
    Element categoryElement = null;
    Element text = null;
    Element title = null;
    Element lat = null;
    Element lon = null;
    Element other = null;
    Node titleText = null;
    Node nodeStr = null;

    xmldoc = impl.createDocument(null, "result", null);

    Element root = xmldoc.getDocumentElement();

    root.setAttribute("r_id", result.getResultId());
    root.setAttribute("s_id", result.getSurveyId());
    root.setAttribute("u_id", result.getUserId());
    root.setAttribute("time", result.getTime());

    if (result.getLatitude() != null) {
        lat = xmldoc.createElementNS(null, "latitude");
        titleText = xmldoc.createTextNode(result.getLatitude());
        lat.appendChild(titleText);
        root.appendChild(lat);
    }

    if (result.getLongitude() != null) {
        lon = xmldoc.createElementNS(null, "longitude");
        titleText = xmldoc.createTextNode(result.getLongitude());
        lon.appendChild(titleText);
        root.appendChild(lon);
    }

    title = xmldoc.createElementNS(null, "title");
    titleText = xmldoc.createTextNode("");
    title.appendChild(titleText);
    root.appendChild(title);

    TreeMap<Integer, Category> categories = survey.getCategories();
    Iterator<Category> iteratorCat = categories.values().iterator();
    while (iteratorCat.hasNext()) {
        Category category = iteratorCat.next();
        categoryElement = xmldoc.createElementNS(null, "category");
        categoryElement.setAttribute("name", category.getName());
        categoryElement.setAttribute("id", String.valueOf(category.getId()));
        root.appendChild(categoryElement);
        Integer categoryId = new Integer(category.getId());
        Vector<Field> questions = category.getFields();
        for (Field question : questions) {
            answerElement = xmldoc.createElementNS(null, "answer");
            answerElement.setAttributeNS(null, "type", question.getXmlType());
            answerElement.setAttributeNS(null, "id", String.valueOf(question.getId()));
            answerElement.setAttributeNS(null, "visited", "false");
            Field answer = result.getCategories().get(categoryId).getFieldById(question.getId());

            if (question.getFieldType() == FieldType.CHOICE) {
                ArrayList<Item> items = answer.getChoice().getItems();
                for (Item item : items) {
                    if (item.getOtr() == null || item.getOtr().equals("0")) {
                        nodeStr = xmldoc.createTextNode("" + item.getIndex());
                        text = xmldoc.createElementNS(null, question.getElementName());
                        text.appendChild(nodeStr);
                        answerElement.appendChild(text);
                        categoryElement.appendChild(answerElement);
                    } else {
                        nodeStr = xmldoc.createTextNode(item.getValue());
                        other = xmldoc.createElementNS(null, "other");
                        other.setAttributeNS(null, "index", "" + item.getIndex());
                        other.appendChild(nodeStr);
                        answerElement.appendChild(other);
                        categoryElement.appendChild(answerElement);
                    }
                }
            } else {
                nodeStr = xmldoc.createTextNode((answer.getValue() == null ? "" : answer.getValue()));
                text = xmldoc.createElementNS(null, question.getElementName());
                text.appendChild(nodeStr);
                answerElement.appendChild(text);
                categoryElement.appendChild(answerElement);
            }

            if ((question.getCategoryId() == survey.getDisplayCategory())
                    && (question.getId() == survey.getDisplayQuestion())) {
                (root.getElementsByTagName("title")).item(0).setTextContent(answer.getValue());
            }

        }

    }

    ResultDeploy resultDeploy = new ResultDeploy(xmldoc, getNextResultFile());
    resultDeploy.deploy(resultPath);
}

From source file:util.ExpiringObjectPool.java

/**
 * Use this method to get objects from the pool. You must pass the
 * name of the bean, like "directory", "userpage" etc. It will look
 * for an expired bean in the queue, and return a reference to this
 * bean if it is found. If it does not find an expired bean, it will
 * create a new bean on the heap and add it to the queue if the 
 * max size of the queue has not been exceeded. If the max size of the
 * queue has been exceeded, it will not add it to the queue, and this
 * means the bean on the heap will be garbage collected. Over time
 * the max size of the pool can be calibrated. The method will log
 * a warning whenever, the max size of the queue is exceeded for a 
 * specific bean name./*from w  w w . ja  v  a 2  s . com*/
 *
 * @param beanName the name of the bean which corresponds to a queue
 * @return Object return the bean as an Object
 * @exception ObjException if anything goes wrong
 */
public synchronized Object newObject(String beanName) throws ObjException {
    if (disablePool) {
        Stringifier bean = null;
        try {
            Class myclass = (Class) queueMap.get(beanName);
            bean = (Stringifier) myclass.newInstance();
        } catch (Exception e) {
            throw new ObjException("Could not instantiate object of type " + beanName, e);
        }
        return bean;
    }

    sweepIfRequired(beanName);

    TreeMap beanMap = (TreeMap) objectMap.get((Object) beanName);
    if (beanMap == null) {
        throw new ObjException("No queue exists for " + beanName
                + ", update the spring config to add a new mapping for " + beanName);
    }
    Iterator iter = beanMap.values().iterator();
    Long age = new Long(System.currentTimeMillis());
    long counter = 1;

    while (iter.hasNext()) {
        counter++;
        Stringifier bean = (Stringifier) iter.next();
        if (!((Boolean) bean.getObject(POOL)).booleanValue()) {
            bean.reset();
            bean.setObject(AGE, age);
            bean.setObject(POOL, new Boolean(true));
            updateStats(beanName, counter, beanMap.size());
            return (Object) bean;
        }
    }

    updateStats(beanName, counter, beanMap.size());

    // didn't find an expired object in pool, allocating on heap now
    Stringifier bean = null;
    try {
        Class myclass = (Class) queueMap.get(beanName);
        bean = (Stringifier) myclass.newInstance();
    } catch (Exception e) {
        throw new ObjException("Could not instantiate object of type " + beanName, e);
    }

    // check if exceeded max objects on the pool
    if (beanMap.size() > maxObjects) {
        logger.warn("Object pool size " + maxObjects + ", exceeded for beanName " + beanName);
    } else {
        bean.setObject(POOL, new Boolean(true));
        bean.setObject(AGE, age);
        beanMap.put(new Long(System.currentTimeMillis()), bean);
    }
    return (Object) bean;
}

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

/**
 * This method loads the votes cast by a particular group of people It is
 * built on top of the items functionality, the significant difference being
 * only one vote can be cast by each person in the group.
 *
 * @param groupGUID the group guid/*from w  w  w  .j  ava  2 s  .  co  m*/
 *
 * @return the tree map< integer, vote bean>
 *
 * @throws WhichDoctorDaoException the which doctor dao exception
 */
public final TreeMap<Integer, VoteBean> load(final int groupGUID) throws WhichDoctorDaoException {

    if (groupGUID == 0) {
        throw new WhichDoctorDaoException("Sorry a group guid greater than 0 is required");
    }

    int year = 0;
    /* Load the group to get its year */
    try {
        GroupBean group = this.groupDAO.loadGUID(groupGUID);
        year = group.getYear();
    } catch (Exception e) {
        dataLogger.error("Error loading group associated with votes: " + e.getMessage());
    }

    TreeMap<Integer, Integer> eligibleVotes = new TreeMap<Integer, Integer>();
    TreeMap<Integer, VoteBean> votesCast = new TreeMap<Integer, VoteBean>();

    try {
        eligibleVotes = loadEligible(groupGUID);
    } catch (Exception e) {
        throw new WhichDoctorDaoException("Error loading eligible votes: " + e.getMessage());
    }

    // Load the vote items for the submitted group GUID
    TreeMap<String, ItemBean> items = new TreeMap<String, ItemBean>();
    try {
        items = this.itemDAO.load(groupGUID, true, "Vote", "Votes");
    } catch (Exception e) {
        dataLogger.error("Error loading votes cast: " + e.getMessage());
    }

    if (items != null) {
        for (ItemBean item : items.values()) {
            // Get the unique vote id for each person
            // Add each vote to the votesCast map
            VoteBean vote = new VoteBean();

            vote.setVoteNumber(PersonBean.getVoteNumber(item.getObject2GUID(), year));
            vote.setGroupGUID(item.getObject1GUID());

            if (eligibleVotes.containsKey(vote.getVoteNumber())) {

                // Set the basic details related to this vote and add it to
                // the treemap
                vote.setId(item.getId());
                vote.setGUID(item.getGUID());
                vote.setCandidateGUID(item.getWeighting());
                vote.setPermission(item.getPermission());
                vote.setActive(item.getActive());
                vote.setCreatedBy(item.getCreatedBy());
                vote.setCreatedDate(item.getCreatedDate());
                vote.setCreatedUser(item.getCreatedUser());
                vote.setModifiedBy(item.getModifiedBy());
                vote.setModifiedDate(item.getModifiedDate());
                vote.setModifiedUser(item.getModifiedUser());

                // Add this to the vote treemap if this person is allowed to
                // vote
                votesCast.put(vote.getVoteNumber(), vote);
            }
        }
    }
    return votesCast;
}

From source file:org.lockss.config.TdbPublisher.java

/** Print a full description of the publisher and all its titles */
public void prettyPrint(PrintStream ps, int indent) {
    ps.println(StringUtil.tab(indent) + "Publisher: " + name);
    TreeMap<String, TdbTitle> sorted = new TreeMap<String, TdbTitle>(CatalogueOrderComparator.SINGLETON);
    for (TdbTitle title : getTdbTitles()) {
        sorted.put(title.getName(), title);
    }/*from  ww w .ja  v a 2s  .co m*/
    for (TdbTitle title : sorted.values()) {
        title.prettyPrint(ps, indent + 2);
    }
}

From source file:org.commoncrawl.service.listcrawler.CrawlHistoryManager.java

private static void updateTestItemStates(TreeMap<URLFP, ProxyCrawlHistoryItem> items) {

    for (ProxyCrawlHistoryItem item : items.values()) {
        item.setHttpResultCode(301);/*from ww w  . j a  v  a 2s.  com*/
        item.setRedirectURL(item.getOriginalURL() + "/redirect");
        item.setRedirectStatus(0);
        item.setRedirectHttpResult(200);
    }
}

From source file:org.lockss.config.TdbProvider.java

/** Print a full description of the publisher and all its titles */
public void prettyPrint(PrintStream ps, int indent) {
    ps.println(StringUtil.tab(indent) + "Provider: " + name);
    TreeMap<String, TdbAu> sorted = new TreeMap<String, TdbAu>(CatalogueOrderComparator.SINGLETON);
    for (TdbAu tdbAu : ausById.values()) {
        sorted.put(tdbAu.getName(), tdbAu);
    }/*  w  w w .  j av a2  s  .c  o m*/
    for (TdbAu tdbAu : sorted.values()) {
        tdbAu.prettyPrint(ps, indent + 2);
    }
}

From source file:com.jaeksoft.searchlib.learning.StandardLearner.java

@Override
public void classify(String data, FieldMap sourceFieldMap, int maxRank, double minScore,
        Collection<LearnerResultItem> collector) throws IOException, SearchLibException {
    rwl.r.lock();//from  ww w .  j  a v a  2 s.  c o  m
    try {
        Collection<TargetField> targetFields = checkIndex(sourceFieldMap);
        TreeMap<String, LearnerResultItem> targetMap = new TreeMap<String, LearnerResultItem>();
        fieldClassify(FIELD_SOURCE_DATA, null, data, targetMap);
        for (TargetField targetField : targetFields)
            fieldClassify(targetField.getBoostedName(), targetField.getBoost(), data, targetMap);
        for (LearnerResultItem learnerResultItem : targetMap.values()) {
            learnerResultItem.score = learnerResultItem.score / learnerResultItem.count
                    * Math.log1p(learnerResultItem.count);
            if (learnerResultItem.score > minScore)
                collector.add(learnerResultItem);
        }
    } finally {
        rwl.r.unlock();
    }
}

From source file:it.cnr.icar.eric.client.ui.thin.UserPreferencesBean.java

/** Returns a Collection of all locales as SelectItems. */
public Collection<SelectItem> getAllLocalesSelectItems() {
    if (allLocalesSelectItems == null) {
        TreeMap<String, SelectItem> selectItemsMap = new TreeMap<String, SelectItem>();
        Locale loc[] = Locale.getAvailableLocales();
        for (int i = 0; i < loc.length; i++) {
            String name = loc[i].getDisplayName(loc[i]);
            SelectItem item = new SelectItem(loc[i].toString(), name);
            selectItemsMap.put(name.toLowerCase(), item);
        }/*  w  w w.j  a  v  a  2  s . c  om*/
        Collection<SelectItem> all = new ArrayList<SelectItem>();
        all.addAll(selectItemsMap.values());
        allLocalesSelectItems = all;
    }
    return allLocalesSelectItems;
}

From source file:org.loklak.geo.GeoNames.java

/**
 * Match a given sequence mix with geolocations. First all locations matching with sequences larger than one
 * word are collected. If the result of this collection is not empty, the largest plase (measured by population)
 * is returned. If no such location can be found, matching with single-word locations is attempted and then also
 * the largest place is returned.//  w w  w .j a  va2  s  .co  m
 * @param mix the sequence mix
 * @return the largest place, matching with the mix, several-word matchings preferred
 */
private GeoMatch geomatch(LinkedHashMap<Integer, String> mix, final boolean preferLargePopulation) {
    TreeMap<Long, GeoMatch> cand = new TreeMap<>();
    int hitcount = 0;
    for (Map.Entry<Integer, String> entry : mix.entrySet()) {
        if (cand.size() > 0 && entry.getValue().indexOf(' ') < 0)
            return preferNonStopwordLocation(cand.values(), preferLargePopulation); // if we have location matches for place names with more than one word, return the largest place (measured by the population)
        List<Integer> locs = this.hash2ids.get(entry.getKey());
        if (locs == null || locs.size() == 0)
            continue;
        for (Integer i : locs) {
            GeoLocation loc = this.id2loc.get(i);
            if (loc != null) {
                for (String name : loc.getNames()) {
                    if (normalize(entry.getValue()).equals(normalize(name))) {
                        cand.put(hitcount++ - loc.getPopulation(), new GeoMatch(entry.getValue(), loc));
                        break;
                    }
                }
            }
        }
    }
    // finally return the largest place (if any found)
    return cand.size() > 0 ? preferNonStopwordLocation(cand.values(), preferLargePopulation) : null;
}

From source file:org.polymap.core.data.feature.FeatureRenderProcessor2.java

protected Image getMap(final Set<ILayer> layers, int width, int height, final ReferencedEnvelope bbox) {
    //        Logger wfsLog = Logging.getLogger( "org.geotools.data.wfs.protocol.http" );
    //        wfsLog.setLevel( Level.FINEST );

    // mapContext
    MapContext mapContext = mapContextRef.get(new Supplier<MapContext>() {
        public MapContext get() {
            log.debug("Creating new MapContext... ");
            // 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 w w w  .j  av  a  2 s  .  c  o m*/
            // add to mapContext
            MapContext result = new DefaultMapContext(bbox.getCoordinateReferenceSystem());
            for (ILayer layer : sortedLayers.values()) {
                try {
                    FeatureSource fs = PipelineFeatureSource.forLayer(layer, false);
                    log.debug("        FeatureSource: " + fs);
                    log.debug("            fs.getName(): " + fs.getName());

                    Style style = layer.getStyle().resolve(Style.class, null);
                    if (style == null) {
                        log.warn("            fs.getName(): " + fs.getName());
                        style = new DefaultStyles().findStyle(fs);
                    }
                    result.addLayer(fs, style);

                    // watch layer for style changes
                    LayerStyleListener listener = new LayerStyleListener(mapContextRef);
                    if (watchedLayers.putIfAbsent(layer, listener) == null) {
                        layer.addPropertyChangeListener(listener);
                    }
                } catch (IOException e) {
                    log.warn(e);
                    // FIXME set layer status and statusMessage
                } catch (PipelineIncubationException e) {
                    log.warn("No pipeline.", e);
                }
            }
            log.debug("created: " + result);
            return result;
        }
    });
    log.debug("using: " + mapContext);

    // render
    //        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
    //        GraphicsConfiguration gc = ge.getDefaultScreenDevice().getDefaultConfiguration();
    //        VolatileImage result = gc.createCompatibleVolatileImage( width, height, Transparency.TRANSLUCENT );

    BufferedImage result = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
    result.setAccelerationPriority(1);

    final Graphics2D g = result.createGraphics();
    //        log.info( "IMAGE: accelerated=" + result.getCapabilities( g.getDeviceConfiguration() ).isAccelerated() );

    try {
        final StreamingRenderer renderer = new StreamingRenderer();

        // rendering hints
        RenderingHints hints = new RenderingHints(RenderingHints.KEY_RENDERING,
                RenderingHints.VALUE_RENDER_SPEED);
        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 );

        // error handler
        renderer.addRenderListener(new RenderListener() {
            int featureCount = 0;

            @Override
            public void featureRenderer(SimpleFeature feature) {
                //                  if (++featureCount == 100) {
                //                      log.info( "Switch off antialiasing!" );
                //                      RenderingHints off = new RenderingHints(
                //                              RenderingHints.KEY_ANTIALIASING,
                //                              RenderingHints.VALUE_ANTIALIAS_OFF );
                //                      renderer.setJava2DHints( off );
                //                      g.setRenderingHints( off );
                //                  }
            }

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

        // 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();
        }
    }
}