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

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

Introduction

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

Prototype

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

Source Link

Document

Returns an Optional containing the first element in iterable that satisfies the given predicate, if such an element exists.

Usage

From source file:com.codereligion.diff.internal.linewriter.MapLineWriter.java

/**
 * Transforms the given map {@code value} into a {@link SortedMap}.
 *
 * @param path the path which describes the position of the given value in the object graph
 * @param value the map to be sorted/*from   w  ww . j a v a 2  s  .  c o m*/
 * @return a new sorted map with the contents of the given map
 */
private SortedMap<Object, Object> transformToSortedMap(final String path, final Map<Object, Object> value) {

    final Optional<Object> anyKey = Iterables.tryFind(value.keySet(), Predicates.notNull());

    final boolean thereIsJustOneKeyAndItIsNull = !anyKey.isPresent();
    if (thereIsJustOneKeyAndItIsNull) {
        return new TreeMap<Object, Object>();
    }

    final Comparator<Object> comparator = findComparatorOrThrowException(path, anyKey.get());
    final SortedMap<Object, Object> sortedMap = new TreeMap<Object, Object>(comparator);
    sortedMap.putAll(value);

    return sortedMap;
}

From source file:org.pentaho.di.trans.dataservice.optimization.paramgen.ParameterGenerationFactory.java

private Optional<ParameterGenerationServiceFactory> getFactory(final StepMeta stepMeta) {
    return Iterables.tryFind(factories, new Predicate<ParameterGenerationServiceFactory>() {
        @Override//from  www.j a  v  a2s. co m
        public boolean apply(ParameterGenerationServiceFactory input) {
            return input.supportsStep(stepMeta);
        }
    });
}

From source file:com.kurtraschke.wmata.gtfsrealtime.services.WMATARouteMapperService.java

private AgencyAndId mapBusRoute(String routeID) {
    if (_staticMappings.containsKey(routeID)) {
        String staticMappedRoute = _staticMappings.getProperty(routeID);
        Optional<Route> matchedRoute = Iterables.tryFind(_gtfsRoutes,
                new ShortNameFilterPredicate(staticMappedRoute, true));

        if (matchedRoute.isPresent()) {
            AgencyAndId mappedRouteID = matchedRoute.get().getId();
            _log.info(/* w  w w .j  a va2s  . co m*/
                    "Mapped WMATA route " + routeID + " to GTFS route " + mappedRouteID + " (using override)");
            return mappedRouteID;
        } else {
            _log.warn("Could not apply static mapping of {} to {}; continuing...", routeID, staticMappedRoute);
        }
    }

    Matcher m = _routeExtract.matcher(routeID);

    if (m.matches()) {
        final String filteredRouteID = m.group(1);
        if (!_matchBadRoutes.apply(filteredRouteID)) {
            Optional<Route> matchedRoute = Iterables.tryFind(_gtfsRoutes,
                    new ShortNameFilterPredicate(filteredRouteID, true));

            if (matchedRoute.isPresent()) {
                AgencyAndId mappedRouteID = matchedRoute.get().getId();
                _log.info("Mapped WMATA route " + routeID + " to GTFS route " + mappedRouteID);
                return mappedRouteID;
            } else {
                _log.warn("Could not map WMATA route: " + routeID);
                return null;
            }
        } else {
            _log.warn("Not mapping blacklisted WMATA route: " + routeID);
            return null;
        }
    } else {
        _log.warn("Not mapping malformed WMATA route: " + routeID);
        return null;
    }
}

From source file:io.pelle.mango.client.web.module.ModuleHandler.java

@SuppressWarnings("unchecked")
public void startUIModule(final String moduleUrl, final String location1, final Map<String, Object> parameters,
        final Optional<AsyncCallback<IModuleUI>> callback) {

    final String location = getLocation(location1);

    LOG.info("starting ui module for url '" + moduleUrl + "'");

    Optional<IModuleUI> moduleUI = Iterables.tryFind(getModuleStack(location),
            new MouldeUrlPredicate(moduleUrl));

    if (moduleUI.isPresent()) {

        LOG.info("ui module for url '" + moduleUrl + "' already started (" + moduleUI.get().toString() + ")");

        moduleUI.get().updateUrl(moduleUrl);

        if (callback.isPresent()) {
            callback.get().onSuccess(moduleUI.get());
        }/*from w  w w.j  a v a 2  s .  c om*/

        MangoClientWeb.getInstance().getLayoutFactory().showModuleUI(moduleUI.get(), location);

    } else {

        if (ModuleUIFactoryRegistry.getInstance().supports(moduleUrl)) {

            ModuleUIFactoryRegistry.getInstance().getModuleFactory(moduleUrl).getNewInstance(moduleUrl,
                    new BaseAsyncCallback<IModuleUI, IModuleUI>(callback) {

                        @Override
                        public void onSuccess(IModuleUI moduleUI) {

                            if (moduleUI.contributesToBreadCrumbs()) {
                                stashCurrentAndShow(moduleUI, location);
                            } else {
                                closeCurrentAndShow(moduleUI, location);
                            }

                            onModuleUIAdd(moduleUI, location);

                            if (callback.isPresent()) {
                                callback.get().onSuccess(moduleUI);
                            }
                        }

                    }, parameters, peekCurrentModule(location));
        } else {
            throw new RuntimeException("unsupported module url '" + moduleUrl + "'");
        }
    }
}

From source file:org.onosproject.drivers.juniper.LinkDiscoveryJuniperImpl.java

@Override
public Set<LinkDescription> getLinks() {
    DeviceId localDeviceId = this.handler().data().deviceId();
    NetconfController controller = checkNotNull(handler().get(NetconfController.class));
    NetconfSession session = controller.getDevicesMap().get(localDeviceId).getSession();

    String reply;/*from   ww w.ja va  2 s  . c  o m*/
    try {
        reply = session.get(requestBuilder(REQ_LLDP_NBR_INFO));
    } catch (IOException e) {
        throw new RuntimeException(new NetconfException(FAILED_CFG, e));
    }
    log.debug("Reply from device {} : {}", localDeviceId, reply);
    Set<LinkAbstraction> linkAbstractions = parseJuniperLldp(
            XmlConfigParser.loadXml(new ByteArrayInputStream(reply.getBytes())));
    log.debug("Set of LinkAbstraction discovered {}", linkAbstractions);

    DeviceService deviceService = this.handler().get(DeviceService.class);
    Set<LinkDescription> descriptions = new HashSet<>();

    //for each lldp neighbor create two LinkDescription
    for (LinkAbstraction linkAbs : linkAbstractions) {

        //find source port by local port name
        Optional<Port> localPort = deviceService.getPorts(localDeviceId).stream().filter(port -> {
            if (linkAbs.localPortName.equals(port.annotations().value(PORT_NAME))) {
                return true;
            }
            return false;
        }).findAny();
        if (!localPort.isPresent()) {
            log.warn("Port name {} does not exist in device {}", linkAbs.localPortName, localDeviceId);
            continue;
        }
        //find destination device by remote chassis id
        com.google.common.base.Optional<Device> dev = Iterables.tryFind(deviceService.getAvailableDevices(),
                input -> input.chassisId().equals(linkAbs.remoteChassisId));

        if (!dev.isPresent()) {
            log.warn("Device with chassis ID {} does not exist", linkAbs.remoteChassisId);
            continue;
        }
        Device remoteDevice = dev.get();

        //find destination port by interface index
        Optional<Port> remotePort = deviceService.getPorts(remoteDevice.id()).stream().filter(port -> {
            if (port.annotations().value("index") != null
                    && Integer.parseInt(port.annotations().value("index")) == linkAbs.remotePortIndex) {
                return true;
            }
            return false;
        }).findAny();
        if (!remotePort.isPresent()) {
            log.warn("Port with index {} does not exist in device {}", linkAbs.remotePortIndex,
                    remoteDevice.id());
            continue;
        }

        JuniperUtils.createBiDirLinkDescription(localDeviceId, localPort.get(), remoteDevice.id(),
                remotePort.get(), descriptions);

    }
    return descriptions;
}

From source file:org.eclipse.osee.orcs.db.internal.search.engines.ArtifactQuerySqlContextFactoryImpl.java

private IOseeBranch getBranchToSearch(QueryData queryData) throws OseeCoreException {
    IOseeBranch branch = null;//from  ww w .j  av a 2s .co  m

    Iterable<? extends Criteria> criterias = queryData.getAllCriteria();
    Optional<? extends Criteria> item = Iterables.tryFind(criterias, new Predicate<Criteria>() {

        @Override
        public boolean apply(Criteria criteria) {
            return HasBranch.class.isAssignableFrom(criteria.getClass());
        }

    });
    if (item.isPresent()) {
        HasBranch criteria = (HasBranch) item.get();
        branch = criteria.getBranch();
    }
    return branch;
}

From source file:org.n52.sos.ogc.sensorML.AbstractSensorML.java

public Optional<SmlIdentifier> findIdentification(Predicate<SmlIdentifier> predicate) {
    if (isSetIdentifications()) {
        return Iterables.tryFind(getIdentifications(), predicate);
    }//from ww  w  .  ja  v a2s .  co  m
    return Optional.absent();
}

From source file:org.zanata.workflow.ClientWorkFlow.java

public boolean isPushSuccessful(List<String> output) {
    Optional<String> successOutput = Iterables.tryFind(output, input -> input.contains("BUILD SUCCESS"));
    return successOutput.isPresent();
}

From source file:com.brighttag.agathon.security.ec2.Ec2SecurityGroupService.java

private Optional<SecurityGroup> getSecurityGroup(String groupName, String dataCenter) {
    DescribeSecurityGroupsResult result = client(dataCenter).describeSecurityGroups();
    // Specifying non-existent group in the request throws exception. Request all and filter instead.
    return Iterables.tryFind(result.getSecurityGroups(), withGroupName(groupName));
}

From source file:com.streamreduce.rest.resource.api.SearchMessageResource.java

/**
 * Compresses the values in a Map&lt;String,Collection&lt;String&gt;&gt; to Strings by selecting the first valid
 * value in the Collection.  This method is presumed to only be called with the value of UriInfo.getQueryParameters.
 *
 * @param map/*from  ww w  .j  a va 2s. com*/
 * @return
 */
private Map<String, String> flattenValues(MultivaluedMap<String, String> map) {
    HashMap<String, String> newMap = new HashMap<>();
    for (String key : map.keySet()) {
        Collection<String> value = map.get(key);
        Optional<String> possibleFind = Iterables.tryFind(value, new Predicate<String>() {
            @Override
            public boolean apply(@Nullable String input) {
                return (input != null && StringUtils.isNotBlank(input));
            }
        });
        if (possibleFind.isPresent()) {
            newMap.put(key, possibleFind.get());
        }
    }
    return newMap;
}