Example usage for com.google.common.collect Sets newTreeSet

List of usage examples for com.google.common.collect Sets newTreeSet

Introduction

In this page you can find the example usage for com.google.common.collect Sets newTreeSet.

Prototype

public static <E> TreeSet<E> newTreeSet(Comparator<? super E> comparator) 

Source Link

Document

Creates a mutable, empty TreeSet instance with the given comparator.

Usage

From source file:com.cloudbees.api.Main.java

public static void main(String[] args) throws Exception {

    File beesCredentialsFile = new File(System.getProperty("user.home"), ".bees/bees.config");
    Preconditions.checkArgument(beesCredentialsFile.exists(), "File %s not found", beesCredentialsFile);
    Properties beesCredentials = new Properties();
    beesCredentials.load(new FileInputStream(beesCredentialsFile));
    String apiUrl = "https://api.cloudbees.com/api";
    String apiKey = beesCredentials.getProperty("bees.api.key");
    String secret = beesCredentials.getProperty("bees.api.secret");
    BeesClient client = new BeesClient(apiUrl, apiKey, secret, "xml", "1.0");
    client.setVerbose(false);//from   w w w  . ja v  a 2  s .  co  m

    URL databasesUrl = Thread.currentThread().getContextClassLoader().getResource("databases.txt");
    Preconditions.checkNotNull(databasesUrl, "File 'databases.txt' NOT found in the classpath");

    Collection<String> databaseNames;
    try {
        databaseNames = Sets.newTreeSet(Resources.readLines(databasesUrl, Charsets.ISO_8859_1));
    } catch (Exception e) {
        throw Throwables.propagate(e);
    }

    databaseNames = Collections2.transform(databaseNames, new Function<String, String>() {
        @Nullable
        @Override
        public String apply(@Nullable String input) {
            // {host_db_create,<<"tco_q5rm">>,<<"TCO_q5rm">>,

            if (input == null)
                return null;

            if (input.startsWith("#"))
                return null;

            if (input.indexOf('"') == -1) {
                logger.warn("Skip invalid line {}", input);
                return null;
            }
            input = input.substring(input.indexOf('"') + 1);
            if (input.indexOf('"') == -1) {
                logger.warn("Skip invalid line {}", input);
                return null;
            }
            return input.substring(0, input.indexOf('"'));

        }
    });
    databaseNames = Collections2.filter(databaseNames, new Predicate<String>() {
        @Override
        public boolean apply(@Nullable String s) {
            return !Strings.isNullOrEmpty(s);
        }
    });

    Multimap<String, String> databasesByAccount = ArrayListMultimap.create();

    Class.forName("com.mysql.jdbc.Driver");

    for (String databaseName : databaseNames) {
        try {
            DatabaseInfo databaseInfo = client.databaseInfo(databaseName, true);
            databasesByAccount.put(databaseInfo.getOwner(), databaseInfo.getName());
            logger.debug("Evaluate " + databaseInfo.getName());

            if (true == false) {
                // Hibernate
                logger.info("Hibernate {}", databaseName);
                Map<String, String> params = new HashMap<String, String>();
                params.put("database_id", databaseName);
                String url = client.getRequestURL("database.hibernate", params);
                String response = client.executeRequest(url);
                DatabaseInfoResponse apiResponse = (DatabaseInfoResponse) client.readResponse(response);
                logger.info("DB {} status: {}", apiResponse.getDatabaseInfo().getName(),
                        apiResponse.getDatabaseInfo().getStatus());

            }
            if (true == false) {
                // Hibernate
                logger.info("Activate {}", databaseName);
                Map<String, String> params = new HashMap<String, String>();
                params.put("database_id", databaseName);
                String url = client.getRequestURL("database.activate", params);
                String response = client.executeRequest(url);
                DatabaseInfoResponse apiResponse = (DatabaseInfoResponse) client.readResponse(response);
                logger.info("DB {} status: {}", apiResponse.getDatabaseInfo().getName(),
                        apiResponse.getDatabaseInfo().getStatus());
            }

            String dbUrl = "jdbc:mysql://" + databaseInfo.getMaster() + "/" + databaseInfo.getName();
            logger.info("Connect to {} user={}", dbUrl, databaseInfo.getUsername());
            Connection cnn = DriverManager.getConnection(dbUrl, databaseInfo.getUsername(),
                    databaseInfo.getPassword());
            cnn.setAutoCommit(false);
            cnn.close();

        } catch (Exception e) {
            logger.warn("Exception for {}", databaseName, e);
        }
    }

    System.out.println("OWNERS");
    for (String account : databasesByAccount.keySet()) {
        System.out.println(account + ": " + Joiner.on(", ").join(databasesByAccount.get(account)));
    }

}

From source file:cc.kave.episodes.mining.evaluation.ProposalHelper.java

public static <T extends Comparable<T>> TreeSet<Tuple<T, Double>> createSortedSet() {
    final TreeSet<Tuple<T, Double>> res = Sets.newTreeSet(new Comparator<Tuple<T, Double>>() {
        @Override//from www .  j  av  a2  s  .c o  m
        public int compare(final Tuple<T, Double> o1, final Tuple<T, Double> o2) {
            // higher probabilities will be sorted above lower ones
            int valueOrdering = Double.compare(o2.getSecond(), o1.getSecond());
            boolean areValuesEqual = valueOrdering == 0;
            if (areValuesEqual) {
                int orderOfFirstTupleMember = o1.getFirst().compareTo(o2.getFirst());
                return orderOfFirstTupleMember;
            } else {
                return valueOrdering;
            }
        }
    });
    return res;
}

From source file:org.apache.druid.collections.IntSetTestUtility.java

public static Set<Integer> getSetBits() {
    return Sets.newTreeSet(setBits);
}

From source file:org.apache.lens.cli.table.CollectionTableFactory.java

public static CollectionTable<XFlattenedColumn> getCollectionTable(Class<? extends XField> claz,
        final String table) {
    if (claz == XExprColumn.class) {
        return new CollectionTable<>(Sets.newTreeSet(new Comparator<XFlattenedColumn>() {
            @Override/*from   w  w  w.java  2  s .  c o m*/
            public int compare(XFlattenedColumn o1, XFlattenedColumn o2) {
                return o1.getExpression().getName().compareTo(o2.getExpression().getName());
            }
        }), new CollectionTable.RowProvider<XFlattenedColumn>() {
            @Override
            public String[][] getRows(XFlattenedColumn element) {
                return new String[][] { { nulltoBlank(element.getExpression().getName()),
                        nulltoBlank(element.getExpression().getDisplayString()),
                        nulltoBlank(element.getExpression().getDescription()),
                        expressionsAsString(element.getExpression().getExprSpec()), }, };
            }

            private String expressionsAsString(List<XExprSpec> exprSpec) {
                StringBuilder sb = new StringBuilder();
                String sep = "";
                for (XExprSpec spec : exprSpec) {
                    sb.append(sep);
                    sep = ", ";
                    List<String> clauses = Lists.newArrayList();
                    if (spec.getStartTime() != null) {
                        clauses.add("after " + spec.getStartTime());
                    }
                    if (spec.getEndTime() != null) {
                        clauses.add("before " + spec.getEndTime());
                    }
                    String sep1 = "";
                    if (clauses.isEmpty()) {
                        clauses.add("always valid");
                    }
                    for (String clause : clauses) {
                        sb.append(sep1).append(clause);
                        sep1 = " and ";
                    }
                    sb.append(": ");
                    sb.append(spec.getExpr());
                }
                return sb.toString();
            }
        }, "Name", "Display String", "Description", "Expr Specs");
    } else if (claz == XDimAttribute.class) {
        return new CollectionTable<>(Sets.newTreeSet(new Comparator<XFlattenedColumn>() {
            @Override
            public int compare(XFlattenedColumn o1, XFlattenedColumn o2) {
                if (o1 == null || o1.getDimAttribute() == null) {
                    return -1;
                } else if (o2 == null || o2.getDimAttribute() == null) {
                    return 1;
                } else if (table.equals(o1.getTableName()) && !table.equals(o2.getTableName())) {
                    return -1;
                } else if (table.equals(o2.getTableName()) && !table.equals(o1.getTableName())) {
                    return 1;
                } else {
                    if (o1.getTableName() == null) {
                        o1.setTableName("");
                    }
                    if (o2.getTableName() == null) {
                        o2.setTableName("");
                    }
                    if (o1.getChainName() == null) {
                        o1.setChainName("");
                    }
                    if (o2.getChainName() == null) {
                        o2.setChainName("");
                    }
                    int cmp = o1.getTableName().compareTo(o2.getTableName());
                    if (cmp != 0) {
                        return cmp;
                    }
                    cmp = o1.getChainName().compareTo(o2.getChainName());
                    if (cmp != 0) {
                        return cmp;
                    }
                    return o1.getDimAttribute().getName().compareTo(o2.getDimAttribute().getName());
                }
            }
        }), new CollectionTable.RowProvider<XFlattenedColumn>() {
            @Override
            public String[][] getRows(XFlattenedColumn element) {
                String prefix = XFlattenedColumnTable.firstNonNull(element.getChainName(),
                        element.getTableName());
                return new String[][] { {
                        (prefix == null || prefix.isEmpty() || prefix.equalsIgnoreCase(table) ? ""
                                : (prefix + ".")) + nulltoBlank(element.getDimAttribute().getName()),
                        nulltoBlank(element.getDimAttribute().getDisplayString()),
                        nulltoBlank(element.getDimAttribute().getDescription()), }, };
            }
        }, "Name", "Display String", "Description");
    } else if (claz == XMeasure.class) {
        return new CollectionTable<>(Sets.newTreeSet(new Comparator<XFlattenedColumn>() {
            @Override
            public int compare(XFlattenedColumn o1, XFlattenedColumn o2) {
                return o1.getMeasure().getName().compareTo(o2.getMeasure().getName());
            }
        }), new CollectionTable.RowProvider<XFlattenedColumn>() {
            @Override
            public String[][] getRows(XFlattenedColumn element) {
                return new String[][] { { nulltoBlank(element.getMeasure().getName()),
                        nulltoBlank(element.getMeasure().getDisplayString()),
                        nulltoBlank(element.getMeasure().getDescription()), }, };
            }
        }, "Name", "Display String", "Description");
    } else {
        return null;
    }
}

From source file:sg.atom.utils._commons.time.JodaUtils.java

public static ArrayList<Interval> condenseIntervals(Iterable<Interval> intervals) {
    ArrayList<Interval> retVal = Lists.newArrayList();

    TreeSet<Interval> sortedIntervals = Sets.newTreeSet(Comparators.intervalsByStartThenEnd());
    for (Interval interval : intervals) {
        sortedIntervals.add(interval);/*from w w w. j  av  a 2 s  .c  o  m*/
    }

    if (sortedIntervals.isEmpty()) {
        return Lists.newArrayList();
    }

    Iterator<Interval> intervalsIter = sortedIntervals.iterator();
    Interval currInterval = intervalsIter.next();
    while (intervalsIter.hasNext()) {
        Interval next = intervalsIter.next();

        if (currInterval.overlaps(next) || currInterval.abuts(next)) {
            currInterval = new Interval(currInterval.getStart(), next.getEnd());
        } else {
            retVal.add(currInterval);
            currInterval = next;
        }
    }
    retVal.add(currInterval);

    return retVal;
}

From source file:net.oneandone.maven.plugins.cycles.graph.GraphDotUtils.java

/**
 * @param component a graph//from  w w  w.  java  2 s  .  c  o  m
 * @param shorten whether to shorten the package names
 * @return a dot string
 */
public static String toDot(DirectedGraph<String, WeightedEdge> component, boolean shorten) {
    StringBuilder builder = new StringBuilder();
    Collection<WeightedEdge> feedbackArcs = FeedbackArcSet.feedbackArcs(component,
            new InstabilityVertexEvaluator<String>());

    TreeSet<WeightedEdge> sortedEdges = Sets.newTreeSet(new WeightedEdgeComparator(component));
    sortedEdges.addAll(component.getEdges());

    builder.append("digraph mygraph {\n");
    double maxEdgeWeight = getMaxEdgeWeight(component);
    for (WeightedEdge edge : sortedEdges) {
        builder.append("    ");
        builder.append(GraphDotUtils.edgeToDot(edge, component, shorten));

        builder.append("[");
        builder.append("label=\"" + (int) edge.getWeight() + "\"");
        double relativeImportance = edge.getWeight() / maxEdgeWeight;
        builder.append(",fontsize=" + (STANDARD_FONTSIZE + (FONT_SIZE * relativeImportance)));
        if (feedbackArcs.contains(edge)) {
            builder.append(",color=red,fontcolor=red,penwidth=3");
        }
        builder.append("]");

        builder.append(";\n");
    }
    builder.append("}\n");
    return builder.toString();
}

From source file:com.twitter.aurora.scheduler.base.Numbers.java

/**
 * Converts a set of integers into a set of contiguous closed ranges that equally represent the
 * input integers./*  www.j  a  v a  2  s  .c om*/
 * <p>
 * The resulting ranges will be in ascending order.
 *
 * @param values Values to transform to ranges.
 * @return Closed ranges with identical members to the input set.
 */
public static Set<Range<Integer>> toRanges(Iterable<Integer> values) {
    ImmutableSet.Builder<Range<Integer>> builder = ImmutableSet.builder();

    PeekingIterator<Integer> iterator = Iterators.peekingIterator(Sets.newTreeSet(values).iterator());

    // Build ranges until there are no numbers left.
    while (iterator.hasNext()) {
        // Start a new range.
        int start = iterator.next();
        int end = start;
        // Increment the end until the range is non-contiguous.
        while (iterator.hasNext() && (iterator.peek() == (end + 1))) {
            end++;
            iterator.next();
        }

        builder.add(Range.closed(start, end));
    }

    return builder.build();
}

From source file:com.opengamma.web.analytics.formatting.SurfaceFormatterUtils.java

static Object formatExpanded(Surface<Double, Double, Double> surface) {
    if (surface instanceof InterpolatedDoublesSurface) {
        List<Double> vol = Lists.newArrayList();
        // the x and y values won't necessarily be unique and won't necessarily map to a rectangular grid
        // this projects them onto a grid with values at every point
        Set<Double> xData = Sets.newTreeSet(Arrays.asList(surface.getXData()));
        Set<Double> yData = Sets.newTreeSet(Arrays.asList(surface.getYData()));
        for (Double y : yData) {
            for (Double x : xData) {
                vol.add(surface.getZValue(x, y));
            }//from  w w w .  j av a 2s .  c o m
        }
        Map<String, Object> results = Maps.newHashMap();
        results.put(X_VALUES, xData);
        results.put(X_LABELS, SurfaceFormatterUtils.getAxisLabels(xData));
        results.put(X_TITLE, ""); // TODO use labels from VolatilitySurface once they exist
        results.put(Y_VALUES, yData);
        results.put(Y_LABELS, SurfaceFormatterUtils.getAxisLabels(yData));
        results.put(Y_TITLE, ""); // TODO use labels from VolatilitySurface once they exist
        results.put(VOL, vol);
        return results;
    } else if (surface instanceof ConstantDoublesSurface) {
        Map<String, Object> results = Maps.newHashMap();
        results.put(LabelledMatrix2DFormatter.X_LABELS, Collections.singletonList("All"));
        results.put(LabelledMatrix2DFormatter.Y_LABELS, Collections.singletonList("All"));
        results.put(LabelledMatrix2DFormatter.MATRIX, Collections.singletonList(surface.getZData()));
        return results;
    } else {
        // TODO format as matrix
        // TODO this won't work - the cell value isn't an error so this makes no difference
        return new MissingValueFormatter(
                "Unable to format surface of type " + surface.getClass().getSimpleName());
    }
}

From source file:com.palantir.atlasdb.keyvalue.api.ColumnSelection.java

public static ColumnSelection valueOf(String serialized) {
    Set<byte[]> columns = Sets.newTreeSet(UnsignedBytes.lexicographicalComparator());
    for (String strColumn : serialized.split("\\s*,\\s*")) {
        strColumn = strColumn.trim();/*from   w ww  .  ja va 2s  .  co  m*/
        if (strColumn.equals("")) {
            continue;
        }
        byte[] column = PtBytes.decodeBase64(strColumn);
        assert !columns.contains(column);
        columns.add(column);
    }
    if (columns.isEmpty()) {
        return all();
    }
    return ColumnSelection.create(columns);
}

From source file:org.apache.druid.java.util.common.JodaUtils.java

public static ArrayList<Interval> condenseIntervals(Iterable<Interval> intervals) {
    ArrayList<Interval> retVal = Lists.newArrayList();

    final SortedSet<Interval> sortedIntervals;

    if (intervals instanceof SortedSet) {
        sortedIntervals = (SortedSet<Interval>) intervals;
    } else {//from ww  w.  j ava  2s.com
        sortedIntervals = Sets.newTreeSet(Comparators.intervalsByStartThenEnd());
        for (Interval interval : intervals) {
            sortedIntervals.add(interval);
        }
    }

    if (sortedIntervals.isEmpty()) {
        return Lists.newArrayList();
    }

    Iterator<Interval> intervalsIter = sortedIntervals.iterator();
    Interval currInterval = intervalsIter.next();
    while (intervalsIter.hasNext()) {
        Interval next = intervalsIter.next();

        if (currInterval.abuts(next)) {
            currInterval = new Interval(currInterval.getStart(), next.getEnd());
        } else if (currInterval.overlaps(next)) {
            DateTime nextEnd = next.getEnd();
            DateTime currEnd = currInterval.getEnd();
            currInterval = new Interval(currInterval.getStart(), nextEnd.isAfter(currEnd) ? nextEnd : currEnd);
        } else {
            retVal.add(currInterval);
            currInterval = next;
        }
    }
    retVal.add(currInterval);

    return retVal;
}