Example usage for com.google.common.base Predicates notNull

List of usage examples for com.google.common.base Predicates notNull

Introduction

In this page you can find the example usage for com.google.common.base Predicates notNull.

Prototype

@GwtCompatible(serializable = true)
public static <T> Predicate<T> notNull() 

Source Link

Document

Returns a predicate that evaluates to true if the object reference being tested is not null.

Usage

From source file:com.google.devtools.build.skyframe.CycleInfo.java

/**
 * Normalize multiple cycles. This includes removing multiple paths to the same cycle, so that
 * a value does not depend on the same cycle multiple ways through the same child value. Note that
 * a value can still depend on the same cycle multiple ways, it's just that each way must be
 * through a different child value (a path with a different first element).
 *///from w  w  w .j  av a  2 s . c o  m
static Iterable<CycleInfo> prepareCycles(final SkyKey value, Iterable<CycleInfo> cycles) {
    final Set<ImmutableList<SkyKey>> alreadyDoneCycles = new HashSet<>();
    return Iterables.filter(Iterables.transform(cycles, new Function<CycleInfo, CycleInfo>() {
        @Override
        public CycleInfo apply(CycleInfo input) {
            CycleInfo normalized = normalizeCycle(value, input);
            if (normalized != null && alreadyDoneCycles.add(normalized.cycle)) {
                return normalized;
            }
            return null;
        }
    }), Predicates.notNull());
}

From source file:net.shibboleth.idp.saml.saml2.profile.delegation.DelegationContext.java

/**
 * Set the relying party credentials which will be included in the assertion's {@link KeyInfoConfirmationDataType}.
 * /* ww  w  . jav  a2s  .c  o m*/
 * @param credentials the confirmation credentials
 */
public void setSubjectConfirmationCredentials(@Nullable @NonnullElements final List<Credential> credentials) {
    if (credentials == null) {
        subjectConfirmationCredentials = null;
    } else {
        subjectConfirmationCredentials = new ArrayList<>(
                Collections2.filter(credentials, Predicates.notNull()));
    }
}

From source file:net.shibboleth.idp.authn.impl.ValidateUserAgentAddress.java

/**
 * Set the IP range(s) to authenticate as particular principals.
 * /*from  w w w .ja v a2s .  c  om*/
 * @param newMappings the IP range(s) to authenticate as particular principals
 */
public void setMappings(@Nonnull @NonnullElements Map<String, Collection<IPRange>> newMappings) {
    ComponentSupport.ifInitializedThrowUnmodifiabledComponentException(this);

    mappings = new HashMap(newMappings.size());
    for (Map.Entry<String, Collection<IPRange>> e : newMappings.entrySet()) {
        if (!Strings.isNullOrEmpty(e.getKey())) {
            mappings.put(e.getKey(), new ArrayList(Collections2.filter(e.getValue(), Predicates.notNull())));
        }
    }
}

From source file:uk.ac.ebi.fg.annotare2.web.server.rpc.transform.UIObjectConverter.java

public static ArrayList<SubmissionRow> uiSubmissionRows(Collection<Submission> submissions) {
    return new ArrayList<>(filter(transform(submissions, SUBMISSION_ROW), Predicates.notNull()));
}

From source file:io.druid.query.groupby.epinephelinae.GroupByMergingQueryRunnerV2.java

public GroupByMergingQueryRunnerV2(GroupByQueryConfig config, ExecutorService exec, QueryWatcher queryWatcher,
        Iterable<QueryRunner<Row>> queryables, int concurrencyHint, BlockingPool<ByteBuffer> mergeBufferPool,
        ObjectMapper spillMapper) {/*from  w  ww.  j  av  a 2  s . c om*/
    this.config = config;
    this.exec = MoreExecutors.listeningDecorator(exec);
    this.queryWatcher = queryWatcher;
    this.queryables = Iterables.unmodifiableIterable(Iterables.filter(queryables, Predicates.notNull()));
    this.concurrencyHint = concurrencyHint;
    this.mergeBufferPool = mergeBufferPool;
    this.spillMapper = spillMapper;
}

From source file:com.android.build.gradle.internal.ProductFlavorCombo.java

private static <S extends DimensionAware & Named> void createProductFlavorCombinations(
        List<ProductFlavorCombo<S>> flavorGroups, List<S> group, int index, List<String> flavorDimensionList,
        ListMultimap<String, S> map) {
    if (index == flavorDimensionList.size()) {
        flavorGroups.add(new ProductFlavorCombo<S>(Iterables.filter(group, Predicates.notNull())));
        return;/*from   ww w  .  j  a v a  2 s.  c o  m*/
    }

    // fill the array at the current index.
    // get the dimension name that matches the index we are filling.
    String dimension = flavorDimensionList.get(index);

    // from our map, get all the possible flavors in that dimension.
    List<S> flavorList = map.get(dimension);

    // loop on all the flavors to add them to the current index and recursively fill the next
    // indices.
    if (flavorList.isEmpty()) {
        throw new RuntimeException(
                String.format("No flavor is associated with flavor dimension '%1$s'.", dimension));
    } else {
        for (S flavor : flavorList) {
            group.add(flavor);
            createProductFlavorCombinations(flavorGroups, group, index + 1, flavorDimensionList, map);
            group.remove(group.size() - 1);
        }
    }
}

From source file:org.jclouds.byon.internal.BYONComputeServiceAdapter.java

@Override
public Iterable<Location> listLocations() {
    Builder<Location> locations = ImmutableSet.builder();
    Location provider = getOnlyElement(locationSupplier.get());
    Set<String> zones = ImmutableSet
            .copyOf(filter(transform(nodes.get().asMap().values(), new Function<Node, String>() {

                @Override/*www.  jav  a  2  s  .  c  om*/
                public String apply(Node arg0) {
                    return arg0.getLocationId();
                }
            }), Predicates.notNull()));
    if (zones.size() == 0)
        return locations.add(provider).build();
    else
        for (String zone : zones) {
            locations.add(new LocationBuilder().scope(LocationScope.ZONE).id(zone).description(zone)
                    .parent(provider).build());
        }
    return locations.build();
}

From source file:org.mayocat.shop.billing.store.jdbi.mapper.OrderMapper.java

@Override
public Order map(int index, ResultSet resultSet, StatementContext ctx) throws SQLException {
    Order order = new Order();
    fillOrderSummary(resultSet, order);/*from w w w . j  ava  2s. c  o m*/

    ObjectMapper mapper = new ObjectMapper();
    //mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    try {
        List<Map<String, Object>> itemsData = mapper.readValue(resultSet.getString("items"),
                new TypeReference<List<Map<String, Object>>>() {
                });

        List<OrderItem> items = FluentIterable.from(itemsData)
                .transform(new Function<Map<String, Object>, OrderItem>() {
                    public OrderItem apply(Map<String, Object> map) {
                        if (map == null) {
                            return null;
                        }
                        OrderItem orderItem = new OrderItem();
                        orderItem.setId(UUID.fromString((String) map.get("id")));
                        orderItem.setOrderId(UUID.fromString((String) map.get("order_id")));
                        if (map.containsKey("purchasable_id") && map.get("purchasable_id") != null) {
                            // There might not be a purchasable id
                            orderItem.setPurchasableId(UUID.fromString((String) map.get("purchasable_id")));
                        }
                        orderItem.setType((String) map.get("type"));
                        orderItem.setTitle((String) map.get("title"));
                        orderItem.setMerchant((String) map.get("merchant"));
                        orderItem.setQuantity(((Integer) map.get("quantity")).longValue());
                        orderItem.setUnitPrice(BigDecimal.valueOf((Double) map.get("unit_price")));
                        orderItem.setItemTotal(BigDecimal.valueOf((Double) map.get("item_total")));
                        if (map.containsKey("vat_rate") && map.get("vat_rate") != null) {
                            // There might not be a VAT rate
                            orderItem.setVatRate(BigDecimal.valueOf((Double) map.get("vat_rate")));
                        }
                        if (map.containsKey("data") && map.get("data") != null) {
                            // There might not be data
                            orderItem.addData((Map<String, Object>) map.get("data"));
                        }
                        return orderItem;
                    }
                }).filter(Predicates.notNull()).toList();
        order.setOrderItems(items);
    } catch (IOException e) {
        logger.error("Failed to deserialize order data", e);
    }

    try {
        resultSet.findColumn("email");
        Customer customer = new Customer();
        customer.setId(order.getCustomerId());
        customer.setSlug(resultSet.getString("customer_slug"));
        customer.setEmail(resultSet.getString("email"));
        customer.setFirstName(resultSet.getString("first_name"));
        customer.setLastName(resultSet.getString("last_name"));
        customer.setPhoneNumber(resultSet.getString("phone_number"));
        customer.setCompany(resultSet.getString("company"));
        order.setCustomer(customer);
    } catch (SQLException e) {
        // Nevermind
    }

    try {
        if (resultSet.getObject("billing_address_id") != null) {
            resultSet.findColumn("billing_address_full_name");
            Address billing = new Address();
            billing.setId((UUID) resultSet.getObject("billing_address_id"));
            billing.setFullName(resultSet.getString("billing_address_full_name"));
            billing.setStreet(resultSet.getString("billing_address_street"));
            billing.setStreetComplement(resultSet.getString("billing_address_street_complement"));
            billing.setZip(resultSet.getString("billing_address_zip"));
            billing.setCity(resultSet.getString("billing_address_city"));
            billing.setCountry(resultSet.getString("billing_address_country"));
            billing.setNote(resultSet.getString("billing_address_note"));
            order.setBillingAddress(billing);
        }
    } catch (SQLException e) {
        // Nevermind
    }

    try {
        if (resultSet.getObject("delivery_address_id") != null) {
            resultSet.findColumn("delivery_address_full_name");
            Address delivery = new Address();
            delivery.setId((UUID) resultSet.getObject("delivery_address_id"));
            delivery.setFullName(resultSet.getString("delivery_address_full_name"));
            delivery.setStreet(resultSet.getString("delivery_address_street"));
            delivery.setStreetComplement(resultSet.getString("delivery_address_street_complement"));
            delivery.setZip(resultSet.getString("delivery_address_zip"));
            delivery.setCity(resultSet.getString("delivery_address_city"));
            delivery.setCountry(resultSet.getString("delivery_address_country"));
            delivery.setNote(resultSet.getString("delivery_address_note"));
            order.setDeliveryAddress(delivery);
        }
    } catch (SQLException e) {
        // Nevermind
    }

    return order;
}

From source file:org.opendaylight.controller.md.statistics.manager.FlowCapableTracker.java

@Override
public synchronized void onDataChanged(final DataChangeEvent<InstanceIdentifier<?>, DataObject> change) {
    logger.debug("Tracker at root {} processing notification", root);

    /*/*from   w w w.  ja va  2  s .  com*/
     * First process all the identifiers which were removed, trying to figure out
     * whether they constitute removal of FlowCapableNode.
     */
    final Collection<NodeKey> removedNodes = Collections2
            .filter(Collections2.transform(Sets.filter(change.getRemovedOperationalData(), filterIdentifiers),
                    new Function<InstanceIdentifier<?>, NodeKey>() {
                        @Override
                        public NodeKey apply(final InstanceIdentifier<?> input) {
                            final NodeKey key = input.firstKeyOf(Node.class, NodeKey.class);
                            if (key == null) {
                                // FIXME: do we have a backup plan?
                                logger.info("Failed to extract node key from {}", input);
                            }
                            return key;
                        }
                    }), Predicates.notNull());
    stats.stopNodeHandlers(removedNodes);

    final Collection<NodeKey> addedNodes = Collections2.filter(
            Collections2.transform(Sets.filter(change.getCreatedOperationalData().keySet(), filterIdentifiers),
                    new Function<InstanceIdentifier<?>, NodeKey>() {
                        @Override
                        public NodeKey apply(final InstanceIdentifier<?> input) {
                            final NodeKey key = input.firstKeyOf(Node.class, NodeKey.class);
                            if (key == null) {
                                // FIXME: do we have a backup plan?
                                logger.info("Failed to extract node key from {}", input);
                            }
                            return key;
                        }
                    }),
            Predicates.notNull());
    stats.startNodeHandlers(addedNodes);

    logger.debug("Tracker at root {} finished processing notification", root);
}

From source file:org.mayocat.localization.RequestLocalizationFilter.java

public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
        throws IOException, ServletException {

    final HttpServletRequest request = (HttpServletRequest) servletRequest;
    final HttpServletResponse response = (HttpServletResponse) servletResponse;

    if (isStaticPath(request.getRequestURI())
            || FluentIterable.from(settings.getExcludePaths()).anyMatch(startsWithPath(request))
            || webContext.getTenant() == null) {
        // Ignore static paths or paths configured as excluded
        chain.doFilter(servletRequest, servletResponse);
        return;/*from  ww w. j  ava2  s .  c  o m*/
    }

    Optional<Cookie> languageCookie = FluentIterable.from(Arrays.asList(request.getCookies()))
            .filter(new Predicate<Cookie>() {
                public boolean apply(Cookie cookie) {
                    return cookie.getName().equals("language");
                }
            }).first();

    if (languageCookie.isPresent()) {
        // Cookie already set, there's no work for us
        chain.doFilter(servletRequest, servletResponse);
        return;
    }

    LocalesSettings localesSettings = configurationService.getSettings(GeneralSettings.class).getLocales();
    List<Locale> alternativeLocales = FluentIterable.from(localesSettings.getOtherLocales().getValue())
            .filter(Predicates.notNull()).toList();

    if (isLocalizedInPath(request.getRequestURI(), alternativeLocales)) {
        // URI already localized (e.g. /fr/product/my-product/), continue
        chain.doFilter(servletRequest, servletResponse);
        return;
    }

    // Maybe there is a better locale matching the user Accept-Language
    String acceptLanguage = request.getHeader("Accept-Language");
    if (!Strings.isNullOrEmpty(acceptLanguage)) {
        final Locale acceptLanguageAsLocale = request.getLocale();
        Optional<Locale> bestMatch = FluentIterable.from(alternativeLocales).filter(new Predicate<Locale>() {
            public boolean apply(Locale input) {
                return input.equals(acceptLanguageAsLocale);
            }
        }).first();

        if (!bestMatch.isPresent() && !Strings.isNullOrEmpty(acceptLanguageAsLocale.getDisplayCountry())) {
            final Locale onlyLanguageAcceptLanguage = new Locale(acceptLanguageAsLocale.getLanguage());
            bestMatch = FluentIterable.from(alternativeLocales).filter(new Predicate<Locale>() {
                public boolean apply(Locale input) {
                    return input.equals(onlyLanguageAcceptLanguage);
                }
            }).first();
        }

        if (bestMatch.isPresent()) {
            // Mark the language as set with a cookie
            Cookie cookie = new Cookie("language", "set");
            cookie.setMaxAge(-1);
            cookie.setPath("/");
            response.addCookie(cookie);

            // Redirect to the found language
            response.sendRedirect("/" + bestMatch.get().toLanguageTag() + request.getRequestURI());
            return;
        }
    }

    chain.doFilter(servletRequest, servletResponse);
}