Example usage for com.google.common.collect Iterables tryFind

List of usage examples for com.google.common.collect Iterables tryFind

Introduction

In this page you can find the example usage for com.google.common.collect Iterables tryFind.

Prototype

public static <T> Optional<T> tryFind(Iterable<T> iterable, Predicate<? super T> predicate) 

Source Link

Document

Returns an Optional containing the first element in iterable that satisfies the given predicate, if such an element exists.

Usage

From source file:org.incode.eurocommercial.contactapp.dom.contactable.ContactableEntity.java

@Action(semantics = SemanticsOf.IDEMPOTENT)
@ActionLayout(named = "Remove")
@MemberOrder(name = "contactNumbers", sequence = "2")
public ContactableEntity removeContactNumber(final String number) {
    final Optional<ContactNumber> contactNumberIfAny = Iterables.tryFind(getContactNumbers(),
            cn -> Objects.equal(cn.getNumber(), number));

    if (contactNumberIfAny.isPresent()) {
        getContactNumbers().remove(contactNumberIfAny.get());
    }/*from ww w. j a v a 2s .com*/
    return this;
}

From source file:org.jmingo.mongo.MongoDBFactory.java

private boolean isUnsupportedOption(String name) {
    return Iterables.tryFind(UNSUPPORTED_OPTIONS, input -> StringUtils.equalsIgnoreCase(name, input))
            .isPresent();
}

From source file:org.apache.drill.exec.planner.logical.DrillScanRel.java

@Override
public RelOptCost computeSelfCost(final RelOptPlanner planner) {
    final ScanStats stats = groupScan.getScanStats(settings);
    int columnCount = getRowType().getFieldCount();
    double ioCost = 0;
    boolean isStarQuery = Iterables.tryFind(getRowType().getFieldNames(), new Predicate<String>() {
        @Override//from  w ww .j  a  v  a 2  s  . com
        public boolean apply(String input) {
            return Preconditions.checkNotNull(input).equals("*");
        }
    }).isPresent();

    if (isStarQuery) {
        columnCount = STAR_COLUMN_COST;
    }

    // double rowCount = RelMetadataQuery.getRowCount(this);
    double rowCount = stats.getRecordCount();
    if (rowCount < 1) {
        rowCount = 1;
    }

    if (PrelUtil.getSettings(getCluster()).useDefaultCosting()) {
        return planner.getCostFactory().makeCost(rowCount * columnCount, stats.getCpuCost(),
                stats.getDiskCost());
    }

    double cpuCost = rowCount * columnCount; // for now, assume cpu cost is proportional to row count.
    // Even though scan is reading from disk, in the currently generated plans all plans will
    // need to read the same amount of data, so keeping the disk io cost 0 is ok for now.
    // In the future we might consider alternative scans that go against projections or
    // different compression schemes etc that affect the amount of data read. Such alternatives
    // would affect both cpu and io cost.

    DrillCostFactory costFactory = (DrillCostFactory) planner.getCostFactory();
    return costFactory.makeCost(rowCount, cpuCost, ioCost, 0);
}

From source file:org.killbill.billing.jaxrs.resources.InvoicePaymentResource.java

@TimedResource
@GET/* w  w w.  jav a2s  . c  o  m*/
@Path("/{paymentId:" + UUID_PATTERN + "}/")
@Produces(APPLICATION_JSON)
@ApiOperation(value = "Retrieve a payment by id", response = InvoicePaymentJson.class)
@ApiResponses(value = { @ApiResponse(code = 400, message = "Invalid payment id supplied"),
        @ApiResponse(code = 404, message = "Payment not found") })
public Response getInvoicePayment(@PathParam("paymentId") final String paymentIdStr,
        @QueryParam(QUERY_WITH_PLUGIN_INFO) @DefaultValue("false") final Boolean withPluginInfo,
        @QueryParam(QUERY_WITH_ATTEMPTS) @DefaultValue("false") final Boolean withAttempts,
        @QueryParam(QUERY_PLUGIN_PROPERTY) final List<String> pluginPropertiesString,
        @QueryParam(QUERY_AUDIT) @DefaultValue("NONE") final AuditMode auditMode,
        @javax.ws.rs.core.Context final HttpServletRequest request) throws PaymentApiException {

    final Iterable<PluginProperty> pluginProperties = extractPluginProperties(pluginPropertiesString);
    final UUID paymentIdId = UUID.fromString(paymentIdStr);
    final TenantContext tenantContext = context.createContext(request);
    final Payment payment = paymentApi.getPayment(paymentIdId, withPluginInfo, withAttempts, pluginProperties,
            tenantContext);
    final AccountAuditLogs accountAuditLogs = auditUserApi.getAccountAuditLogs(payment.getAccountId(),
            auditMode.getLevel(), tenantContext);

    final List<InvoicePayment> invoicePayments = invoicePaymentApi.getInvoicePayments(paymentIdId,
            tenantContext);
    final InvoicePayment invoicePayment = Iterables.tryFind(invoicePayments, new Predicate<InvoicePayment>() {
        @Override
        public boolean apply(final InvoicePayment input) {
            return input.getType() == InvoicePaymentType.ATTEMPT && input.isSuccess();
        }
    }).orNull();
    final UUID invoiceId = invoicePayment != null ? invoicePayment.getInvoiceId() : null;

    final InvoicePaymentJson result = new InvoicePaymentJson(payment, invoiceId, accountAuditLogs);
    return Response.status(Response.Status.OK).entity(result).build();
}

From source file:org.apache.brooklyn.util.exceptions.Exceptions.java

/** returns the first exception in the call chain which is not of common uninteresting types
 * (ie excluding ExecutionException and PropagatedRuntimeExceptions); 
 * or the original throwable if all are uninteresting 
 *///from   www  .  j  a va 2s.  c om
public static Throwable getFirstInteresting(Throwable throwable) {
    return Iterables.tryFind(getCausalChain(throwable), Predicates.not(IS_THROWABLE_BORING)).or(throwable);
}

From source file:org.n52.sos.ogc.sensorML.AbstractSensorML.java

public Optional<SmlCapabilities> findCapabilities(Predicate<SmlCapabilities> predicate) {
    if (this.capabilities != null) {
        return Iterables.tryFind(this.capabilities, predicate);
    } else {// www.  j  a va 2  s  . co m
        return Optional.absent();
    }
}

From source file:info.magnolia.ui.dialog.formdialog.FormPresenterImpl.java

@Override
public void setLocale(Locale locale) {
    if (uiContext instanceof SubAppContext && !ObjectUtils.equals(locale, this.activeLocale)) {
        final Locale formerLocale = this.activeLocale;
        this.activeLocale = locale;
        ((SubAppContext) uiContext).setAuthoringLocale(locale);

        final Map<TabDefinition, FormSection> currentFormSections = localeToFormSections.get(formerLocale);
        final Map<TabDefinition, FormSection> newFormSections = getLocaleSpecificFormSections(
                this.activeLocale);

        for (final Map.Entry<TabDefinition, FormSection> currentFormSectionEntry : currentFormSections
                .entrySet()) {/*from  w  w  w . j av  a  2 s.  c o m*/
            final TabDefinition tabDefinition = currentFormSectionEntry.getKey();
            final FormSection currentFormSection = currentFormSectionEntry.getValue();

            if (currentFormSection != null) {
                FormSection newFormSection = Iterables.tryFind(newFormSections.values(),
                        new FormSectionNameMatches(currentFormSection.getName())).orNull();
                if (newFormSection == null) {
                    newFormSection = formBuilder.buildFormTab(tabDefinition, itemDatasource, null)
                            .getContainer();
                    newFormSections.put(tabDefinition, newFormSection);
                }

                ((SingleComponentContainer) currentFormSection.getParent()).setContent(newFormSection);
            }
        }
    }
}

From source file:com.thinkbiganalytics.nifi.rest.support.NifiConnectionUtil.java

/**
 * Return a connection that has both the supplied source and destination id
 *
 * @param connections a collection of connection objects
 * @param sourceId    a sourceId to match
 * @param destId      a destination id to match
 * @return a connection that has both the source and destination id
 *//*from   w ww . j  a v a2  s.  c  o m*/
public static ConnectionDTO findConnection(Collection<ConnectionDTO> connections, final String sourceId,
        final String destId) {
    ConnectionDTO connection = null;
    connection = Iterables.tryFind(connections, new Predicate<ConnectionDTO>() {
        @Override
        public boolean apply(ConnectionDTO connectionDTO) {
            return connectionDTO.getSource().getId().equals(sourceId)
                    && connectionDTO.getDestination().getId().equalsIgnoreCase(destId);
        }
    }).orNull();

    return connection;

}

From source file:org.apache.provisionr.commands.CreateCommand.java

Provisionr getService() {
    Optional<Provisionr> service = Iterables.tryFind(services, ProvisionrPredicates.withId(id));
    if (!service.isPresent()) {
        throw new NoSuchElementException("No provisioning service found with id: " + id);
    }/*from  www . j  ava  2  s .  c o m*/
    return service.get();
}

From source file:org.killbill.billing.payment.core.sm.payments.PaymentLeavingStateCallback.java

protected PaymentTransactionModelDao getPendingPaymentTransaction(
        final List<PaymentTransactionModelDao> existingPaymentTransactions) throws PaymentApiException {
    return Iterables.tryFind(existingPaymentTransactions, new Predicate<PaymentTransactionModelDao>() {
        @Override//from   w ww  .  ja  v  a2 s  .c  o m
        public boolean apply(final PaymentTransactionModelDao input) {
            return input.getTransactionStatus() == TransactionStatus.PENDING;
        }
    }).orNull();
}