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

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

Source Link

Document

Returns the first element in iterable that satisfies the given predicate; use this method only when such an element is known to exist.

Usage

From source file:de.cosmocode.palava.model.geoplanet.Place.java

/**
 * Retrieve the preferredAlias for a specified locale.
 * // w  w  w.java 2s .  c o  m
 * @param locale the target locale
 * @return a preferred alias of this place for the given locale
 * @throws NoSuchElementException if there is no preferred alias for
 *         the given locale
 */
public Alias getPreferredAlias(final Locale locale) {
    final String language = locale.getLanguage();
    return Iterables.find(getAliases(), new Predicate<Alias>() {

        @Override
        public boolean apply(Alias input) {
            if (input.getNameType() == NameType.Q) {
                return StringUtils.equals(input.getLanguageCode(), language);
            } else {
                return false;
            }
        }

    });
}

From source file:brooklyn.networking.sdn.SdnAgentImpl.java

@Override
public InetAddress attachNetwork(String containerId, final String networkId) {
    final SdnProvider provider = getAttribute(SDN_PROVIDER);
    boolean createNetwork = false;
    Cidr subnetCidr = null;/*from  w w w.  ja  va  2s . c  o  m*/
    synchronized (provider.getNetworkMutex()) {
        subnetCidr = provider.getSubnetCidr(networkId);
        if (subnetCidr == null) {
            subnetCidr = provider.getNextSubnetCidr(networkId);
            createNetwork = true;
        }
    }
    if (createNetwork) {
        // Get a CIDR for the subnet from the availabkle pool and create a virtual network
        EntitySpec<VirtualNetwork> networkSpec = EntitySpec.create(VirtualNetwork.class)
                .configure(VirtualNetwork.NETWORK_ID, networkId)
                .configure(VirtualNetwork.NETWORK_CIDR, subnetCidr);

        // Start and then add this virtual network as a child of SDN_NETWORKS
        VirtualNetwork network = provider.getAttribute(SdnProvider.SDN_NETWORKS).addChild(networkSpec);
        Entities.manage(network);
        Entities.start(network,
                Collections.singleton(
                        ((DockerInfrastructure) provider.getAttribute(SdnProvider.DOCKER_INFRASTRUCTURE))
                                .getDynamicLocation()));
        Entities.waitForServiceUp(network);
    } else {
        Task<Boolean> lookup = TaskBuilder.<Boolean>builder().name("Waiting until virtual network is available")
                .body(new Callable<Boolean>() {
                    @Override
                    public Boolean call() throws Exception {
                        return Repeater.create().every(Duration.TEN_SECONDS).until(new Callable<Boolean>() {
                            public Boolean call() {
                                Optional<Entity> found = Iterables.tryFind(
                                        provider.getAttribute(SdnProvider.SDN_NETWORKS).getMembers(),
                                        EntityPredicates.attributeEqualTo(VirtualNetwork.NETWORK_ID,
                                                networkId));
                                return found.isPresent();
                            }
                        }).limitTimeTo(Duration.ONE_MINUTE).run();
                    }
                }).build();
        Boolean result = DynamicTasks.queueIfPossible(lookup).orSubmitAndBlock().andWaitForSuccess();
        if (!result) {
            throw new IllegalStateException(
                    String.format("Cannot find virtual network entity for %s", networkId));
        }
    }

    InetAddress address = getDriver().attachNetwork(containerId, networkId);
    LOG.info("Attached container ID {} to {}: {}",
            new Object[] { containerId, networkId, address.getHostAddress() });

    // Rescan SDN network groups for containers
    DynamicGroup network = (DynamicGroup) Iterables.find(
            provider.getAttribute(SdnProvider.SDN_APPLICATIONS).getMembers(),
            EntityPredicates.attributeEqualTo(VirtualNetwork.NETWORK_ID, networkId));
    network.rescanEntities();

    return address;
}

From source file:edu.udo.scaffoldhunter.view.ViewConverter.java

/**
 * Finds the subset corresponding to the given database id.
 *
 * @param root// www .  ja va2  s.c om
 *          the root of the subset tree to be searched
 * @param subsetId
 *          the database id
 *
 * @return  the subset found
 *
 * @throws  NoSuchElementException
 */
private Subset findSubset(Subset root, final int subsetId) {
    Iterable<Subset> subsetIterable = Subsets.getSubsetTreeIterable(root);

    return Iterables.find(subsetIterable, new Predicate<Subset>() {
        @Override
        public boolean apply(Subset input) {
            return input.getId() == subsetId;
        }
    });
}

From source file:org.opendaylight.protocol.pcep.pcc.mock.Main.java

private static ch.qos.logback.classic.Logger getRootLogger(final LoggerContext lc) {
    return Iterables.find(lc.getLoggerList(), new Predicate<Logger>() {
        @Override/*from   w ww. jav a2 s  .  co  m*/
        public boolean apply(final Logger input) {
            return (input != null) ? input.getName().equals(Logger.ROOT_LOGGER_NAME) : false;
        }
    });
}

From source file:dynamite.zafroshops.app.fragment.AddZopFragment.java

public void setLocation(View v) {
    LocationBase address = ((MainActivity) getActivity()).getAddress(false);
    MobileCountry current = null;//  w  w w  . ja  va2  s .c o  m

    if (address != null && zopCountries.size() > 0) {
        final String country = address.CountryCode;
        if (country != null) {
            current = Iterables.find(zopCountries, new Predicate<MobileCountry>() {
                @Override
                public boolean apply(MobileCountry input) {
                    return input.ID.compareToIgnoreCase(country) == 0;
                }
            });
        }

        View view = v == null ? getView() : v;
        if (view != null && current != null) {
            ((Spinner) view.findViewById(R.id.newZopCountry))
                    .setSelection(zopCountryAdapter.getPosition(current));
            ((EditText) view.findViewById(R.id.newZopCity)).setText(address.Town);
            ((EditText) view.findViewById(R.id.newZopStreet)).setText(address.Street);
            ((EditText) view.findViewById(R.id.newZopStreetNumber)).setText(address.StreetNumber);
        }
    }
}

From source file:org.dasein.cloud.jclouds.vcloud.director.compute.VmSupport.java

@Override
public VirtualMachine clone(String vmId, String intoDcId, String name, String description, boolean powerOn,
        String... firewallIds) throws InternalException, CloudException {
    RestContext<VCloudDirectorAdminClient, VCloudDirectorAdminAsyncClient> ctx = provider.getCloudClient();

    try {//from ww w  . j  a v  a2 s . c  om
        try {
            CloneVAppParams.Builder<?> options = CloneVAppParams.builder().description(description).name(name);

            if (powerOn) {
                options.powerOn();
            }
            // note this says vmId, but the copy operation is on the vApp. you might want to rename this variable accordingly
            URI vAppUri = null;
            VApp clone = ctx.getApi().getVdcClient().cloneVApp(vAppUri, options.build());

            Task task = Iterables.find(clone.getTasks(), new Predicate<Task>() {
                @Override
                public boolean apply(Task input) {
                    return input.getOperationName().equals("cloneVApp");
                }
            });
            provider.waitForTask(task);
            return null; // TODO: identify vm
        } catch (RuntimeException e) {
            logger.error("Error booting " + vmId + ": " + e.getMessage());
            if (logger.isDebugEnabled()) {
                e.printStackTrace();
            }
            throw new CloudException(e);
        }
    } finally {
        ctx.close();
    }
}

From source file:org.opentestsystem.authoring.testauth.validation.ScoringRuleValidator.java

@Override
public void validate(final Object obj, final Errors errors) {
    // execute JSR-303 validations (annotations)
    this.jsrValidator.validate(obj, errors);

    final ScoringRule scoringRule = (ScoringRule) obj;

    // parameterDataMap can only be evaluated if corresponding ComputationRule is passed along
    if (StringUtils.isNotBlank(scoringRule.getComputationRuleId())
            && scoringRule.getComputationRule() != null) {
        validateFileUploads(errors, scoringRule);

        if (!CollectionUtils.isEmpty(scoringRule.getParameters())) {
            // check for duplicate parameter names
            final Map<String, Collection<ScoringRuleParameter>> duplicates = Maps.filterEntries(
                    Multimaps.index(scoringRule.getParameters(), RULE_PARAMETER_TO_NAME_TRANSFORMER).asMap(),
                    PARAMETER_DUPLICATE_FILTER);
            if (!duplicates.isEmpty()) {
                rejectValue(errors, PARAMETERS,
                        getErrorMessageRoot() + PARAMETERS + MSG_PARAMETER_NAME + MSG_DUPLICATES,
                        duplicates.keySet().toString());
            }//from  w  w w . j  a  v a 2  s  .co  m

            for (int i = 0; i < scoringRule.getParameters().size(); i++) {
                final ScoringRuleParameter scoringRuleParameter = scoringRule.getParameters().get(i);
                try {
                    errors.pushNestedPath(PARAMETERS + "[" + i + "]");
                    final ComputationRuleParameter computationRuleParameter = Iterables
                            .find(scoringRule.getComputationRule().getParameters(), FUNCTION_PARAMETER_FINDER
                                    .getInstance(scoringRuleParameter.getComputationRuleParameterName()));
                    if (computationRuleParameter == null) {
                        rejectValue(errors, PARAMETER_NAME,
                                getErrorMessageRoot() + PARAMETERS + MSG_PARAMETER_NAME + MSG_NOT_FOUND,
                                scoringRuleParameter.getComputationRuleParameterName());
                    } else {
                        // evaluate every value within the rule parameter to ensure it adheres to the constraints of the ComputationRuleParameter
                        ValidationUtils.invokeValidator(this.scoringRuleParameterValidator,
                                scoringRuleParameter, errors, computationRuleParameter);
                    }
                } catch (final NoSuchElementException e) {
                    rejectValue(errors, PARAMETER_NAME,
                            getErrorMessageRoot() + PARAMETERS + MSG_PARAMETER_NAME + MSG_NOT_FOUND,
                            scoringRuleParameter.getComputationRuleParameterName());
                } finally {
                    errors.popNestedPath();
                }
            }

            for (final ComputationRuleParameter computationRuleParameter : scoringRule.getComputationRule()
                    .getParameters()) {
                if (!Iterables.any(scoringRule.getParameters(),
                        RULE_PARAMETER_FINDER.getInstance(computationRuleParameter.getParameterName()))) {
                    rejectValue(errors, PARAMETERS,
                            getErrorMessageRoot() + PARAMETERS + MSG_PARAMETER_NAME + MSG_MISSING,
                            computationRuleParameter.getParameterName());
                }
            }
        }
    }
}

From source file:elaborate.editor.model.orm.User.java

public void removeUserSetting(String key) {
    if (hasUserSetting(key)) {
        Iterables.find(Lists.newArrayList(getUserSettings()), userSettingWithKey(key));
    }
}

From source file:org.jclouds.digitalocean2.compute.functions.DropletToNodeMetadata.java

protected Hardware getHardware(final String slug) {
    return Iterables.find(hardwares.get().values(), new Predicate<Hardware>() {
        @Override/*  ww  w .  ja  v  a  2 s  .  com*/
        public boolean apply(Hardware input) {
            return input.getId().equals(slug);
        }
    });
}

From source file:org.geoserver.importer.format.GeoJSONFormat.java

File file(ImportData data, final ImportTask item) {
    if (data instanceof Directory) {
        return Iterables.find(((Directory) data).getFiles(), new Predicate<FileData>() {
            @Override/*from   w  ww. jav a2  s  .  com*/
            public boolean apply(FileData input) {
                return FilenameUtils.getBaseName(input.getFile().getName()).equals(item.getLayer().getName());
            }
        }).getFile();
    } else {
        return maybeFile(data).get();
    }
}