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

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

Introduction

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

Prototype

@Nullable
public static <T> T find(Iterable<? extends T> iterable, Predicate<? super T> predicate,
        @Nullable T defaultValue) 

Source Link

Document

Returns the first element in iterable that satisfies the given predicate, or defaultValue if none found.

Usage

From source file:gov.nih.nci.firebird.selenium2.pages.investigator.profile.AddOrganizationAssociationDialogHelper.java

private SearchResultListing<AbstractLoadableComponent<?>> getListingById(final AbstractOrganizationRole role) {
    return Iterables.find(getDialog().getSearchResults(),
            new Predicate<SearchResultListing<AbstractLoadableComponent<?>>>() {
                @Override//  w  w w .j  a  v  a  2  s .com
                public boolean apply(SearchResultListing<AbstractLoadableComponent<?>> listing) {
                    return role.getOrganization().getExternalId().equals(listing.getExternalId());
                }
            }, null);
}

From source file:com.netflix.curator.framework.recipes.locks.Reaper.java

@VisibleForTesting
int getEmptyCount(final String path) {
    PathHolder found = Iterables.find(queue, new Predicate<PathHolder>() {
        @Override//ww w .j ava 2 s .  c om
        public boolean apply(PathHolder holder) {
            return holder.path.equals(path);
        }
    }, null);

    return (found != null) ? found.emptyCount : -1;
}

From source file:com.android.tools.idea.editors.vmtrace.TraceViewPanel.java

public void setTrace(@NotNull VmTraceData trace) {
    myTraceData = trace;/*from www. j a  va2s  . c o m*/

    List<ThreadInfo> threads = trace.getThreads(true);
    if (threads.isEmpty()) {
        return;
    }

    ThreadInfo defaultThread = Iterables.find(threads, new Predicate<ThreadInfo>() {
        @Override
        public boolean apply(ThreadInfo input) {
            return MAIN_THREAD_NAME.equals(input.getName());
        }
    }, threads.get(0));

    myTraceViewCanvas.setTrace(trace, defaultThread, getCurrentRenderClock());
    myThreadCombo.setModel(new DefaultComboBoxModel(threads.toArray()));
    myThreadCombo.setSelectedItem(defaultThread);
    myThreadCombo.setRenderer(new ColoredListCellRenderer() {
        @Override
        protected void customizeCellRenderer(JList list, Object value, int index, boolean selected,
                boolean hasFocus) {
            String name = value instanceof ThreadInfo ? ((ThreadInfo) value).getName() : value.toString();
            append(name);
        }
    });

    myThreadCombo.setEnabled(true);
    myRenderClockSelectorCombo.setEnabled(true);

    myVmStatsTreeTableModel.setTraceData(trace, defaultThread);
    myVmStatsTreeTableModel.setClockType(getCurrentRenderClock());
    myTreeTable.setModel(myVmStatsTreeTableModel);

    VmStatsTreeUtils.adjustTableColumnWidths(myTreeTable);
    VmStatsTreeUtils.setCellRenderers(myTreeTable);
    VmStatsTreeUtils.setSpeedSearch(myTreeTable);
    VmStatsTreeUtils.enableSorting(myTreeTable, myVmStatsTreeTableModel);
}

From source file:brooklyn.networking.cloudstack.loadbalancer.CloudStackLoadBalancerImpl.java

@Override
protected String getAddressOfEntity(Entity member) {
    JcloudsSshMachineLocation machine = (JcloudsSshMachineLocation) Iterables.find(member.getLocations(),
            Predicates.instanceOf(JcloudsSshMachineLocation.class), null);

    if (machine != null && machine.getNode().getProviderId() != null) {
        return machine.getNode().getProviderId();
    } else {/*www .  jav  a  2 s  . c  om*/
        LOG.error("Unable to construct cloudstack-id representation for {} in {}; skipping in {}",
                new Object[] { member, machine, this });
        return null;
    }
}

From source file:org.brooth.jeta.apt.processors.MetaInjectProcessor.java

private void buildInjectMethod(TypeSpec.Builder builder, RoundContext context, TypeElement masterElement,
        ClassName masterClassName, Boolean staticMeta, ArrayList<Element> unhandledElements) {
    MethodSpec.Builder methodBuilder;//from  ww w .j a v  a2  s. c o m
    if (staticMeta) {
        methodBuilder = MethodSpec.methodBuilder("injectStatic").addParameter(metaScopeTypeName, "scope",
                Modifier.FINAL);

    } else {
        methodBuilder = MethodSpec.methodBuilder("inject")
                .addParameter(metaScopeTypeName, "scope", Modifier.FINAL)
                .addParameter(masterClassName, "master", Modifier.FINAL);
    }

    methodBuilder.addAnnotation(Override.class).addModifiers(Modifier.PUBLIC).returns(void.class);
    Multimap<String, StatementSpec> statements = ArrayListMultimap.create();
    for (TypeElement scopeElement : moduleScopes) {
        for (Element element : context.elements()) {
            if (element.getKind() == ElementKind.METHOD) {
                String methodStatement = null;
                if (staticMeta) {
                    if (element.getModifiers().contains(Modifier.STATIC))
                        methodStatement = String.format("%1$s.%2$s",
                                masterElement.getQualifiedName().toString(),
                                element.getSimpleName().toString());
                } else {
                    if (!element.getModifiers().contains(Modifier.STATIC))
                        methodStatement = String.format("master.%1$s", element.getSimpleName().toString());
                }
                if (methodStatement == null)
                    continue;

                ExecutableElement methodElement = (ExecutableElement) element;
                List<? extends VariableElement> paramElements = methodElement.getParameters();
                Multimap<String, StatementSpec> varStatements = HashMultimap.create();
                for (VariableElement paramElement : paramElements) {
                    StatementSpec statement = getResultStatement(scopeElement, paramElement.asType(), "",
                            "getInstance()");
                    if (statement != null) {
                        statement.element = paramElement;
                        varStatements.put(statement.providerScopeStr, statement);
                    }
                }

                if (!varStatements.isEmpty()) {
                    for (String varScope : varStatements.keySet()) {
                        Collection<StatementSpec> scopeVarStatements = varStatements.get(varScope);
                        List<String> paramFormats = new ArrayList<>(paramElements.size());
                        List<Object> paramArgs = new ArrayList<>(paramElements.size());
                        for (final VariableElement paramElement : paramElements) {
                            StatementSpec varStatement = Iterables.find(scopeVarStatements,
                                    new Predicate<StatementSpec>() {
                                        @Override
                                        public boolean apply(StatementSpec input) {
                                            return input.element == paramElement;
                                        }
                                    }, null);

                            if (varStatement != null) {
                                paramFormats.add(varStatement.format);
                                paramArgs.addAll(Arrays.asList(varStatement.args));

                            } else {
                                paramFormats.add("$L");
                                paramArgs.add("null");
                            }
                        }

                        StatementSpec methodStatementSpec = new StatementSpec(varScope,
                                (methodStatement + '(' + Joiner.on(", ").join(paramFormats) + ')'),
                                paramArgs.toArray(new Object[paramArgs.size()]));

                        if (!statements.containsEntry(varScope, methodStatementSpec)) {
                            statements.put(varScope, methodStatementSpec);
                            unhandledElements.remove(element);
                        }
                    }
                }

            } else if (element.getKind() == ElementKind.FIELD) {
                String fieldStatement = null;

                if (staticMeta) {
                    if (element.getModifiers().contains(Modifier.STATIC))
                        fieldStatement = String.format("%1$s.%2$s =\n",
                                masterElement.getQualifiedName().toString(),
                                element.getSimpleName().toString());
                } else {
                    if (!element.getModifiers().contains(Modifier.STATIC))
                        fieldStatement = String.format("master.%1$s = ", element.getSimpleName().toString());
                }
                if (fieldStatement == null)
                    continue;

                StatementSpec statement = getResultStatement(scopeElement, element.asType(), fieldStatement,
                        "getInstance()");
                if (statement != null) {
                    statement.element = element;
                    if (!statements.containsEntry(statement.providerScopeStr, statement)) {
                        statements.put(statement.providerScopeStr, statement);
                        unhandledElements.remove(element);
                    }
                }

            } else {
                throw new ProcessingException("Unhandled injection element type " + element.getKind());
            }
        }
    }

    if (!statements.isEmpty()) {
        List<String> scopes = new ArrayList<>(statements.keySet());
        Collections.sort(scopes, new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                return isAssignableScope(o1, o2) ? 1 : -1;
            }
        });

        for (String scopeElement : scopes) {
            ClassName scopeClassName = ClassName.bestGuess(scopeElement);
            ClassName scopeMetacodeClassName = ClassName.get(scopeClassName.packageName(),
                    MetacodeUtils.toSimpleMetacodeName(scopeClassName.toString()), "MetaScopeImpl");
            methodBuilder.beginControlFlow("if(scope.isAssignable($T.class))", scopeClassName)
                    .addStatement("final $T s = ($T) scope", scopeMetacodeClassName, scopeMetacodeClassName);

            for (StatementSpec statement : statements.get(scopeElement))
                methodBuilder.addStatement(statement.format, statement.args);

            methodBuilder.endControlFlow();
        }
    }

    builder.addMethod(methodBuilder.build());
}

From source file:org.sonar.server.issue.ws.IssueShowWsHandler.java

/**
 * Can be null on project or on removed component
 *///from w  w w.  ja va  2  s . c  o  m
@CheckForNull
private Component getSubProject(IssueQueryResult result, @Nullable final ComponentDto component) {
    if (component != null) {
        return Iterables.find(result.components(), new Predicate<Component>() {
            @Override
            public boolean apply(Component input) {
                Long groupId = component.subProjectId();
                return groupId != null && groupId.equals(((ComponentDto) input).getId());
            }
        }, null);
    }
    return null;
}

From source file:co.cask.cdap.data2.transaction.queue.hbase.HBaseQueueClientFactory.java

@Override
public QueueConsumer createConsumer(final QueueName queueName, final ConsumerConfig consumerConfig,
        int numGroups) throws IOException {
    final HBaseQueueAdmin admin = ensureTableExists(queueName);
    try {/*www.  ja v a2 s  .c o  m*/
        final long groupId = consumerConfig.getGroupId();

        // A callback for create a list of HBaseQueueConsumer
        // based on the current queue consumer state of the given group
        Callable<List<HBaseQueueConsumer>> consumerCreator = new Callable<List<HBaseQueueConsumer>>() {

            @Override
            public List<HBaseQueueConsumer> call() throws Exception {
                List<HBaseConsumerState> states;
                try (HBaseConsumerStateStore stateStore = admin.getConsumerStateStore(queueName)) {
                    TransactionExecutor txExecutor = Transactions.createTransactionExecutor(txExecutorFactory,
                            stateStore);

                    // Find all consumer states for consumers that need to be created based on current state
                    states = txExecutor.execute(new Callable<List<HBaseConsumerState>>() {
                        @Override
                        public List<HBaseConsumerState> call() throws Exception {
                            List<HBaseConsumerState> consumerStates = Lists.newArrayList();

                            HBaseConsumerState state = stateStore.getState(groupId,
                                    consumerConfig.getInstanceId());
                            if (state.getPreviousBarrier() == null) {
                                // Old HBase consumer (Salted based, not sharded)
                                consumerStates.add(state);
                                return consumerStates;
                            }

                            // Find the smallest start barrier that has something to consume for this instance.
                            // It should always exists since we assume the queue is configured before this method is called
                            List<QueueBarrier> queueBarriers = stateStore.getAllBarriers(groupId);
                            if (queueBarriers.isEmpty()) {
                                throw new IllegalStateException(String.format(
                                        "No consumer information available. Queue: %s, GroupId: %d, InstanceId: %d",
                                        queueName, groupId, consumerConfig.getInstanceId()));
                            }
                            QueueBarrier startBarrier = Iterables.find(Lists.reverse(queueBarriers),
                                    new Predicate<QueueBarrier>() {
                                        @Override
                                        public boolean apply(QueueBarrier barrier) {
                                            return barrier.getGroupConfig().getGroupSize() > consumerConfig
                                                    .getInstanceId()
                                                    && stateStore.isAllConsumed(consumerConfig,
                                                            barrier.getStartRow());
                                        }
                                    }, queueBarriers.get(0));

                            int groupSize = startBarrier.getGroupConfig().getGroupSize();
                            for (int i = consumerConfig.getInstanceId(); i < groupSize; i += consumerConfig
                                    .getGroupSize()) {
                                consumerStates.add(stateStore.getState(groupId, i));
                            }
                            return consumerStates;
                        }
                    });
                }

                List<HBaseQueueConsumer> consumers = Lists.newArrayList();
                for (HBaseConsumerState state : states) {
                    QueueType queueType = (state.getPreviousBarrier() == null) ? QueueType.QUEUE
                            : QueueType.SHARDED_QUEUE;
                    HTable hTable = createHTable(admin.getDataTableId(queueName, queueType));
                    int distributorBuckets = getDistributorBuckets(hTable.getTableDescriptor());

                    HBaseQueueStrategy strategy = (state.getPreviousBarrier() == null)
                            ? new SaltedHBaseQueueStrategy(hBaseTableUtil, distributorBuckets)
                            : new ShardedHBaseQueueStrategy(hBaseTableUtil, distributorBuckets);
                    consumers.add(queueUtil.getQueueConsumer(cConf, hTable, queueName, state,
                            admin.getConsumerStateStore(queueName), strategy));
                }
                return consumers;
            }
        };

        return new SmartQueueConsumer(queueName, consumerConfig, consumerCreator);
    } catch (Exception e) {
        // If there is exception, nothing much can be done here besides propagating
        Throwables.propagateIfPossible(e);
        throw new IOException(e);
    }
}

From source file:org.openhab.binding.loxone.internal.LoxoneBinding.java

private Miniserver findMiniserver(final String instance) {
    return Iterables.find(miniservers, new Predicate<Miniserver>() {
        public boolean apply(Miniserver miniserver) {
            return instance.equalsIgnoreCase(miniserver.host().getName());
        }//w  w w .  j a va  2  s . c o m
    }, Iterables.getFirst(miniservers, null));
}

From source file:com.ning.billing.osgi.bundles.analytics.dao.factory.BusinessInvoiceFactory.java

private BusinessInvoiceItemBaseModelDao createBusinessInvoiceItem(final Account account, final Invoice invoice,
        final InvoiceItem invoiceItem, final Collection<InvoiceItem> otherInvoiceItems,
        final Long accountRecordId, final Long tenantRecordId, @Nullable final ReportGroup reportGroup,
        final TenantContext context) throws AnalyticsRefreshException {
    // For convenience, populate empty columns using the linked item
    final InvoiceItem linkedInvoiceItem = Iterables.find(otherInvoiceItems, new Predicate<InvoiceItem>() {
        @Override/*w w w .  j a v a  2 s  . c  o  m*/
        public boolean apply(final InvoiceItem input) {
            return invoiceItem.getLinkedItemId() != null && invoiceItem.getLinkedItemId().equals(input.getId());
        }
    }, null);

    SubscriptionBundle bundle = null;
    // Subscription and bundle could be null for e.g. credits or adjustments
    if (invoiceItem.getBundleId() != null) {
        bundle = getSubscriptionBundle(invoiceItem.getBundleId(), context);
    }
    if (bundle == null && linkedInvoiceItem != null && linkedInvoiceItem.getBundleId() != null) {
        bundle = getSubscriptionBundle(linkedInvoiceItem.getBundleId(), context);
    }

    Plan plan = null;
    if (Strings.emptyToNull(invoiceItem.getPlanName()) != null) {
        plan = getPlanFromInvoiceItem(invoiceItem, context);
    }
    if (plan == null && linkedInvoiceItem != null
            && Strings.emptyToNull(linkedInvoiceItem.getPlanName()) != null) {
        plan = getPlanFromInvoiceItem(linkedInvoiceItem, context);
    }

    PlanPhase planPhase = null;
    if (invoiceItem.getSubscriptionId() != null && Strings.emptyToNull(invoiceItem.getPhaseName()) != null) {
        planPhase = getPlanPhaseFromInvoiceItem(invoiceItem, context);
    }
    if (planPhase == null && linkedInvoiceItem != null && linkedInvoiceItem.getSubscriptionId() != null
            && Strings.emptyToNull(linkedInvoiceItem.getPhaseName()) != null) {
        planPhase = getPlanPhaseFromInvoiceItem(linkedInvoiceItem, context);
    }

    final Long invoiceItemRecordId = invoiceItem.getId() != null
            ? getInvoiceItemRecordId(invoiceItem.getId(), context)
            : null;
    final AuditLog creationAuditLog = invoiceItem.getId() != null
            ? getInvoiceItemCreationAuditLog(invoiceItem.getId(), context)
            : null;

    return createBusinessInvoiceItem(account, invoice, invoiceItem, otherInvoiceItems, bundle, plan, planPhase,
            invoiceItemRecordId, creationAuditLog, accountRecordId, tenantRecordId, reportGroup);
}

From source file:org.sonar.server.rule.DeprecatedRulesDefinitionLoader.java

@CheckForNull
private static RuleDebt findRequirement(List<RuleDebt> requirements, final String repoKey,
        final String ruleKey) {
    return Iterables.find(requirements, new RuleDebtMatchRepoKeyAndRuleKey(repoKey, ruleKey), null);
}