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:org.eclipse.incquery.patternlanguage.helper.CorePatternLanguageHelper.java

/**
 * Returns the parameter of a pattern by name
 * /*from   w w  w.j a  v  a 2  s  . co  m*/
 * @param pattern
 * @param name
 * @return the requested parameter of the pattern, or null if none exists
 * @since 0.7.0
 */
public static Variable getParameterByName(final Pattern pattern, final String name) {
    return Iterables.find(pattern.getParameters(), new Predicate<Variable>() {

        @Override
        public boolean apply(Variable variable) {
            return name.equals(variable.getName());
        }
    }, null);
}

From source file:org.sonar.server.plugins.ws.UpdateAction.java

@Nonnull
private PluginUpdate findPluginUpdateByKey(String key) {
    Optional<UpdateCenter> updateCenter = updateCenterFactory.getUpdateCenter(false);
    PluginUpdate pluginUpdate = MISSING_PLUGIN;

    if (updateCenter.isPresent()) {
        pluginUpdate = Iterables.find(updateCenter.get().findPluginUpdates(), new PluginKeyPredicate(key),
                MISSING_PLUGIN);/*from   w  w  w .j  a va2 s . c  o m*/
    }

    if (pluginUpdate == MISSING_PLUGIN) {
        throw new IllegalArgumentException(format(
                "No plugin with key '%s' or plugin '%s' is already in latest compatible version", key, key));
    }
    return pluginUpdate;
}

From source file:org.eclipse.incquery.patternlanguage.emf.ui.contentassist.PatternImporter.java

@Override
public void apply(final IDocument document, final ConfigurableCompletionProposal proposal)
        throws BadLocationException {
    if (document instanceof IXtextDocument) {
        IXtextDocument xtextDocument = (IXtextDocument) document;
        if (targetPattern == null || Strings.isNullOrEmpty(targetPattern.getName()))
            return;
        importStatus = ((IXtextDocument) document).readOnly(new IUnitOfWork<ImportState, XtextResource>() {

            @Override//from  w w  w  .j  a v a  2 s  .com
            public ImportState exec(XtextResource state) throws Exception {
                final PatternModel model = (PatternModel) Iterators.find(state.getAllContents(),
                        Predicates.instanceOf(PatternModel.class));
                if (targetPackage.equals(model.getPackageName())) {
                    return ImportState.SAMEPACKAGE;
                }
                final XImportSection importSection = model.getImportPackages();
                PatternImport relatedImport = Iterables.find(importSection.getPatternImport(),
                        new Predicate<PatternImport>() {

                            @Override
                            public boolean apply(PatternImport decl) {
                                return targetPattern.equals(decl.getPattern())
                                        || targetPattern.getName().equals(decl.getPattern().getName());
                            }
                        }, null);
                if (relatedImport == null) {

                    return ImportState.NONE;
                }
                // Checking whether found pattern definition equals to different pattern
                if (targetPattern.equals(relatedImport.getPattern())) {
                    return ImportState.FOUND;
                } else {
                    return ImportState.CONFLICTING;
                }
            }
        });

        String replacementString = getActualReplacementString(proposal) + "();";
        ReplaceEdit edit = new ReplaceEdit(proposal.getReplacementOffset(), proposal.getReplacementLength(),
                replacementString);
        edit.apply(document);
        //+2 is used to put the cursor inside the parentheses
        int cursorOffset = getActualReplacementString(proposal).length() + 2;
        if (importStatus == ImportState.NONE) {
            xtextDocument.modify(new Void<XtextResource>() {

                @Override
                public void process(XtextResource state) throws Exception {
                    XImportSection importSection = (XImportSection) Iterators.find(state.getAllContents(),
                            Predicates.instanceOf(XImportSection.class), null);
                    if (importSection.getImportDeclarations().size() + importSection.getPackageImport().size()
                            + importSection.getPatternImport().size() == 0) {
                        //Empty import sections need to be replaced to generate white space after the package declaration
                        XImportSection newSection = EMFPatternLanguageFactory.eINSTANCE.createXImportSection();
                        ((PatternModel) importSection.eContainer()).setImportPackages(newSection);
                        importSection = newSection;
                    }
                    PatternImport newImport = EMFPatternLanguageFactory.eINSTANCE.createPatternImport();
                    newImport.setPattern(targetPattern);
                    importSection.getPatternImport().add(newImport);

                }
            });
            //Two new lines + "import " + pattern fqn
            cursorOffset += 2 + 7 + CorePatternLanguageHelper.getFullyQualifiedName(targetPattern).length();
        }
        proposal.setCursorPosition(cursorOffset);
    }
}

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

@Override
public String findItemNameByUUIDOrName(final String instance, final String uuid, final String name) {
    Map.Entry<String, BindingConfig> entry = Iterables.find(bindingConfigs.entrySet(),
            new Predicate<Map.Entry<String, BindingConfig>>() {
                public boolean apply(Map.Entry<String, BindingConfig> entry) {
                    LoxoneBindingConfig config = (LoxoneBindingConfig) entry.getValue();
                    boolean matchesInstance = isDefaultLoxoneInstance(config.instance) ? true
                            : config.instance.equalsIgnoreCase(instance);
                    boolean matchesUUID = uuid.equalsIgnoreCase(config.uuid);
                    boolean matchesName = name.equalsIgnoreCase(config.name);
                    return matchesInstance && (matchesName || matchesUUID);
                }// ww w  . j  av  a 2  s.c o  m
            }, null);
    return entry == null ? null : entry.getKey();
}

From source file:com.github.nethad.clustermeister.provisioning.ec2.CredentialsManager.java

/**
 * Get {@link Credentials} by name./*from w  w  w  .j  a v  a 2 s.  co m*/
 * 
 * @param name  the name of the credentials (e.g. the configured name).
 * @return the credentials with the corresponding name or null if none is found.
 */
public Credentials getCredentials(final String name) {
    SetView<Credentials> union = Sets.union(configuredCredentials, getNodeKeyPairs());
    Credentials result = Iterables.find(union, new Predicate<Credentials>() {
        @Override
        public boolean apply(Credentials input) {
            return input.getName().equals(name);
        }
    }, null);

    return result;
}

From source file:com.eviware.loadui.impl.statistics.model.chart.line.ChartTestEventSegment.java

private TestEventSourceDescriptor[] getDescriptors(Execution execution) {
    TestEventTypeDescriptor descriptor = Iterables.find(execution.getEventTypes(), typeFilter, null);
    return descriptor == null ? EMPTY_DESCRIPTOR_ARRAY
            : Lists.newArrayList(Iterables.filter(descriptor.getTestEventSources(), sourceFilter))
                    .toArray(EMPTY_DESCRIPTOR_ARRAY);
}

From source file:com.autoupdater.client.utils.services.notifier.AbstractNotifier.java

/**
 * Returns first service bound to given message.
 * //from  w w w .  ja v  a2 s.  c o  m
 * @param additionalMessage
 *            AdditionalMessage
 * @return Service bound to message, or null if none set
 */
public IService<RecievedMessage> getMessageSource(final AdditionalMessage additionalMessage) {
    return Iterables.find(additionalMessages.keySet(), new Predicate<IService<RecievedMessage>>() {
        @Override
        public boolean apply(IService<RecievedMessage> message) {
            return additionalMessages.get(message).equals(additionalMessage);
        }
    }, null);
}

From source file:org.solovyev.android.messenger.chats.AccountChatImpl.java

private boolean addParticipant(@Nonnull Entity participant) {
    final boolean contains = Iterables.find(participants, new EntityAwareByIdFinder(participant.getEntityId()),
            null) != null;/*from ww w  .jav  a  2s  . c o  m*/
    if (!contains) {
        if (this.chat.isPrivate()) {
            if (participants.size() == 2) {
                throw new IllegalArgumentException("Only 2 participants can be in private chat!");
            }
        }
        return participants.add(Users.newEmptyUser(participant));
    }

    return false;
}

From source file:org.eclipse.viatra.query.patternlanguage.jvmmodel.PatternLanguageJvmModelAssociator.java

private void setDeclaredParameter(Pattern pattern, final VariableReference reference) {
    Variable declaration = Iterables.find(pattern.getParameters(), new Predicate<Variable>() {

        @Override//from   ww w .  j  ava2 s .  c  o  m
        public boolean apply(Variable variable) {
            return Objects.equals(variable.getName(), reference.getVar());
        }
    }, null);
    if (declaration != null) {
        reference.setVariable(declaration);
    }
}

From source file:it.anyplace.sync.client.SyncthingClient.java

private @Nullable BlockExchangeConnectionHandler borrowFromPool(final DeviceAddress deviceAddress) {
    synchronized (pool) {
        BlockExchangeConnectionHandler connectionHandler = Iterables.find(pool,
                new Predicate<BlockExchangeConnectionHandler>() {
                    @Override// w  ww .  java2s .  c  o m
                    public boolean apply(BlockExchangeConnectionHandler input) {
                        return equal(deviceAddress, input.getAddress());
                    }
                }, null);
        if (connectionHandler != null) {
            pool.remove(connectionHandler);
            if (connectionHandler.isClosed()) { //TODO check live
                return borrowFromPool(deviceAddress);
            } else {
                return connectionHandler;
            }
        } else {
            return null;
        }
    }
}