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:com.netflix.exhibitor.core.state.ServerList.java

public ServerSpec getSpec(final String hostname) {
    return Iterables.find(specs, new Predicate<ServerSpec>() {
        @Override//from w w  w  .  j ava 2 s  . c om
        public boolean apply(ServerSpec spec) {
            return spec.getHostname().equals(hostname);
        }
    }, null);
}

From source file:nl.surfnet.coin.selfservice.util.SpringSecurity.java

public static InstitutionIdentityProvider validateIdp(final InstitutionIdentityProvider idp) {
    if (SpringSecurity.getCurrentUser().isSuperUser()) {
        return idp;
    } else {//w  ww .jav  a2s.  c  o m
        List<InstitutionIdentityProvider> institutionIdps = SpringSecurity.getCurrentUser()
                .getInstitutionIdps();

        InstitutionIdentityProvider currentInstitutionIdentityProvider = Iterables.find(institutionIdps,
                new Predicate<InstitutionIdentityProvider>() {
                    @Override
                    public boolean apply(InstitutionIdentityProvider input) {
                        return input.getId().equals(idp.getId());
                    }
                }, null);

        if (currentInstitutionIdentityProvider != null) {
            return currentInstitutionIdentityProvider;
        } else {
            throw new SecurityException(
                    idp.getId() + " is unknown for " + SpringSecurity.getCurrentUser().getUsername());
        }
    }
}

From source file:org.solovyev.android.messenger.accounts.AccountsAdapter.java

@Nullable
protected AccountListItem findInAllElements(@Nonnull Account account) {
    return Iterables.find(getAllElements(), Predicates.<AccountListItem>equalTo(createListItem(account)), null);
}

From source file:org.gradle.model.internal.core.DomainObjectCollectionBackedModelMap.java

@Nullable
@Override
public T get(String name) {
    return Iterables.find(collection, new HasNamePredicate<T>(name, namer), null);
}

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

@Override
public void execute(CommandLineArguments arguments) {
    CommandLineHandle console = getCommandLineHandle();
    if (arguments.argumentCount() < 2) {
        console.expectedArguments(getArguments());
        return;/*from w w  w .  ja  v  a2 s. co m*/
    }

    AmazonNodeManager nodeManager = getNodeManager();
    Scanner scanner = arguments.asScanner();

    AmazonInstanceShutdownState shutdownState;
    String shutdownStateArgument = scanner.next();
    try {
        shutdownState = AmazonInstanceShutdownState.valueOf(shutdownStateArgument.toUpperCase());
    } catch (IllegalArgumentException ex) {
        console.print("Unknown shutdown state '%s'.", shutdownStateArgument);
        return;
    }

    List<AmazonNode> nodesToShutdown = Lists.newLinkedList();
    while (scanner.hasNext()) {
        final String nodeId = scanner.next();
        Node node = Iterables.find(getNodeManager().getNodes(), new Predicate<Node>() {
            @Override
            public boolean apply(Node input) {
                return input.getID().equalsIgnoreCase(nodeId);
            }
        }, null);
        if (node != null) {
            nodesToShutdown.add(node.as(AmazonNode.class));
        } else {
            console.print("Unknown node ID: %s. Skipping.", nodeId);
        }
    }

    console.print("Shutting down %d nodes", nodesToShutdown.size());
    List<ListenableFuture<? extends Object>> futures = new ArrayList<ListenableFuture<? extends Object>>(
            nodesToShutdown.size());
    for (AmazonNode amazonNode : nodesToShutdown) {
        ListenableFuture<Boolean> future = nodeManager.removeNode(amazonNode, shutdownState);
        addFailureLogger(future);
        futures.add(future);
    }

    waitForFuturesToComplete(futures,
            "Interrupted while waiting for nodes to shut down. Nodes may not all be stopped properly.",
            "Failed to wait for nodes to stop.", "{} nodes failed to shut down.");
    console.print("Shutdown completed.");

}

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

private PluginUpdate findAvailablePluginByKey(String key) {
    PluginUpdate pluginUpdate = Iterables.find(
            updateCenterFactory.getUpdateCenter(false).findAvailablePlugins(), hasKey(key), MISSING_PLUGIN);
    if (pluginUpdate == MISSING_PLUGIN) {
        throw new IllegalArgumentException(format(
                "No plugin with key '%s' or plugin '%s' is already installed in latest version", key, key));
    }//www .  ja  v a  2  s  . com
    return pluginUpdate;
}

From source file:org.polymap.core.data.image.cache304.ClearCacheAction.java

@Override
public void selectionChanged(IAction action, ISelection selection) {
    selected.clear();// w w  w  .jav a  2 s .c  o  m
    action.setEnabled(false);
    for (ILayer layer : new SelectionAdapter(selection).elementsOfType(ILayer.class)) {
        // check permissions
        if (!ACLUtils.checkPermission(layer, AclPermission.WRITE, false)) {
            return;
        }
        // check cache processor in pipeline
        try {
            IService service = layer.getGeoResource().service(null);
            Pipeline pipeline = new DefaultPipelineIncubator().newPipeline(LayerUseCase.ENCODED_IMAGE,
                    layer.getMap(), layer, service);
            PipelineProcessor found = Iterables.find(pipeline, Predicates.instanceOf(ImageCacheProcessor.class),
                    null);
            if (found == null) {
                return;
            }
        } catch (Exception e) {
            log.warn("", e);
            return;
        }

        selected.add(layer);
    }
    action.setEnabled(true);
}

From source file:com.netflix.exhibitor.core.rest.ConfigResource.java

@Path("get-state")
@GET/*from   w ww  .  j  a  v a  2  s .  co  m*/
@Produces(MediaType.APPLICATION_JSON)
public Response getSystemState(@Context Request request) throws Exception {
    InstanceConfig config = context.getExhibitor().getConfigManager().getConfig();

    String response = new FourLetterWord(FourLetterWord.Word.RUOK, config,
            context.getExhibitor().getConnectionTimeOutMs()).getResponse();
    ServerList serverList = new ServerList(config.getString(StringConfigs.SERVERS_SPEC));
    ServerSpec us = Iterables.find(serverList.getSpecs(),
            ServerList.isUs(context.getExhibitor().getThisJVMHostname()), null);

    ObjectNode mainNode = JsonNodeFactory.instance.objectNode();
    ObjectNode configNode = JsonNodeFactory.instance.objectNode();
    ObjectNode controlPanelNode = JsonNodeFactory.instance.objectNode();

    mainNode.put("version", context.getExhibitor().getVersion());
    mainNode.put("running", "imok".equals(response));
    mainNode.put("backupActive", context.getExhibitor().getBackupManager().isActive());
    mainNode.put("standaloneMode", context.getExhibitor().getConfigManager().isStandaloneMode());
    mainNode.put("extraHeadingText", context.getExhibitor().getExtraHeadingText());
    mainNode.put("nodeMutationsAllowed", context.getExhibitor().nodeMutationsAllowed());

    configNode.put("rollInProgress", context.getExhibitor().getConfigManager().isRolling());
    configNode.put("rollStatus",
            context.getExhibitor().getConfigManager().getRollingConfigState().getRollingStatus());
    configNode.put("rollPercentDone",
            context.getExhibitor().getConfigManager().getRollingConfigState().getRollingPercentDone());

    configNode.put("hostname", context.getExhibitor().getThisJVMHostname());
    configNode.put("serverId", (us != null) ? us.getServerId() : -1);
    for (StringConfigs c : StringConfigs.values()) {
        configNode.put(fixName(c), config.getString(c));
    }
    for (IntConfigs c : IntConfigs.values()) {
        String fixedName = fixName(c);
        int value = config.getInt(c);

        configNode.put(fixedName, value);
    }

    EncodedConfigParser zooCfgParser = new EncodedConfigParser(config.getString(StringConfigs.ZOO_CFG_EXTRA));
    ObjectNode zooCfgNode = JsonNodeFactory.instance.objectNode();
    for (EncodedConfigParser.FieldValue fv : zooCfgParser.getFieldValues()) {
        zooCfgNode.put(fv.getField(), fv.getValue());
    }
    configNode.put("zooCfgExtra", zooCfgNode);

    if (context.getExhibitor().getBackupManager().isActive()) {
        ObjectNode backupExtraNode = JsonNodeFactory.instance.objectNode();
        EncodedConfigParser parser = context.getExhibitor().getBackupManager().getBackupConfigParser();
        List<BackupConfigSpec> configs = context.getExhibitor().getBackupManager().getConfigSpecs();
        for (BackupConfigSpec c : configs) {
            String value = parser.getValue(c.getKey());
            backupExtraNode.put(c.getKey(), (value != null) ? value : "");
        }
        configNode.put("backupExtra", backupExtraNode);
    }

    configNode.put("controlPanel", controlPanelNode);
    mainNode.put("config", configNode);

    String json = JsonUtil.writeValueAsString(mainNode);
    EntityTag tag = new EntityTag(Hashing.sha1().hashString(json).toString());

    Response.ResponseBuilder builder = request.evaluatePreconditions(tag);
    if (builder == null) {
        builder = Response.ok(json).tag(tag);
    }

    return builder.build();
}

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

@Nonnull
private PluginUpdate findPluginUpdateByKey(String key) {
    PluginUpdate pluginUpdate = Iterables.find(updateCenterFactory.getUpdateCenter(false).findPluginUpdates(),
            new PluginKeyPredicate(key), MISSING_PLUGIN);
    if (pluginUpdate == MISSING_PLUGIN) {
        throw new IllegalArgumentException(format(
                "No plugin with key '%s' or plugin '%s' is already in latest compatible version", key, key));
    }//from w  w w.  ja v a2s . co m
    return pluginUpdate;
}

From source file:net.sourceforge.fenixedu.domain.cms.UnitClassTemplateController.java

/**
 * @param unit/*from   w  w w .  j  av a2s  .  c o  m*/
 * @param subUnitAcronym
 * @return the first subUnit of 'unit' with a 'subUnitAcronym'
 */
private Unit findSubUnitByAcronym(final Unit unit, final String subUnitAcronym) {
    return Iterables.find(unit.getSubUnits(), new Predicate<Unit>() {
        @Override
        public boolean apply(Unit subUnit) {
            return StringUtils.equalsIgnoreCase(UnitAcronym.normalize(subUnit.getAcronym()),
                    UnitAcronym.normalize(subUnitAcronym));
        }
    }, null);
}