Example usage for com.google.common.collect Collections2 filter

List of usage examples for com.google.common.collect Collections2 filter

Introduction

In this page you can find the example usage for com.google.common.collect Collections2 filter.

Prototype



@CheckReturnValue
public static <E> Collection<E> filter(Collection<E> unfiltered, Predicate<? super E> predicate) 

Source Link

Document

Returns the elements of unfiltered that satisfy a predicate.

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. j a  va  2  s.  c o 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:com.stackframe.bentographer.BentoGrapher.java

/**
 * @param args the command line arguments
 */// w w  w.  j av  a2s  .  c o m
public static void main(String[] args) throws Exception {
    Class.forName("org.sqlite.JDBC");
    File db = findDatabase();
    Connection connection = openConnection(db);
    try {
        Map<String, Library> libraries = getLibraries(connection);
        String selected = (String) select(libraries.keySet(), "Choose Library", "Library");
        Library library = libraries.get(selected);
        Collection<Field> fields = getFields(connection, library);

        fields = Collections2.filter(fields, new Predicate<Field>() {

            @Override
            public boolean apply(Field t) {
                return !ignorableFields.contains(t.type);
            }
        });

        Comparator<Field> dateComparator = makeTypeComparator("com.filemaker.bento.field.core.date");
        Comparator<Field> dateCreatedComparator = makeTypeComparator(
                "com.filemaker.bento.field.private.timestamp.dateCreated");
        Comparator<Field> dateModifiedComparator = makeTypeComparator(
                "com.filemaker.bento.field.private.timestamp.dateModified");
        Ordering<Field> xOrdering = Ordering.from(dateComparator).compound(dateCreatedComparator)
                .compound(dateModifiedComparator);
        Collection<Field> sortedXFields = xOrdering.immutableSortedCopy(fields);

        // FIXME: This depends on the implemenation of Field.toString() returning the type name. It should use a Renderer or something.
        final Field x = (Field) select(sortedXFields, "Choose X", "X");

        fields = Collections2.filter(fields, new Predicate<Field>() {

            @Override
            public boolean apply(Field t) {
                return t != x;
            }
        });

        Ordering<Field> yOrdering = Ordering.from(Collections.reverseOrder(dateModifiedComparator))
                .compound(Collections.reverseOrder(dateCreatedComparator))
                .compound(Collections.reverseOrder(dateComparator));
        Collection<Field> sortedYFields = yOrdering.immutableSortedCopy(fields);
        Field y = (Field) select(sortedYFields, "Choose Y", "Y");

        // FIXME: Make the rendering of dates smart. It looks like date is seconds since 1/1/2001 and is defined by Core Data.
        // FIXME: Make the graphs printable.
        // FIXME: Make it easy to dynamically add more Y values to same graph.
        // FIXME: Package up a binary that is easy to run. (JNLP/Web Startable?)
        // FIXME: Publish some screenshots to make it easier to understand what this is for.
        // FIXME: Make it possible to save graph paramters and automatically bring them back up.
        // FIXME: Make setting of min as 0 configurable.
        // FIXME: Fix graph to show actual data points on lines.

        makeGraph(connection, library, x, y);
    } finally {
        connection.close();
    }
}

From source file:com.stackframe.sarariman.PaidTimeOff.java

private static Collection<Employee> employeesToCredit(Sarariman sarariman) {
    return Collections2.filter(sarariman.getDirectory().getByUserName().values(), Utilities.activeFulltime);
}

From source file:org.dspace.xoai.data.DSpaceItem.java

private static List<Element> filter(List<Element> input, String name) {
    return Lists.newArrayList(Collections2.filter(input, new MetadataNamePredicate(name)));
}

From source file:org.broad.igv.util.collections.CollUtils.java

public static <T> List<T> filter(Collection<T> unfiltered, Predicate<? super T> predicate) {
    if (unfiltered == null)
        return null;
    Collection<T> filteredColl = Collections2.filter(unfiltered, predicate);
    List<T> filteredList = new ArrayList<T>(filteredColl);
    return filteredList;
}

From source file:org.apache.isis.core.commons.lang.Types.java

public static <T> Collection<T> filtered(final List<Object> candidates, final Class<T> type) {
    return Collections2.transform(Collections2.filter(candidates, Types.isOfType(type)), Types.castTo(type));
}

From source file:com.ning.billing.osgi.bundles.analytics.utils.BusinessInvoiceUtils.java

public static boolean isRevenueRecognizable(final InvoiceItem invoiceItem,
        final Collection<InvoiceItem> otherInvoiceItemsOnAllInvoices) {
    final Collection<InvoiceItem> otherInvoiceItems = Collections2.filter(otherInvoiceItemsOnAllInvoices,
            new Predicate<InvoiceItem>() {
                @Override//from  w  ww. ja  va 2 s.co  m
                public boolean apply(final InvoiceItem input) {
                    return input.getInvoiceId().equals(invoiceItem.getInvoiceId());
                }
            });

    // All items are recognizable except user generated credit (CBA_ADJ and CREDIT_ADJ on their own invoice)
    return !(InvoiceItemType.CBA_ADJ.equals(invoiceItem.getInvoiceItemType()) && (otherInvoiceItems.size() == 1
            && InvoiceItemType.CREDIT_ADJ.equals(otherInvoiceItems.iterator().next().getInvoiceItemType())
            && otherInvoiceItems.iterator().next().getInvoiceId().equals(invoiceItem.getInvoiceId())
            && otherInvoiceItems.iterator().next().getAmount()
                    .compareTo(invoiceItem.getAmount().negate()) == 0));
}

From source file:com.anathema_roguelike.main.utilities.datastructures.CollectionUtils.java

@SuppressWarnings(value = { "unchecked" })
public static <U, F extends U> Collection<F> filterByClass(Collection<U> unfiltered, final Class<F> cls) {
    return (Collection<F>) Collections2.filter(unfiltered, new Predicate<U>() {

        @Override//from  w  w  w .  j  a  v a  2s. c om
        public boolean apply(U superclass) {
            return cls.isAssignableFrom(superclass.getClass());
        }
    });
}

From source file:io.crate.planner.projection.Projections.java

public static Collection<? extends Projection> shardProjections(Collection<? extends Projection> projections) {
    return Collections2.filter(projections, Projection.IS_SHARD_PROJECTION);
}

From source file:io.crate.execution.dsl.projection.Projections.java

public static Collection<? extends Projection> shardProjections(Collection<? extends Projection> projections) {
    return Collections2.filter(projections, Projection.IS_SHARD_PROJECTION::test);
}