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

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

Introduction

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

Prototype

public static <F, T> Collection<T> transform(Collection<F> fromCollection, Function<? super F, T> function) 

Source Link

Document

Returns a collection that applies function to each element of fromCollection .

Usage

From source file:com.himanshu.utilities.guava.ListTransformDemo.java

public static void main(String[] args) {
    List<WrapperA> wrapperAList = new ArrayList<WrapperA>();
    wrapperAList.add(new WrapperA("test 1"));
    wrapperAList.add(new WrapperA("test 2"));
    wrapperAList.add(new WrapperA("test 3"));

    Collection<WrapperB> wrapperBList = Collections2.transform(wrapperAList,
            new Function<WrapperA, WrapperB>() {

                @Override//from   ww w.  j  a  va 2s. c  om
                public WrapperB apply(WrapperA arg0) {
                    return new WrapperB(arg0.getName(), UUID.randomUUID().toString());
                }
            });
    System.out.println("WrapperA : " + wrapperAList);
    System.out.println("WrapperB : " + wrapperBList);
}

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  a2 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:net.bobah.mail.Dupes.java

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

    final CommandLineParser parser = new PosixParser();
    final Options options = new Options()
            .addOption("j", "threads", true, "number of parallel threads to use for analyzing")
            .addOption("hash", true,
                    "hash function to use, possible values: " + Arrays.toString(Hashes.values()))
            .addOption("dir", true, "add directory to search");
    final CommandLine cmdline = parser.parse(options, args);

    final int threads = Integer.valueOf(
            cmdline.getOptionValue("threads", String.valueOf(Runtime.getRuntime().availableProcessors())));
    final HashFunction hash = Hashes.valueOf(cmdline.getOptionValue("hash", "adler32")).hashfunc;
    final File[] dirs = Collections2
            .transform(Arrays.asList(cmdline.getOptionValues("dir")), new Function<String, File>() {
                @Override/*from   w  w  w. jav a 2s  .c o m*/
                public File apply(String from) {
                    return new File(from);
                }
            }).toArray(new File[] {});

    log.info("hash: {}, threads: {}, dirs: {} in total", hash, threads, dirs.length);
    try {
        new Dupes(threads, hash, dirs).run();
    } finally {
        Utils.shutdownLogger();
    }
}

From source file:gt.org.ms.api.requesting.ValidationsHelper.java

public static <T> T findBestMatchItem(final String param, List<T> options) {
    List<MatchItem> weights = new ArrayList<MatchItem>(
            Collections2.transform(options, new Function<T, MatchItem>() {
                @Override//from  w  w w .  j a  va  2s . c o  m
                public MatchItem apply(T f) {
                    return new MatchItem(
                            StringUtils.getLevenshteinDistance(param.toLowerCase(), f.toString().toLowerCase()),
                            f);
                }
            }));

    Collections.sort(weights);
    //fot those objects without tostring implementation it will be wrong so better return null
    return (T) weights.get(0).value;
}

From source file:com.parking.rest.dto.VehicleDto.java

public static Collection<VehicleDto> fromBeanCollection(Collection<Vehicle> vehicles) {
    return Collections2.transform(vehicles, new Function<Vehicle, VehicleDto>() {
        @Override//from w w w  .  j a va2 s. co  m
        public VehicleDto apply(Vehicle vehicle) {
            return fromBean(vehicle);
        }
    });
}

From source file:ca.cutterslade.match.scheduler.Day.java

static ImmutableSet<Day> forNames(Set<String> days) {
    return ImmutableSet.copyOf(Collections2.transform(days, new Function<String, Day>() {

        @Override/*from ww  w  .ja v  a 2s.c  o  m*/
        public Day apply(String name) {
            return new Day(name);
        }
    }));
}

From source file:org.mayocat.addons.store.dbi.AddonsHelper.java

public static <T extends Identifiable & HasAddons> List<T> withAddons(List<T> entities, AddonsDAO dao) {
    Collection<UUID> ids = Collections2.transform(entities, new Function<T, UUID>() {
        @Override//w w w .ja  v a2 s  .com
        public UUID apply(final T entity) {
            return entity.getId();
        }
    });
    if (ids.size() <= 0) {
        return entities;
    }
    List<AddonGroup> addons = dao.findAllAddonsForIds(new ArrayList(ids));
    Map<UUID, List<AddonGroup>> addonsForEntity = Maps.newHashMap();
    for (AddonGroup addon : addons) {
        if (!addonsForEntity.containsKey(addon.getEntityId())) {
            addonsForEntity.put(addon.getEntityId(), new ArrayList<AddonGroup>());
        }
        addonsForEntity.get(addon.getEntityId()).add(addon);
    }
    for (T entity : entities) {
        if (addonsForEntity.containsKey(entity.getId())) {
            entity.setAddons(asMap(addonsForEntity.get(entity.getId())));
        }
    }
    return entities;
}

From source file:ca.cutterslade.match.scheduler.Gym.java

static ImmutableSet<Gym> forNames(Set<String> names) {
    return ImmutableSet.copyOf(Collections2.transform(names, new Function<String, Gym>() {

        @Override//from www . j av  a2  s. c om
        public Gym apply(String name) {
            return new Gym(name);
        }
    }));
}

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:gov.bnl.channelfinder.ChannelUtil.java

/**
 * Return a list of tag names associated with this channel
 * //w w  w .  java  2  s  .  c o  m
 * @param channel channel to be processed
 * @return Collection of names of tags
 */
public static Collection<String> getTagNames(XmlChannel channel) {
    return Collections2.transform(channel.getTags(), new Function<XmlTag, String>() {
        @Override
        public String apply(XmlTag tag) {
            return tag.getName();
        }
    });
}