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.jayway.jaxrs.hateoas.support.ReflectionBasedHateoasLinkInjector.java

@SuppressWarnings({ "unchecked" })
@Override/*w w w .j a  v a 2  s .  c o m*/
public Object injectLinks(Object entity, LinkProducer<Object> linkProducer, final HateoasVerbosity verbosity) {
    try {
        Field field = ReflectionUtils.getFieldHierarchical(entity.getClass(), linksFieldName);

        if (Collection.class.isAssignableFrom(field.getType())) {

            field.set(entity, Collections2.transform(linkProducer.getLinks(entity),
                    new Function<HateoasLink, Map<String, Object>>() {
                        @Override
                        public Map<String, Object> apply(HateoasLink from) {
                            return from.toMap(verbosity);
                        }
                    }));
        } else {
            throw new IllegalArgumentException("Field '" + linksFieldName + "' is not a Collection object");
        }

        return entity;
    } catch (Exception e) {
        throw new HateoasInjectException(e);
    }
}

From source file:org.graylog2.security.InMemoryRolePermissionResolver.java

@Override
public Collection<Permission> resolvePermissionsInRole(String roleId) {
    final Set<String> permissions = resolveStringPermission(roleId);

    // copy to avoid reiterating all the time
    return Sets.newHashSet(Collections2.transform(permissions, new Function<String, Permission>() {
        @Nullable/*  w w  w .ja  v a 2s.c om*/
        @Override
        public Permission apply(@Nullable String input) {
            return new WildcardPermission(input);
        }
    }));
}

From source file:com.netflix.paas.cassandra.discovery.EurekaClusterDiscoveryService.java

@Override
public Collection<String> getClusterNames() {
    final Pattern regex = Pattern.compile(this.config.getString(PROPERTY_MATCH));

    return Collections2.filter(Collections2.transform(client.getApplications().getRegisteredApplications(),
            new Function<Application, String>() {
                @Override/*from   w w  w  . j av a 2  s.  c  o  m*/
                public String apply(Application app) {
                    return app.getName();
                }
            }), new Predicate<String>() {
                @Override
                public boolean apply(String clusterName) {
                    Matcher m = regex.matcher(clusterName);
                    return m.matches();
                }
            });
}

From source file:se.crafted.chrisb.ecoCreature.events.mappers.EntityKilledEventMapper.java

private Collection<DropEvent> createDropEvents(final EntityKilledEvent event) {
    final Player killer = event.getKiller();
    final DropConfig dropConfig = getDropConfig(killer.getWorld());
    event.setSpawnerMobTracker(dropConfig);

    Collection<AbstractDrop> drops = Collections2.transform(dropConfig.collectDrops(event),
            new Function<AbstractDrop, AbstractDrop>() {

                @Override/*from  w  ww. ja v a  2 s  .c o m*/
                public AbstractDrop apply(AbstractDrop drop) {
                    if (drop instanceof CoinDrop) {
                        CoinDrop coinDrop = (CoinDrop) drop;
                        coinDrop.setGain(dropConfig.getGainMultiplier(killer));
                        coinDrop.setParty(dropConfig.getPartyMembers(killer));
                        coinDrop.addParameter(MessageToken.CREATURE, coinDrop.getName())
                                .addParameter(MessageToken.ITEM, event.getWeaponName());
                    }

                    if (drop instanceof ItemDrop) {
                        ItemDrop itemDrop = (ItemDrop) drop;
                        if (dropConfig.isOverrideDrops() && !itemDrop.getItems().isEmpty()
                                || dropConfig.isClearOnNoDrops() && itemDrop.getItems().isEmpty()) {
                            event.getDrops().clear();
                        }

                        if (dropConfig.isClearEnchantedDrops()) {
                            Iterables.removeIf(event.getDrops(), new Predicate<ItemStack>() {

                                @Override
                                public boolean apply(ItemStack stack) {
                                    boolean notEmpty = !stack.getEnchantments().isEmpty();
                                    LoggerUtil.getInstance()
                                            .debugTrue("Cleared enchanted item: " + stack.getType(), notEmpty);
                                    return notEmpty;
                                }
                            });
                        }
                    }

                    if (drop instanceof EntityDrop) {
                        EntityDrop entityDrop = (EntityDrop) drop;
                        if (entityDrop.getEntityTypes().contains(EntityType.EXPERIENCE_ORB)) {
                            event.resetDroppedExp();
                        }
                    }

                    return drop;
                }
            });

    return drops.isEmpty() ? EMPTY_COLLECTION
            : Lists.newArrayList(new DropEvent(killer, drops, event.getClass()));
}

From source file:com.github.msoliter.iroh.container.resolvers.SubclassResolver.java

@Override
public Source resolve(final Field field) {

    /**// w ww.  j  a va  2 s  .  c  o m
     * Find all potential sources by filter on whether or not a source's
     * type can be assigned to the field's type.
     */
    Iterable<Source> potential = Iterables
            .concat(Collections2.transform(Collections2.filter(sources.keySet(), new Predicate<Class<?>>() {

                @Override
                public boolean apply(Class<?> type) {
                    return field.getType().isAssignableFrom(type);
                }
            }), new Function<Class<?>, Collection<Source>>() {

                @Override
                public Collection<Source> apply(Class<?> type) {
                    return sources.get(type);
                }
            }));

    /**
     * If there isn't exactly one source in the set, check if there's 
     * exactly one overriding source available, in case we're unit testing.
     */
    if (Iterables.size(potential) != 1) {
        Iterable<Source> overriding = Iterables.filter(potential, new Predicate<Source>() {

            @Override
            public boolean apply(Source source) {
                return source.isOverriding();
            }
        });

        if (Iterables.size(overriding) != 1) {
            throw new UnexpectedImplementationCountException(field.getType(),
                    Iterables.transform(potential, new Function<Source, Class<?>>() {

                        @Override
                        public Class<?> apply(Source source) {
                            return source.getType();
                        }
                    }));

        } else {
            return overriding.iterator().next();
        }

    } else {
        return potential.iterator().next();
    }
}

From source file:com.ning.billing.util.tag.api.DefaultTagUserApi.java

@Override
public List<TagDefinition> getTagDefinitions(final TenantContext context) {
    return ImmutableList.<TagDefinition>copyOf(Collections2.transform(
            tagDefinitionDao.getTagDefinitions(internalCallContextFactory.createInternalTenantContext(context)),
            new Function<TagDefinitionModelDao, TagDefinition>() {
                @Override//from  w ww  .j av  a2s .  c om
                public TagDefinition apply(final TagDefinitionModelDao input) {
                    return new DefaultTagDefinition(input, TagModelDaoHelper.isControlTag(input.getName()));
                }
            }));
}

From source file:com.ning.billing.invoice.api.svcs.DefaultInvoiceInternalApi.java

@Override
public Collection<Invoice> getUnpaidInvoicesByAccountId(final UUID accountId, final LocalDate upToDate,
        final InternalTenantContext context) {
    return Collections2.transform(dao.getUnpaidInvoicesByAccountId(accountId, upToDate, context),
            new Function<InvoiceModelDao, Invoice>() {
                @Override/*w w  w  .  j a v  a2s .com*/
                public Invoice apply(final InvoiceModelDao input) {
                    return new DefaultInvoice(input);
                }
            });
}

From source file:gt.org.ms.controller.home.handlers.BusqPersonasByRenglonHandler.java

@Override
public List<Persona> execute(BusquedaAvanzadaDto request) {
    List<Persona> personas = new ArrayList();
    List<FiltroAvanzadoDto> filtros = new ArrayList<FiltroAvanzadoDto>(Collections2.filter(request.getFiltros(),
            new com.google.common.base.Predicate<FiltroAvanzadoDto>() {
                @Override/*from   w ww. java2  s. c  om*/
                public boolean apply(FiltroAvanzadoDto t) {
                    return t.getCampo().equals(CampoBusquedaAvanzada.RENGLON);
                }
            }));
    for (final FiltroAvanzadoDto filtro : filtros) {
        if (filtro.getCampo().equals(CampoBusquedaAvanzada.RENGLON)) {
            final List<Integer> catRenglonesIds = new ArrayList();
            final Puestos inicio = puestosRepo.findOne(filtro.getValor1());
            catRenglonesIds.addAll(Collections2.transform(puestosRepo.findAll(new Specification() {
                @Override
                public Predicate toPredicate(Root root, CriteriaQuery cq, CriteriaBuilder cb) {

                    if (filtro.getComparador().equals(ComparadorBusqueda.MAYOR)) {
                        return cb.greaterThanOrEqualTo(root.get(Puestos_.valorNum), inicio.getValorNum());
                    }
                    if (filtro.getComparador().equals(ComparadorBusqueda.MENOR)) {
                        return cb.lessThanOrEqualTo(root.get(Puestos_.valorNum), inicio.getValorNum());
                    }
                    if (filtro.getComparador().equals(ComparadorBusqueda.IGUAL)) {
                        return cb.equal(root.get(Puestos_.valorNum), inicio.getValorNum());
                    }
                    if (filtro.getComparador().equals(ComparadorBusqueda.DIFERENTE)) {
                        return cb.notEqual(root.get(Puestos_.valorNum), inicio.getValorNum());
                    }
                    final Puestos fin = isNull(filtro.getValor2()) ? null
                            : puestosRepo.findOne(filtro.getValor2());
                    return cb.and(cb.like(root.get(Puestos_.tipo), C.CAT_PUESTOS_RENGLON),
                            cb.greaterThanOrEqualTo(root.get(Puestos_.valorNum), inicio.getValorNum()),
                            cb.lessThanOrEqualTo(root.get(Puestos_.valorNum), fin.getValorNum()));

                }
            }), new Function<Puestos, Integer>() {
                @Override
                public Integer apply(Puestos f) {
                    return f.getId();
                }
            }));
            final List<Integer> catPuestosNominalesIds = new ArrayList();

            catPuestosNominalesIds.addAll(Collections2.transform(puestosRepo.findAll(new Specification() {
                @Override
                public Predicate toPredicate(Root root, CriteriaQuery cq, CriteriaBuilder cb) {
                    return root.get(Puestos_.codigoPadre).in(catRenglonesIds);
                }
            }), new Function<Puestos, Integer>() {
                @Override
                public Integer apply(Puestos f) {
                    return f.getId();
                }
            }));
            personas.addAll(EntitiesHelper.getPersonas(new ArrayList<PersonaChildEntity>(
                    Collections2.transform(puestoPersonaRepo.findAll(new Specification() {
                        @Override
                        public Predicate toPredicate(Root root, CriteriaQuery cq, CriteriaBuilder cb) {
                            return root.get(Puesto_.fkPuestoNominal).in(catPuestosNominalesIds);
                        }
                    }), new Function<Puesto, RegistroLaboral>() {
                        @Override
                        public RegistroLaboral apply(Puesto f) {
                            return f.getFkRegistroLaboral();
                        }
                    }))));

        }
    }

    return personas;
}

From source file:models.AuthorisedUser.java

public boolean is(String roleName) {
    return Collections2.transform(roles, new Function<SecurityRole, String>() {
        @Nullable/*  w  w  w.ja va  2s.  c  o  m*/
        @Override
        public String apply(@Nullable SecurityRole securityRole) {
            return securityRole.getName();
        }
    }).contains(roleName);
}

From source file:com.netflix.staash.cassandra.discovery.EurekaAstyanaxHostSupplier.java

public Supplier<List<Host>> getSupplier(final String clusterName) {
    return new Supplier<List<Host>>() {

        public List<Host> get() {
            Application app = eurekaClient.getApplication(clusterName.toUpperCase());
            List<Host> hosts = Lists.newArrayList();
            if (app == null) {
                LOG.warn("Cluster '{}' not found in eureka", new Object[] { clusterName });
            } else {
                List<InstanceInfo> ins = app.getInstances();
                if (ins != null && !ins.isEmpty()) {
                    hosts = Lists.newArrayList(
                            Collections2.transform(Collections2.filter(ins, new Predicate<InstanceInfo>() {
                                public boolean apply(InstanceInfo input) {
                                    return input.getStatus() == InstanceInfo.InstanceStatus.UP;
                                }/*  w w w .java 2s  . c  o  m*/
                            }), new Function<InstanceInfo, Host>() {
                                public Host apply(InstanceInfo info) {
                                    String[] parts = StringUtils
                                            .split(StringUtils.split(info.getHostName(), ".")[0], '-');

                                    Host host = new Host(info.getHostName(), info.getPort())
                                            .addAlternateIpAddress(StringUtils.join(
                                                    new String[] { parts[1], parts[2], parts[3], parts[4] },
                                                    "."))
                                            .addAlternateIpAddress(info.getIPAddr()).setId(info.getId());

                                    try {
                                        if (info.getDataCenterInfo() instanceof AmazonInfo) {
                                            AmazonInfo amazonInfo = (AmazonInfo) info.getDataCenterInfo();
                                            host.setRack(amazonInfo.get(MetaDataKey.availabilityZone));
                                        }
                                    } catch (Throwable t) {
                                        LOG.error("Error getting rack for host " + host.getName(), t);
                                    }

                                    return host;
                                }
                            }));
                } else {
                    LOG.warn("Cluster '{}' found in eureka but has no instances", new Object[] { clusterName });
                }
            }
            return hosts;
        }
    };
}