Example usage for java.util TreeMap keySet

List of usage examples for java.util TreeMap keySet

Introduction

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

Prototype

public Set<K> keySet() 

Source Link

Document

Returns a Set view of the keys contained in this map.

Usage

From source file:spec.reporter.Utils.java

public static void generateMainChart(double compositeScore, TreeMap<String, Double> scores) {

    // Valid benchmarks + room for all possible extra - compiler, crypto, scimark, scimark.small, scimark.large, startup, xml, composite score
    Color[] colors = new Color[scores.size() + 8];

    // create the dataset...
    DefaultCategoryDataset dataset = new DefaultCategoryDataset();
    int count = 0;

    Iterator<String> iteratorBenchmarks = scores.keySet().iterator();
    while (iteratorBenchmarks.hasNext()) {
        String key = iteratorBenchmarks.next();
        Double score = scores.get(key);
        if (Utils.isValidScore(score)) {
            dataset.addValue(score, key, key);
            colors[count++] = (Color) colorMap.get(key);
        }/*ww w. j a  v  a 2  s.c  om*/
    }

    if (Utils.isValidScore(compositeScore)) {
        dataset.addValue(compositeScore, Utils.CSCORE_NAME, Utils.CSCORE_NAME);
        colors[count++] = (Color) colorMap.get(Utils.CSCORE_NAME);
    }

    JFreeChart chart = ChartFactory.createStackedBarChart("Scores", // chart title
            "", // domain axis label
            "", dataset, // data
            PlotOrientation.HORIZONTAL, // orientation
            false, // include legend
            false, // tooltips?
            false // URLs?
    );

    CategoryItemRenderer renderer = chart.getCategoryPlot().getRendererForDataset(dataset);
    for (int i = 0; i < count; i++) {
        Color paint = (Color) colors[i];
        if (paint != null) {
            renderer.setSeriesPaint(i, paint);
        }
    }

    try {
        ChartUtilities.saveChartAsJPEG(new File(getFullImageName("all")), chart, 600,
                50 + (dataset.getRowCount()) * 20);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.etudes.util.HtmlHelper.java

/**
 * Clean some user entered HTML. Assures well formed HTML. Assures all anchor tags have target=_blank. Assures all tag attributes are in determined (alpha) order.
 * /* www .j  a va  2  s  .  c  o m*/
 * @param source
 *        The source HTML
 * @param fragment
 *        if true, return a fragment of html, else return a complete html document.
 * @return The cleaned up HTML.
 */
protected static String cleanWithHtmlCleaner(String source, boolean fragment) {
    if (source == null)
        return null;

    // http://htmlcleaner.sourceforge.net
    // http://mvnrepository.com/artifact/net.sourceforge.htmlcleaner/htmlcleaner/2.2
    HtmlCleaner cleaner = new HtmlCleaner();
    cleaner.getProperties().setOmitXmlDeclaration(true);
    cleaner.getProperties().setTranslateSpecialEntities(false);
    cleaner.getProperties().setOmitComments(true);

    TagNode node = cleaner.clean(source);

    node.traverse(new TagNodeVisitor() {
        public boolean visit(TagNode tagNode, HtmlNode htmlNode) {
            if (htmlNode instanceof TagNode) {
                TagNode tag = (TagNode) htmlNode;
                String tagName = tag.getName();
                if ("a".equals(tagName)) {
                    // if there is a href attribute, and it does not begin with # (a link to an anchor), add a target attribute
                    String href = tag.getAttributeByName("href");
                    if ((href != null) && (!href.startsWith("#"))) {
                        tag.setAttribute("target", "_blank");
                    }
                }

                // order the tag attributes
                Map<String, String> attributes = tag.getAttributes();
                TreeMap<String, String> attr = new TreeMap<String, String>();
                attr.putAll(attributes);

                for (String key : attr.keySet()) {
                    tag.removeAttribute(key);
                }

                for (String key : attr.keySet()) {
                    String value = attr.get(key);

                    // fix up style attributes
                    if ("style".equalsIgnoreCase(key)) {
                        value = canonicalStyleAttribute(value);
                    }

                    tag.setAttribute(key, value);
                }
            }

            return true;
        }
    });

    String rv = "";
    final HtmlSerializer serializer = new CompactHtmlSerializer(cleaner.getProperties());

    try {
        TagNode nodeToGet = node;
        boolean omitEnvelope = false;

        if (fragment) {
            Object[] nodes = node.evaluateXPath("//body");
            if (nodes.length == 1) {
                nodeToGet = (TagNode) (nodes[0]);
                omitEnvelope = true;
            }
        }

        rv = serializer.getAsString(nodeToGet, "UTF-8", omitEnvelope);
    } catch (XPatherException e) {
    } catch (IOException e) {
    }

    return rv;
}

From source file:com.powers.wsexplorer.gui.GUIUtil.java

public static Listener createTextSortListener(final Table table, final Map<String, String> map,
        final boolean sortOnValues) {

    Listener sortListener = new Listener() {
        public void handleEvent(Event e) {

            final int direction = table.getSortDirection();

            Collator collator = Collator.getInstance(Locale.getDefault());
            TableColumn column = (TableColumn) e.widget;

            Set<String> keys = null;
            List<String> l = new LinkedList<String>();
            Iterator<String> itr = null;

            if (sortOnValues) {

                TreeMap<String, String> tm = new TreeMap<String, String>(
                        new MapValueComparator(map, direction == SWT.DOWN));
                tm.putAll(map);/* ww  w. j a v a 2s  . co  m*/

                if (direction == SWT.DOWN) {
                    table.setSortDirection(SWT.UP);
                } else {
                    table.setSortDirection(SWT.DOWN);
                }

                itr = tm.keySet().iterator();
            } else {

                keys = map.keySet();
                l.addAll(keys);
                Collections.sort(l, collator);

                if (direction == SWT.DOWN) {
                    Collections.reverse(l);
                    table.setSortDirection(SWT.UP);
                } else {
                    table.setSortDirection(SWT.DOWN);
                }

                itr = l.iterator();
            }

            // remove all table data
            table.removeAll();

            String key = null;
            String value = null;

            while (itr.hasNext()) {
                key = itr.next();
                if (StringUtils.isNotBlank(key)) {
                    TableItem ti = new TableItem(table, SWT.BORDER);
                    ti.setText(0, key);
                    value = map.get(key);
                    if (StringUtils.isNotBlank(value)) {
                        ti.setText(1, value);
                    }
                }

            }

            table.setSortColumn(column);
        }
    };

    return sortListener;
}

From source file:com.sfs.DataFilter.java

/**
 * Parses the text data into a collection.
 *
 * @param text the text//w  w  w  .  j  av  a2  s  .  com
 *
 * @return the collection< string>
 */
public static Collection<String> parseTextDataToCollection(final String text) {

    final Collection<String> textList = new ArrayList<String>();

    if (StringUtils.isNotBlank(text)) {
        TreeMap<Integer, TreeMap<Integer, String>> parsedMap = DataFilter.parseTextData(text);

        if (parsedMap != null) {
            for (Integer row : parsedMap.keySet()) {
                TreeMap<Integer, String> colMap = parsedMap.get(row);
                if (colMap != null) {
                    for (Integer col : colMap.keySet()) {
                        final String value = colMap.get(col);
                        if (StringUtils.isNotBlank(value)) {
                            textList.add(value.trim());
                        }
                    }
                }
            }
        }
    }
    return textList;
}

From source file:com.core.util.wx.PayUtils.java

/**
 * ?????// w w  w.j a  v  a  2  s.  c o m
 */
public static String formatBizQueryParaMap(Map<String, String> paraMap, boolean urlencode) {
    StringBuilder sb = new StringBuilder();
    TreeMap<String, String> sortMap = new TreeMap<String, String>(paraMap);
    if (urlencode) {
        try {
            for (String key : sortMap.keySet()) {
                sb.append(key).append("=").append(URLEncoder.encode(sortMap.get(key), "UTF-8")).append("&");
            }
        } catch (UnsupportedEncodingException e) {
            LOG.error(e.getMessage(), e);
        }
    } else {
        for (String key : sortMap.keySet()) {
            sb.append(key).append("=").append(sortMap.get(key)).append("&");
        }
    }

    if (sb.length() > 0) {
        sb.deleteCharAt(sb.length() - 1);
    }
    return sb.toString();
}

From source file:nl.uva.sne.commons.SemanticUtils.java

public static Set<Term> tf_idf_Disambiguation(Set<Term> possibleTerms, Set<String> nGrams, String lemma,
        double confidence, boolean matchTitle) throws IOException, JWNLException, ParseException {
    List<List<String>> allDocs = new ArrayList<>();
    Map<String, List<String>> docs = new HashMap<>();
    if (possibleTerms == null || possibleTerms.size() < 10) {
        return null;
    }//from   w ww  .  j a  v  a 2s. co m
    for (Term tv : possibleTerms) {
        Set<String> doc = SemanticUtils.getDocument(tv);
        allDocs.add(new ArrayList<>(doc));
        docs.put(tv.getUID(), new ArrayList<>(doc));
    }

    Set<String> contextDoc = new HashSet<>();
    for (String s : nGrams) {
        if (s.contains("_")) {
            String[] parts = s.split("_");
            for (String token : parts) {
                if (token.length() >= 1 && !token.contains(lemma)) {
                    contextDoc.add(token);
                }
            }
        } else if (s.length() >= 1 && !s.contains(lemma)) {
            contextDoc.add(s);
        }
    }
    docs.put("context", new ArrayList<>(contextDoc));

    Map<String, Map<String, Double>> featureVectors = new HashMap<>();
    for (String k : docs.keySet()) {
        List<String> doc = docs.get(k);
        Map<String, Double> featureVector = new TreeMap<>();
        for (String term : doc) {
            if (!featureVector.containsKey(term)) {
                double tfidf = tfIdf(doc, allDocs, term);
                featureVector.put(term, tfidf);
            }
        }
        featureVectors.put(k, featureVector);
    }

    Map<String, Double> contextVector = featureVectors.remove("context");

    Map<String, Double> scoreMap = new HashMap<>();
    for (String key : featureVectors.keySet()) {
        Double similarity = cosineSimilarity(contextVector, featureVectors.get(key));

        for (Term t : possibleTerms) {
            if (t.getUID().equals(key)) {

                String stemTitle = stem(t.getLemma().toLowerCase());
                String stemLema = stem(lemma);
                //                    List<String> subTokens = new ArrayList<>();
                //                    if (!t.getLemma().toLowerCase().startsWith("(") && t.getLemma().toLowerCase().contains("(") && t.getLemma().toLowerCase().contains(")")) {
                //                        int index1 = t.getLemma().toLowerCase().indexOf("(") + 1;
                //                        int index2 = t.getLemma().toLowerCase().indexOf(")");
                //                        String sub = t.getLemma().toLowerCase().substring(index1, index2);
                //                        subTokens.addAll(tokenize(sub, true));
                //                    }
                //
                //                    List<String> nTokens = new ArrayList<>();
                //                    for (String s : nGrams) {
                //                        if (s.contains("_")) {
                //                            String[] parts = s.split("_");
                //                            for (String token : parts) {
                //                                nTokens.addAll(tokenize(token, true));
                //                            }
                //                        } else {
                //                            nTokens.addAll(tokenize(s, true));
                //                        }
                //                    }
                //                    if (t.getCategories() != null) {
                //                        for (String s : t.getCategories()) {
                //                            if (s != null && s.contains("_")) {
                //                                String[] parts = s.split("_");
                //                                for (String token : parts) {
                //                                    subTokens.addAll(tokenize(token, true));
                //                                }
                //                            } else if (s != null) {
                //                                subTokens.addAll(tokenize(s, true));
                //                            }
                //                        }
                //                    }
                ////                    System.err.println(t.getGlosses());
                //                    Set<String> intersection = new HashSet<>(nTokens);
                //                    intersection.retainAll(subTokens);
                //                    if (intersection.isEmpty()) {
                //                        similarity -= 0.1;
                //                    }
                int dist = edu.stanford.nlp.util.StringUtils.editDistance(stemTitle, stemLema);
                similarity = similarity - (dist * 0.05);
                t.setConfidence(similarity);
            }
        }
        scoreMap.put(key, similarity);
    }

    if (scoreMap.isEmpty()) {
        return null;
    }

    ValueComparator bvc = new ValueComparator(scoreMap);
    TreeMap<String, Double> sorted_map = new TreeMap(bvc);
    sorted_map.putAll(scoreMap);
    //        System.err.println(sorted_map);

    Iterator<String> it = sorted_map.keySet().iterator();
    String winner = it.next();

    Double s1 = scoreMap.get(winner);
    if (s1 < confidence) {
        return null;
    }

    Set<Term> terms = new HashSet<>();
    for (Term t : possibleTerms) {
        if (t.getUID().equals(winner)) {
            terms.add(t);
        }
    }
    if (!terms.isEmpty()) {
        return terms;
    } else {
        Logger.getLogger(SemanticUtils.class.getName()).log(Level.INFO, "No winner");
        return null;
    }
}

From source file:com.sangupta.jerry.oauth.OAuthUtils.java

/**
 * Read all oauth params from the given map of parameters.
 * //from  ww  w .  ja va  2s .  c o  m
 * @param params
 * @param signature
 * @return
 */
private static String getAllOAuthParams(TreeMap<String, String> params) {
    StringBuilder builder = new StringBuilder();
    boolean first = true;

    for (String key : params.keySet()) {
        if (!key.startsWith("oauth_")) {
            continue;
        }

        if (!first) {
            builder.append(',');
        } else {
            first = false;
        }

        builder.append(key);
        builder.append("=\"");
        builder.append(UriUtils.encodeURIComponent(params.get(key), true));
        builder.append('"');
    }

    return builder.toString();
}

From source file:me.philnate.textmanager.updates.Updater.java

/**
 * checks what the actual db version is, if an old version is encountered
 * appropriate updates are performed to get the db to the latest version
 *///  www.jav a2 s.c  om
public static void checkUpdateNeeded(String packageName) {
    checkArgument(StringUtils.isNotBlank(packageName), "You must insert a packageName");
    TreeMap<Version, Class<? extends Update>> updates = createUpdateList(packageName);
    Setting v = Setting.find("version");
    // check that an version is set, if none was found set it to 1
    LOG.info(format("Database version is %s", v.getValue()));
    if (StringUtils.isBlank(v.getValue())) {
        Version db = (Version) ComparatorUtils.min(startVersion, updates.lastKey(), null);
        LOG.debug(String.format("No Version set, assuming []", db.toString()));
        v = new Setting("version", db);
        ds.save(v);
    }
    LOG.info(format("Found these Database upgrades: '%s'", updates.keySet()));
    for (Version vers : updates.keySet()) {
        if (vers.compareTo(new Version(v.getValue())) < Version.AFTER) {
            // if version is smaller than actual db version we have nothing
            // todo here
            LOG.debug(format("Database is already newer than '%s'", vers));
            continue;
        }
        try {
            LOG.info(format("Going to update Database to version '%s'", vers));
            backUp();
            // create new Instance
            Update up = updates.get(vers).newInstance();
            // verify that everything is met for this update
            up.preCheck();
            // do the actual update
            up.upgrade();
            // verify that everything is as expected
            up.postCheck();
            // update the version
            v.setValue(vers.toString()).save();
        } catch (Exception e) {
            // in case of an exception stop further rollback and stop
            // further updates
            LOG.error("Update process caused an exception going to rollback", e);
            rollback();
            return;
        } finally {
            // finally drop backup directory to avoid to get conflicting
            // data versions
            try {
                FileUtils.deleteDirectory(backUpPath);
            } catch (IOException e) {
                LOG.error("Could not remove file", e);
            }
        }
    }
}

From source file:module.entities.NameFinder.DB.java

public static void insertJsonResponse(int curConsId, TreeMap<Integer, String> input) throws SQLException {
    try {/*  w w  w  .  ja v a  2  s.  c  o m*/
        String insertSQL = "INSERT INTO enhancedentities " + "(consultation_id,article_id,json_text) VALUES"
                + "(?,?,?);";
        PreparedStatement prepStatement = connection.prepareStatement(insertSQL);
        //            connection.setAutoCommit(false);
        for (int curArticle : input.keySet()) {
            String json_text = input.get(curArticle);
            prepStatement.setInt(1, curConsId);
            prepStatement.setInt(2, curArticle);
            prepStatement.setString(3, json_text);
            //                prepStatement.executeUpdate();
            prepStatement.addBatch();
        }
        prepStatement.executeBatch();
        //            connection.commit();
        prepStatement.close();

        //            for (int i = 0; i<x.length; i++){
        //                System.out.println(x[i]);
        //            }
    } catch (BatchUpdateException ex) {
        ex.printStackTrace();
        //            System.out.println(ex.getNextException());
    }
}

From source file:module.entities.NameFinder.DB.java

public static void insertDemocracitConsultationMinister(TreeMap<Integer, String> consultationCountersign,
        TreeMap<Integer, String> consultationCounterrole) throws SQLException {
    try {//from w  w w.  j a  va 2s .  co m
        String sql = "INSERT INTO consultations_ner "
                + "(id,countersigned_name, countersigned_position) VALUES " + "(?,?,?)";
        PreparedStatement prepStatement = connection.prepareStatement(sql);
        for (int consId : consultationCountersign.keySet()) {
            prepStatement.setInt(1, consId);
            prepStatement.setString(2, consultationCountersign.get(consId));
            if (consultationCounterrole.get(consId) != null) {
                prepStatement.setString(3, consultationCounterrole.get(consId));
            } else {
                prepStatement.setString(3, "");
            }
            prepStatement.addBatch();
        }
        prepStatement.executeBatch();
        prepStatement.close();
    } catch (BatchUpdateException ex) {
        //            ex.printStackTrace();
        System.out.println(ex.getNextException());
    }
}