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.adobe.epubcheck.opf.OPFChecker30.java

private void checkDictCollectionContent(ResourceCollection collection) {
    if (collection.hasRole(Roles.DICTIONARY)) {
        boolean dictFound = false;
        for (LinkedResource resource : collection.getResources().asList()) {
            final Optional<OPFItem> item = opfHandler.getItemByPath(resource.getPath());
            if (!dictFound && item.isPresent() && "application/xhtml+xml".equals(item.get().getMimeType())) {
                // Search if this resource was reported as DICTIONARY content
                dictFound = Iterables.tryFind(context.featureReport.getFeature(FeatureEnum.DICTIONARY),
                        new Predicate<Feature>() {

                            @Override
                            public boolean apply(Feature dict) {
                                return item.get().getPath().equals(dict.getLocation().get().getPath());
                            }/*from  www  .  j a  va2  s.  co  m*/
                        }).isPresent();
            }
        }
        if (!dictFound) {
            // No Dictionary content
            report.message(MessageId.OPF_078, EPUBLocation.create(path));
        }
    }
}

From source file:org.jmingo.query.QueryManager.java

private AtomicReference<QuerySet> getQuerySetRef(Path path) {
    Optional<AtomicReference<QuerySet>> result = Iterables.tryFind(querySetRegistry,
            querySet -> querySet.get().getPath().equals(path));
    return result.or(new AtomicReference<>(null));
}

From source file:c3.ops.priam.identity.InstanceIdentity.java

public List<String> getSeeds() throws UnknownHostException {
    populateRacMap();/*from   www. ja  v  a2s .  c om*/
    List<String> seeds = new LinkedList<String>();
    // Handle single zone deployment
    if (config.getRacs().size() == 1) {
        // Return empty list if all nodes are not up
        if (membership.getRacMembershipSize() != locMap.get(myInstance.getRac()).size())
            return seeds;
        // If seed node, return the next node in the list
        if (locMap.get(myInstance.getRac()).size() > 1
                && locMap.get(myInstance.getRac()).get(0).getHostIP().equals(myInstance.getHostIP())) {
            PriamInstance instance = locMap.get(myInstance.getRac()).get(1);
            if (instance != null && !isInstanceDummy(instance)) {
                if (config.isMultiDC())
                    seeds.add(instance.getHostIP());
                else
                    seeds.add(instance.getHostName());
            }
        }
    }
    for (String loc : locMap.keySet()) {
        PriamInstance instance = Iterables.tryFind(locMap.get(loc), differentHostPredicate).orNull();
        if (instance != null && !isInstanceDummy(instance)) {
            if (config.isMultiDC())
                seeds.add(instance.getHostIP());
            else
                seeds.add(instance.getHostName());
        }
    }
    return seeds;
}

From source file:org.immutables.sequence.Sequence.java

/**
 * Returns an {@link Optional} containing the first element in this fluent iterable that
 * satisfies the given predicate, if such an element exists.
 * <p>// w ww .  j  a  v a  2  s  .c o  m
 * <b>Warning:</b> avoid using a {@code predicate} that matches {@code null}. If {@code null} is
 * matched in this fluent iterable, a {@link NullPointerException} will be thrown.
 * @param predicate the predicate
 * @return the optional
 */
public final Optional<E> firstMatch(Predicate<? super E> predicate) {
    return Optional.ofNullable(Iterables.tryFind(iterable, predicate::test).orNull());
}

From source file:org.apache.brooklyn.enricher.stock.Propagator.java

private Sensor<?> getDestinationSensor(final Sensor<?> sourceSensor) {
    // sensor equality includes the type; we want just name-equality so will use predicate.
    Optional<? extends Sensor<?>> mappingSensor = Iterables.tryFind(sensorMapping.keySet(),
            SensorPredicates.nameEqualTo(sourceSensor.getName()));

    return mappingSensor.isPresent() ? sensorMapping.get(mappingSensor.get()) : sourceSensor;
}

From source file:org.splevo.ui.vpexplorer.providers.VPExplorerContentProvider.java

@Override
public Object getParent(final Object element) {
    if (element instanceof VariationPoint) {
        File parent = vpFileIndex.get((VariationPoint) element);
        if (parent != null) {
            return parent;
        }/*from   w  w  w. j  av  a  2s . c o  m*/
        Optional<VariationPoint> corr = Iterables.tryFind(vpFileIndex.keySet(),
                new Predicate<VariationPoint>() {
                    @Override
                    public boolean apply(VariationPoint arg0) {
                        return arg0.getId().equals(((VariationPoint) element).getId());
                    }
                });
        if (corr.isPresent()) {
            return vpFileIndex.get(corr.get());
        }
        return null;
    } else if (element instanceof Variant) {
        return ((Variant) element).getVariationPoint();
    } else if (element instanceof SoftwareElement) {
        return ((SoftwareElement) element).eContainer();
    } else if (element instanceof File) {
        if (rootFiles.contains(element)) {
            return null;
        } else {
            return ((File) element).getParentFile();
        }
    } else if (element instanceof FileWrapper) {
        if (rootFiles.contains(((FileWrapper) element).getFile())) {
            return null;
        } else {
            return ((FileWrapper) element).getParent();
        }
    }
    return null;
}

From source file:com.thinkbiganalytics.metadata.modeshape.support.JcrVersionUtil.java

public static Version findVersion(Node node, final String versionName) {
    if (!isVersionable(node)) {
        return null;
    }//from w  ww.  j  a v a 2 s .  c o m
    Version version = Iterables.tryFind(getVersions(node), new Predicate<Version>() {
        @Override
        public boolean apply(Version version) {
            try {
                String identifier = node.getIdentifier();
                String frozenIdentifer = JcrPropertyUtil.getString(version.getFrozenNode(), "jcr:frozenUuid");
                return version.getName().equalsIgnoreCase(versionName)
                        && frozenIdentifer.equalsIgnoreCase(identifier);
            } catch (RepositoryException e) {

            }
            return false;
        }
    }).orNull();
    return version;
}

From source file:org.jclouds.aliyun.ecs.compute.strategy.CreateResourcesThenCreateNodes.java

private KeyPair getOrImportKeyPairForPublicKey(ECSServiceTemplateOptions options, String regionId) {
    logger.debug(">> checking if the key pair already exists...");
    PublicKey userKey = readPublicKey(options.getPublicKey());
    final String fingerprint = computeFingerprint(userKey);
    KeyPair keyPair;/*  w w w. ja  v a  2 s.c  om*/

    synchronized (CreateResourcesThenCreateNodes.class) {
        Optional<KeyPair> keyPairOptional = Iterables.tryFind(api.sshKeyPairApi().list(regionId).concat(),
                new Predicate<KeyPair>() {
                    @Override
                    public boolean apply(KeyPair input) {
                        return input.keyPairFingerPrint().equals(fingerprint.replace(":", ""));
                    }
                });
        if (!keyPairOptional.isPresent()) {
            logger.debug(">> key pair not found. Importing a new key pair %s ...", fingerprint);
            keyPair = api.sshKeyPairApi().importKeyPair(regionId, options.getPublicKey(),
                    namingConvention.create().uniqueNameForGroup(JCLOUDS_KEYPAIR_IMPORTED));
            logger.debug(">> key pair imported! %s", keyPair);
        } else {
            logger.debug(">> key pair found for key %s", fingerprint);
            keyPair = keyPairOptional.get();
        }
        return keyPair;
    }
}

From source file:io.druid.indexing.jdbc.supervisor.JDBCSupervisor.java

public JDBCSupervisor(final TaskStorage taskStorage, final TaskMaster taskMaster,
        final IndexerMetadataStorageCoordinator indexerMetadataStorageCoordinator,
        final JDBCIndexTaskClientFactory taskClientFactory, final ObjectMapper mapper,
        final JDBCSupervisorSpec spec) {
    this.taskStorage = taskStorage;
    this.taskMaster = taskMaster;
    this.indexerMetadataStorageCoordinator = indexerMetadataStorageCoordinator;
    this.sortingMapper = mapper.copy().configure(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY, true);
    this.spec = spec;
    this.emitter = spec.getEmitter();
    this.monitorSchedulerConfig = spec.getMonitorSchedulerConfig();

    this.dataSource = spec.getDataSchema().getDataSource();
    this.ioConfig = spec.getIoConfig();
    this.tuningConfig = spec.getTuningConfig();
    this.taskTuningConfig = JDBCTuningConfig.copyOf(this.tuningConfig);
    this.supervisorId = String.format("JDBCSupervisor-%s", dataSource);
    this.exec = Execs.singleThreaded(supervisorId);
    this.scheduledExec = Execs.scheduledSingleThreaded(supervisorId + "-Scheduler-%d");
    this.reportingExec = Execs.scheduledSingleThreaded(supervisorId + "-Reporting-%d");

    int workerThreads = Math.min(10, this.ioConfig.getTaskCount());
    this.workerExec = MoreExecutors
            .listeningDecorator(Execs.multiThreaded(workerThreads, supervisorId + "-Worker-%d"));
    log.info("Created worker pool with [%d] threads for dataSource [%s]", workerThreads, this.dataSource);

    this.taskInfoProvider = new TaskInfoProvider() {
        @Override/*  ww  w  .ja v a  2 s .  c om*/
        public TaskLocation getTaskLocation(final String id) {
            Preconditions.checkNotNull(id, "id");
            Optional<TaskRunner> taskRunner = taskMaster.getTaskRunner();
            if (taskRunner.isPresent()) {
                Optional<? extends TaskRunnerWorkItem> item = Iterables
                        .tryFind(taskRunner.get().getRunningTasks(), new Predicate<TaskRunnerWorkItem>() {
                            @Override
                            public boolean apply(TaskRunnerWorkItem taskRunnerWorkItem) {
                                return id.equals(taskRunnerWorkItem.getTaskId());
                            }
                        });

                if (item.isPresent()) {
                    return item.get().getLocation();
                }
            } else {
                log.error("Failed to get task runner because I'm not the leader!");
            }

            return TaskLocation.unknown();
        }

        @Override
        public Optional<TaskStatus> getTaskStatus(String id) {
            return taskStorage.getStatus(id);
        }
    };

    this.futureTimeoutInSeconds = Math.max(MINIMUM_FUTURE_TIMEOUT_IN_SECONDS,
            tuningConfig.getChatRetries() * (tuningConfig.getHttpTimeout().getStandardSeconds()
                    + JDBCIndexTaskClient.MAX_RETRY_WAIT_SECONDS));

    int chatThreads = (this.tuningConfig.getChatThreads() != null ? this.tuningConfig.getChatThreads()
            : Math.min(10, this.ioConfig.getTaskCount() * this.ioConfig.getReplicas()));
    this.taskClient = taskClientFactory.build(taskInfoProvider, dataSource, chatThreads,
            this.tuningConfig.getHttpTimeout(), this.tuningConfig.getChatRetries());
    log.info("Created taskClient with dataSource[%s] chatThreads[%d] httpTimeout[%s] chatRetries[%d]",
            dataSource, chatThreads, this.tuningConfig.getHttpTimeout(), this.tuningConfig.getChatRetries());
}

From source file:brooklyn.networking.sdn.mesos.CalicoModuleImpl.java

/** For Calico we use profiles to group containers in networks and add the required IP address to the eth1 calico interface. */
@Override//from   w  ww.  jav  a2s. com
public InetAddress attachNetwork(MesosSlave slave, Entity entity, String containerId, String subnetId) {
    InetAddress address = getNextContainerAddress(subnetId);

    // Run some commands to get information about the container network namespace
    String dockerIpOutput = slave.execCommand(sudo("ip addr show dev docker0 scope global label docker0"));
    String dockerIp = Strings.getFirstWordAfter(dockerIpOutput.replace('/', ' '), "inet");
    String inspect = Strings
            .trimEnd(slave.execCommand(sudo("docker inspect -f '{{.State.Pid}}' " + containerId)));
    String dockerPid = Iterables.find(Splitter.on(CharMatcher.anyOf("\r\n")).omitEmptyStrings().split(inspect),
            StringPredicates.matchesRegex("^[0-9]+$"));
    Cidr subnetCidr = getSubnetCidr(subnetId);
    String slaveAddressOutput = slave.execCommand(sudo("ip addr show dev eth0 scope global label eth0"));
    String slaveAddress = Strings.getFirstWordAfter(slaveAddressOutput.replace('/', ' '), "inet");

    // Determine whether we are attatching the container to the initial application network
    String applicationId = entity.getApplicationId();
    boolean initial = subnetId.equals(applicationId);

    // Add the container if we have not yet done so
    if (initial) {
        execCalicoCommand(slave,
                String.format("calicoctl container add %s %s", containerId, address.getHostAddress()));

        // Return its endpoint ID
        String getEndpointId = String.format("calicoctl container %s endpoint-id show", containerId);
        String getEndpointIdStdout = execCalicoCommand(slave, getEndpointId);
        Optional<String> endpointId = Iterables.tryFind(
                Splitter.on(CharMatcher.anyOf("\r\n")).split(getEndpointIdStdout),
                StringPredicates.matchesRegex("[0-9a-f]{32}"));
        if (!endpointId.isPresent())
            throw new IllegalStateException("Cannot find endpoint-id: " + getEndpointIdStdout);

        // Add to the application profile
        execCalicoCommand(slave, String.format("calicoctl profile add %s", subnetId));
        execCalicoCommand(slave,
                String.format("calicoctl endpoint %s profile append %s", endpointId.get(), subnetId));
    }

    // Set up the network
    List<String> commands = MutableList.of();
    commands.add(sudo("mkdir -p /var/run/netns"));
    commands.add(BashCommands
            .ok(sudo(String.format("ln -s /proc/%s/ns/net /var/run/netns/%s", dockerPid, dockerPid))));
    if (initial) {
        commands.add(sudo(String.format("ip netns exec %s ip route del default", dockerPid)));
        commands.add(sudo(String.format("ip netns exec %s ip route add default via %s", dockerPid, dockerIp)));
        commands.add(sudo(String.format("ip netns exec %s ip route add %s via %s", dockerPid,
                subnetCidr.toString(), slaveAddress)));
    } else {
        commands.add(sudo(String.format("ip netns exec %s ip addr add %s/%d dev eth1", dockerPid,
                address.getHostAddress(), subnetCidr.getLength())));
    }
    for (String cmd : commands) {
        slave.execCommand(cmd);
    }

    return address;
}