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.xtext.resource.impl.AbstractContainer.java

@Override
public IResourceDescription getResourceDescription(final URI uri) {
    return Iterables.find(getResourceDescriptions(), new Predicate<IResourceDescription>() {
        @Override//  ww w . j  a v  a  2s .  c  om
        public boolean apply(IResourceDescription input) {
            return uri.equals(input.getURI());
        }
    }, null);
}

From source file:com.netflix.exhibitor.core.automanage.ClusterStatusTask.java

public ClusterStatusTask(Exhibitor exhibitor, List<ServerSpec> specs) {
    this.exhibitor = exhibitor;
    this.specs = ImmutableList.copyOf(specs);
    us = Iterables.find(specs, ServerList.isUs(exhibitor.getThisJVMHostname()), null);
}

From source file:ratpack.session.clientside.internal.CookieBasedSessionStorageBindingHandler.java

public void handle(final Context context) {
    context.getRequest().addLazy(SessionStorage.class, () -> {
        Cookie sessionCookie = Iterables.find(context.getRequest().getCookies(),
                c -> sessionName.equals(c.name()), null);
        ConcurrentMap<String, Object> sessionMap = sessionService.deserializeSession(sessionCookie);
        DefaultSessionStorage storage = new DefaultSessionStorage(sessionMap);
        ConcurrentMap<String, Object> initialSessionMap = new ConcurrentHashMap<>(sessionMap);
        context.getRequest().add(InitialStorageContainer.class,
                new InitialStorageContainer(new DefaultSessionStorage(initialSessionMap)));
        return storage;
    });/*from w  ww.jav a2  s .c om*/

    context.getResponse().beforeSend(responseMetaData -> {
        Optional<SessionStorage> storageOptional = context.getRequest().maybeGet(SessionStorage.class);
        if (storageOptional.isPresent()) {
            SessionStorage storage = storageOptional.get();
            boolean hasChanged = !context.getRequest().get(InitialStorageContainer.class)
                    .isSameAsInitial(storage);
            if (hasChanged) {
                Set<Map.Entry<String, Object>> entries = storage.entrySet();

                if (entries.isEmpty()) {
                    invalidateSession(responseMetaData);
                } else {
                    ByteBufAllocator bufferAllocator = context.get(ByteBufAllocator.class);
                    String cookieValue = sessionService.serializeSession(bufferAllocator, entries);
                    responseMetaData.cookie(sessionName, cookieValue);
                }
            }
        }
    });

    context.next();
}

From source file:org.sonar.server.util.TypeValidations.java

private TypeValidation findByKey(String key) {
    TypeValidation typeValidation = Iterables.find(typeValidationList, new TypeValidationMatchKey(key), null);
    checkRequest(typeValidation != null, "Type '%s' is not valid.", key);
    return typeValidation;
}

From source file:com.netflix.exhibitor.core.state.Checker.java

public InstanceStateTypes calculateState() throws Exception {
    InstanceConfig config = exhibitor.getConfigManager().getConfig();

    if (!isSet(config, StringConfigs.ZOOKEEPER_DATA_DIRECTORY)
            || !isSet(config, StringConfigs.ZOOKEEPER_INSTALL_DIRECTORY)) {
        return InstanceStateTypes.LATENT;
    }//  www.ja  v  a2 s. c  om

    InstanceStateTypes potentialState = InstanceStateTypes.DOWN;
    ServerList serverList = new ServerList(config.getString(StringConfigs.SERVERS_SPEC));
    ServerSpec us = Iterables.find(serverList.getSpecs(), ServerList.isUs(exhibitor.getThisJVMHostname()),
            null);
    if (us != null) {
        if (!exhibitor.getControlPanelValues().isSet(ControlPanelTypes.RESTARTS)) {
            potentialState = InstanceStateTypes.NO_RESTARTS_DOWN;
        }
    } else {
        if (!exhibitor.getControlPanelValues().isSet(ControlPanelTypes.UNLISTED_RESTARTS)) {
            potentialState = InstanceStateTypes.UNLISTED_DOWN;
        }
    }

    InstanceStateTypes actualState = potentialState;
    String ruok = new FourLetterWord(FourLetterWord.Word.RUOK, hostname, config,
            exhibitor.getConnectionTimeOutMs()).getResponse();
    if ("imok".equals(ruok)) {
        // The following code depends on inside knowledge of the "srvr" response. If they change it
        // this code might break

        List<String> lines = new FourLetterWord(FourLetterWord.Word.SRVR, hostname, config,
                exhibitor.getConnectionTimeOutMs()).getResponseLines();
        for (String line : lines) {
            if (line.contains("not currently serving")) {
                actualState = InstanceStateTypes.NOT_SERVING;
                break;
            }

            if (line.toLowerCase().startsWith("mode")) {
                actualState = InstanceStateTypes.SERVING;
                break;
            }
        }
    }

    return actualState;
}

From source file:msi.gama.outputs.AbstractOutputManager.java

public IOutput getOutputWithName(final String s) {
    return Iterables.find(this, each -> each.getName().equals(s), null);
}

From source file:org.polarsys.reqcycle.types.impl.TypesManager.java

@Override
public IType getType(final String id) {
    IType result = allTypes.get(id);/*from   www . ja  v  a 2  s.c o m*/
    if (result == null) {
        result = Iterables.find(Iterables.concat(Iterables.transform(providers, new ProviderToITypes())),
                new Predicate<IType>() {
                    public boolean apply(IType t) {
                        return id.equals(t.getId());
                    }
                }, null);
    }
    return result;
}

From source file:org.gradle.api.internal.plugins.DefaultAppliedPlugins.java

public Class<?> findPlugin(String id) {
    return Iterables.find(matchingForId(id), new Predicate<Class<?>>() {
        public boolean apply(Class<?> input) {
            return true;
        }//from w  w  w .j  ava  2 s. c  o m
    }, null);
}

From source file:ru.ksu.niimm.cll.mocassin.crawl.parser.gate.FakeBibliographyExtractor.java

@Override
public String getToKey(String fromKey, int number) {
    Entry<Pair<String, String>, Integer> entry = Iterables.find(link2number.entrySet(),
            new FromKeyPredicate(fromKey, number), null);
    return entry != null ? entry.getKey().getSecond() : null;
}

From source file:eu.itesla_project.iidm.import_.ucte.UcteImporter.java

private static void createBuses(UcteNetworkExt ucteNetwork, Network network, EntsoeFileName ucteFileName) {
    for (UcteSubstation ucteSubstation : ucteNetwork.getSubstations()) {

        // skip substations with only one Xnode
        UcteNodeCode firstUcteNodeCode = Iterables.find(ucteSubstation.getNodes(),
                code -> code.getUcteCountryCode() != UcteCountryCode.XX, null);
        if (firstUcteNodeCode == null) {
            continue;
        }//from w  w w. j  ava 2  s.  co  m

        LOGGER.trace("Create substation '{}'", ucteSubstation.getName());

        Substation substation = network.newSubstation().setId(ucteSubstation.getName())
                .setCountry(Country.valueOf(firstUcteNodeCode.getUcteCountryCode().name())).add();

        for (UcteVoltageLevel ucteVoltageLevel : ucteSubstation.getVoltageLevels()) {
            UcteVoltageLevelCode ucteVoltageLevelCode = ucteVoltageLevel.getNodes().iterator().next()
                    .getVoltageLevelCode();

            LOGGER.trace("Create voltage level '{}'", ucteVoltageLevel.getName());

            VoltageLevel voltageLevel = substation.newVoltageLevel().setId(ucteVoltageLevel.getName())
                    .setNominalV(ucteVoltageLevelCode.getVoltageLevel())
                    .setTopologyKind(TopologyKind.BUS_BREAKER).add();

            for (UcteNodeCode ucteNodeCode : ucteVoltageLevel.getNodes()) {
                UcteNode ucteNode = ucteNetwork.getNode(ucteNodeCode);

                // skip Xnodes
                if (ucteNode.getCode().getUcteCountryCode() == UcteCountryCode.XX) {
                    continue;
                }

                LOGGER.trace("Create bus '{}'", ucteNodeCode.toString());

                Bus bus = voltageLevel.getBusBreakerView().newBus().setId(ucteNodeCode.toString()).add();

                if (isValueValid(ucteNode.getActiveLoad()) || isValueValid(ucteNode.getReactiveLoad())) {
                    createLoad(ucteNode, voltageLevel, bus);
                }

                if (ucteNode.isGenerator()) {
                    createGenerator(ucteNode, voltageLevel, bus);
                }
            }
        }
    }
}