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:org.incode.eurocommercial.contactapp.dom.contacts.Contact.java

@Action(semantics = SemanticsOf.IDEMPOTENT)
@ActionLayout(named = "Remove")
@MemberOrder(name = "contactRoles", sequence = "2")
public Contact removeContactRole(ContactGroup contactGroup) {
    final Optional<ContactRole> contactRoleIfAny = Iterables.tryFind(getContactRoles(),
            cn -> Objects.equal(cn.getContactGroup(), contactGroup));

    if (contactRoleIfAny.isPresent()) {
        getContactRoles().remove(contactRoleIfAny.get());
    }//w w w .  j  a v  a2  s.  c o m
    return this;
}

From source file:com.eucalyptus.simpleworkflow.ActivityTask.java

public Pair<String, Date> calculateNextTimeout() {
    final Iterable<Pair<String, Optional<Long>>> taggedTimeouts = Iterables.filter(Lists.newArrayList(
            Pair.ropair("SCHEDULE_TO_CLOSE", toTimeout(getCreationTimestamp(), getScheduleToCloseTimeout())),
            Pair.ropair("SCHEDULE_TO_START", toTimeout(getCreationTimestamp(), getScheduleToStartTimeout())),
            getState() == State.Active
                    ? Pair.ropair("START_TO_CLOSE", toTimeout(getStartedTimestamp(), getStartToCloseTimeout()))
                    : null,/*from   w  w w .ja  v  a  2  s.co m*/
            getState() == State.Active
                    ? Pair.ropair("HEARTBEAT", toTimeout(getLastUpdateTimestamp(), getHeartbeatTimeout()))
                    : null),
            Predicates.notNull());
    final Function<Pair<String, Optional<Long>>, Long> timeExtractor = Functions
            .compose(CollectionUtils.<Long>optionalOrNull(), Pair.<String, Optional<Long>>right());
    final Long timeout = CollectionUtils.reduce(
            CollectionUtils.fluent(taggedTimeouts).transform(timeExtractor).filter(Predicates.notNull()),
            Long.MAX_VALUE, CollectionUtils.lmin());
    final String tag = Iterables
            .tryFind(taggedTimeouts, CollectionUtils.propertyPredicate(timeout, timeExtractor))
            .transform(Pair.<String, Optional<Long>>left()).or("SCHEDULE_TO_CLOSE");
    return timeout == Long.MAX_VALUE ? null : Pair.pair(tag, new Date(timeout));
}

From source file:org.jclouds.virtualbox.functions.NodeCreator.java

private void reconfigureNatInterfaceIfNeeded(final String guestOsUser, final String guestOsPassword,
        String osTypeId, IMachine clone, NetworkSpec networkSpec) {

    final String scriptName = "nat";
    final String folder = "redHatAndDerivatives";
    if (osTypeId.contains("RedHat")) {
        File scriptFile = copyScriptToWorkingDir(folder, scriptName);
        copyToNodeAndExecScript(guestOsUser, guestOsPassword, clone.getName(), scriptFile);
    } else if (osTypeId.contains("Ubuntu") || osTypeId.contains("Debian")) {
        NodeMetadata partialNodeMetadata = buildPartialNodeMetadata(clone, guestOsUser, guestOsPassword);

        Optional<NetworkInterfaceCard> optionalNatIfaceCard = Iterables
                .tryFind(networkSpec.getNetworkInterfaceCards(), new Predicate<NetworkInterfaceCard>() {

                    @Override//w w  w  . jav a 2  s.  c o  m
                    public boolean apply(NetworkInterfaceCard nic) {
                        return nic.getNetworkAdapter().getNetworkAttachmentType()
                                .equals(NetworkAttachmentType.NAT);
                    }
                });

        checkState(networkUtils.enableNetworkInterface(partialNodeMetadata, optionalNatIfaceCard.get()),
                "cannot enable NAT Interface on vm(%s)", clone.getName());
    }
}

From source file:com.google.caliper.maven.BenchmarkMojo.java

private void checkCaliperDependency() throws MojoExecutionException {
    // check Caliper library is available
    Optional caliper = Iterables.tryFind(project.getArtifacts(), CALIPER_PREDICATE);
    if (!caliper.isPresent()) {
        throw dependencyNotFound(CALIPER_GROUP_ID, CALIPER_ARTIFACT_ID);
    }//w  ww.j  ava 2s . co  m
    getLog().debug("Using Caliper library " + caliper.get());

    // get java agent for allocation instrument, Caliper won't run without it
    if (isNullOrEmpty(allocationAgentJar)) {
        Optional allocation = Iterables.tryFind(project.getArtifacts(), ALLOCATION_PREDICATE);
        if (!allocation.isPresent()) {
            throw new IllegalArgumentException("Can't find allocation agent jar on the classpath");
        }
        Artifact a = (Artifact) allocation.get();
        allocationAgentJar = a.getFile().getAbsolutePath();
    }
    File agentJar = new File(allocationAgentJar);
    if (!agentJar.isFile() || !agentJar.canRead()) {
        throw new IllegalArgumentException(
                "Can't read agent jar " + allocationAgentJar + " (check file exists and its permissions)");
    }
    getLog().debug("Using allocation library " + allocationAgentJar);
}

From source file:com.google.devtools.build.android.SplitConfigurationFilter.java

/**
 * Checks if the {@code other} split configuration filter could have been produced as a filename
 * by aapt based on this configuration filter being passed as a split flag.
 *
 * <p>This means that there must be a one-to-one mapping from each configuration in this filter to
 * a configuration in the {@code other} filter such that the non-API-version specifiers of the two
 * configurations match and the API version specifier of the {@code other} filter's configuration
 * is greater than or equal to the API version specifier of this filter's configuration.
 *
 * <p>Order of whole configurations doesn't matter, as aapt will reorder the configurations
 * according to complicated internal logic (yes, logic even more complicated than this!).
 *
 * <p>Care is needed with API version specifiers because aapt may add or change minimum
 * API version specifiers to configurations according to whether they had specifiers which are
 * only supported in certain versions of Android. It will only ever increase the minimum version
 * or leave it the same.//from   ww w  .  j a v a 2 s  . c o  m
 *
 * <p>The other (non-wildcard) specifiers should be case-insensitive identical, including order;
 * aapt will not allow parts of a single configuration to be parsed out of order.
 *
 * @see ResourceConfiguration#matchesConfigurationFromFilename(ResourceConfiguration)
 */
boolean matchesFilterFromFilename(SplitConfigurationFilter filenameFilter) {
    if (filenameFilter.configs.size() != this.configs.size()) {
        return false;
    }

    List<ResourceConfiguration> unmatchedConfigs = new ArrayList<>(this.configs);
    for (ResourceConfiguration filenameConfig : filenameFilter.configs) {
        Optional<ResourceConfiguration> matched = Iterables.tryFind(unmatchedConfigs,
                new ResourceConfiguration.MatchesConfigurationFromFilename(filenameConfig));
        if (!matched.isPresent()) {
            return false;
        }
        unmatchedConfigs.remove(matched.get());
    }
    return true;
}

From source file:org.killbill.billing.tenant.api.user.DefaultTenantUserApi.java

private boolean isCachedInTenantKVCache(final String key) {
    return Iterables.tryFind(CACHED_TENANT_KEY, new Predicate<TenantKey>() {
        @Override//from w  ww. j  a v  a 2 s  .  co m
        public boolean apply(final TenantKey input) {
            return key.startsWith(input.toString());
        }
    }).orNull() != null;
}

From source file:com.google.gerrit.server.change.Submit.java

private static Optional<SubmitRecord> findOkRecord(Collection<SubmitRecord> in) {
    return Iterables.tryFind(in, new Predicate<SubmitRecord>() {
        @Override//from w w  w .j a  v a2  s .c o  m
        public boolean apply(SubmitRecord input) {
            return input.status == OK;
        }
    });
}

From source file:org.incode.eurocommercial.contactapp.dom.group.ContactGroup.java

@Action(semantics = SemanticsOf.IDEMPOTENT)
@ActionLayout(named = "Remove")
@MemberOrder(name = "contactRoles", sequence = "2")
public ContactGroup removeContactRole(final Contact contact) {
    final Optional<ContactRole> contactRoleIfAny = Iterables.tryFind(getContactRoles(),
            cn -> Objects.equal(cn.getContact(), contact));

    if (contactRoleIfAny.isPresent()) {
        getContactRoles().remove(contactRoleIfAny.get());
    }/*w ww.jav a 2 s .  c o m*/
    return this;
}

From source file:com.textocat.textokit.commons.cas.AnnotationUtils.java

public static <A extends Annotation> A findByCoveredText(JCas jCas, Class<A> annoClass,
        final String coveredText) {
    Optional<A> findRes = Iterables.tryFind(jCas.getAnnotationIndex(annoClass), new Predicate<A>() {
        @Override/*from   w  w w  .  ja  v  a2  s .  c  o m*/
        public boolean apply(A input) {
            return Objects.equals(input.getCoveredText(), coveredText);
        }
    });
    return findRes.orNull();
}

From source file:clocker.docker.location.DockerLocation.java

@Override
public MachineLocation obtain(Map<?, ?> flags) throws NoMachinesAvailableException {
    // Check context for entity being deployed
    Object context = flags.get(LocationConfigKeys.CALLER_CONTEXT.getName());
    if (context != null && !(context instanceof Entity)) {
        throw new IllegalStateException("Invalid location context: " + context);
    }//from w w  w.  j  av a2  s.  co  m
    Entity entity = (Entity) context;

    // Get the available hosts
    List<DockerHostLocation> available = getDockerHostLocations();
    LOG.debug("Placement for: {}", Iterables.toString(Iterables.transform(available, EntityFunctions.id())));

    // Apply placement strategies
    List<DockerAwarePlacementStrategy> entityStrategies = entity.config()
            .get(DockerAttributes.PLACEMENT_STRATEGIES);
    if (entityStrategies == null)
        entityStrategies = ImmutableList.of();
    for (DockerAwarePlacementStrategy strategy : Iterables.concat(strategies, entityStrategies)) {
        available = strategy.filterLocations(available, entity);
        LOG.debug("Placement after {}: {}", strategy,
                Iterables.toString(Iterables.transform(available, EntityFunctions.id())));
    }

    // Use the provisioning strategy to add a new host
    DockerHostLocation machine = null;
    DockerHost dockerHost = null;
    if (available.size() > 0) {
        machine = available.get(0);
        dockerHost = machine.getOwner();
    } else {
        // Get permission to create a new Docker host
        if (permit.tryAcquire()) {
            try {
                // Determine if headroom scaling policy is being used and suspend
                Integer headroom = getOwner().config().get(ContainerHeadroomEnricher.CONTAINER_HEADROOM);
                Double headroomPercent = getOwner().config()
                        .get(ContainerHeadroomEnricher.CONTAINER_HEADROOM_PERCENTAGE);
                boolean headroomSet = (headroom != null && headroom > 0)
                        || (headroomPercent != null && headroomPercent > 0d);
                Optional<Policy> policy = Iterables.tryFind(getOwner().getDockerHostCluster().policies(),
                        Predicates.instanceOf(AutoScalerPolicy.class));
                if (headroomSet && policy.isPresent())
                    policy.get().suspend();

                try {
                    // Resize the host cluster
                    LOG.info("Provisioning new host");
                    Entity added = Iterables.getOnlyElement(getOwner().getDockerHostCluster().resizeByDelta(1));
                    dockerHost = (DockerHost) added;
                    machine = dockerHost.getDynamicLocation();

                    // Update autoscaler policy with new minimum size and resume
                    if (headroomSet && policy.isPresent()) {
                        int currentMin = policy.get().config().get(AutoScalerPolicy.MIN_POOL_SIZE);
                        LOG.info("Updating autoscaler policy ({}) setting {} to {}", new Object[] {
                                policy.get(), AutoScalerPolicy.MIN_POOL_SIZE.getName(), currentMin + 1 });
                        policy.get().config().set(AutoScalerPolicy.MIN_POOL_SIZE, currentMin + 1);
                    }
                } finally {
                    if (policy.isPresent())
                        policy.get().resume();
                }
            } finally {
                permit.release();
            }
        } else {
            // Wait until whoever has the permit releases it, and try again
            try {
                permit.acquire();
            } catch (InterruptedException ie) {
                Exceptions.propagate(ie);
            } finally {
                permit.release();
            }
            return obtain(flags);
        }
    }

    // Now wait until the host has started up
    Entities.waitForServiceUp(dockerHost);

    // Obtain a new Docker container location, save and return it
    try {
        LOG.debug("Obtain a new container from {} for {}", machine, entity);
        Map<?, ?> hostFlags = MutableMap.copyOf(flags);
        DockerContainerLocation container = machine.obtain(hostFlags);
        containers.put(machine, container.getId());
        return container;
    } finally {
        // Release any placement strategy locks
        for (DockerAwarePlacementStrategy strategy : Iterables.concat(strategies, entityStrategies)) {
            if (strategy instanceof WithMutexes) {
                ((WithMutexes) strategy).releaseMutex(entity.getApplicationId());
            }
        }
    }
}