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:codex.extract.JavaExtractor.java

private void process0(Iterable<? extends JavaFileObject> files, Writer writer) {
    try {//  w w  w .  j ava 2s .  co  m
        // we set our output dir to tmp.dir just in case annotation processors decide to generate
        // output even though we don't want any
        List<String> opts = Lists.newArrayList("-Xjcov", "-d", System.getProperty("java.io.tmpdir"));

        String cp = Joiner.on(File.pathSeparator).join(classpath());
        if (cp.length() > 0) {
            opts.add("-classpath");
            opts.add(cp);
        }

        int[] diags = new int[Diagnostic.Kind.values().length];
        DiagnosticListener<JavaFileObject> diag = new DiagnosticListener<JavaFileObject>() {
            public void report(Diagnostic<? extends JavaFileObject> diagnostic) {
                diags[diagnostic.getKind().ordinal()]++;
            }
        };
        JavacTaskImpl task = (JavacTaskImpl) _compiler.getTask(null, null, diag, opts, null, files);
        Iterable<? extends CompilationUnitTree> asts = task.parse();
        task.analyze(); // don't need results, but need annotations in tree

        writer.openSession();
        try {
            Context context = task.getContext();
            ExtractingScanner scanner = new ExtractingScanner(Types.instance(context), _omitBodies);
            for (CompilationUnitTree tree : asts) {
                scanner.extract(tree, writer);
            }
        } finally {
            writer.closeSession();
        }

        // annoyingly, there's no (public) way to tell the task that we're done without generating
        // .class files, so instead we have to do this reach around
        Method endContext = Iterables.find(Arrays.asList(task.getClass().getDeclaredMethods()),
                m -> m.getName().equals("cleanup"));
        endContext.setAccessible(true);
        endContext.invoke(task);

        // report the number of diagnostics
        StringBuilder sb = new StringBuilder();
        for (Diagnostic.Kind kind : Diagnostic.Kind.values()) {
            int count = diags[kind.ordinal()];
            if (count == 0)
                continue;
            if (sb.length() > 0)
                sb.append(", ");
            sb.append(kind.toString().toLowerCase()).append('=').append(count);
        }
        if (sb.length() > 0)
            log("Diagnostics [" + sb + "]");

    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.jclouds.ec2.compute.functions.EC2ImageParser.java

@Override
public Image apply(final org.jclouds.ec2.domain.Image from) {
    if (from.getImageType() != ImageType.MACHINE) {
        return null;
    }/*w ww. j  a v a2  s . c o m*/
    ImageBuilder builder = new ImageBuilder();
    builder.providerId(from.getId());
    builder.id(from.getRegion() + "/" + from.getId());
    builder.name(from.getName());
    builder.description(from.getDescription() != null ? from.getDescription() : from.getImageLocation());
    builder.userMetadata(ImmutableMap.<String, String>builder().put("owner", from.getImageOwnerId())
            .put("rootDeviceType", from.getRootDeviceType().value())
            .put("virtualizationType", from.getVirtualizationType().value())
            .put("hypervisor", from.getHypervisor().value()).build());

    OperatingSystem.Builder osBuilder = OperatingSystem.builder();
    osBuilder.is64Bit(from.getArchitecture() == Architecture.X86_64);
    OsFamily family = parseOsFamily(from);
    osBuilder.family(family);
    osBuilder.version(
            ComputeServiceUtils.parseVersionOrReturnEmptyString(family, from.getImageLocation(), osVersionMap));
    osBuilder.description(from.getImageLocation());
    osBuilder.arch(from.getVirtualizationType().value());

    reviseParsedImage.reviseParsedImage(from, builder, family, osBuilder);

    builder.defaultCredentials(credentialProvider.apply(from));

    try {
        builder.location(Iterables.find(locations.get(), new Predicate<Location>() {

            @Override
            public boolean apply(Location input) {
                return input.getId().equals(from.getRegion());
            }

        }));
    } catch (NoSuchElementException e) {
        logger.error("unknown region %s for image %s; not in %s", from.getRegion(), from.getId(), locations);
        builder.location(new LocationBuilder().scope(LocationScope.REGION).id(from.getRegion())
                .description(from.getRegion()).parent(defaultLocation.get()).build());
    }
    builder.operatingSystem(osBuilder.build());
    builder.status(toPortableImageStatus.get(from.getImageState()));
    builder.backendStatus(from.getRawState());
    return builder.build();
}

From source file:org.linagora.linshare.view.tapestry.components.ListThreadMembers.java

public void onActionFromDeleteMember(String identifier) {
    toDelete = Iterables.find(members, ThreadMemberVo.equalTo(identifier));
    selectedMemberId = identifier;
}

From source file:org.jclouds.gogrid.compute.functions.ServerToNodeMetadata.java

protected Hardware parseHardware(Server from) {
    Hardware hardware = null;/*from   w w w. j a  va2  s. c  o m*/
    try {
        hardware = Iterables.find(hardwares.get(), new FindHardwareForServer(from));
    } catch (NoSuchElementException e) {
        logger.debug("could not find a matching hardware for server %s", from);
    }
    return hardware;
}

From source file:org.jclouds.openstack.nova.compute.functions.ServerToNodeMetadata.java

protected Image parseImage(Server from) {
    try {//from  w  w w.  j  a  va2  s . c  om
        return Iterables.find(images.get(), new FindImageForServer(from));
    } catch (NoSuchElementException e) {
        logger.warn("could not find a matching image for server %s in location %s", from, location);
    }
    return null;
}

From source file:com.eucalyptus.compute.common.internal.vm.VmVolumeState.java

public VmVolumeAttachment removeVolumeAttachment(final String volumeId) throws NoSuchElementException {
    final VmVolumeAttachment v = Iterables.find(this.attachments, VmVolumeAttachment.volumeIdFilter(volumeId));
    if (v == null) {
        throw new NoSuchElementException("Failed to find volume attachment for instance "
                + this.getVmInstance().getInstanceId() + " and volume " + volumeId);
    } else {/*from  www  . j  a  va 2  s . c  o m*/
        this.attachments.remove(v);
        return v;
    }
}

From source file:org.apache.brooklyn.entity.database.mysql.InitSlaveTaskBody.java

private MySqlNode getMaster() {
    return (MySqlNode) Iterables.find(cluster.getMembers(), MySqlClusterUtils.IS_MASTER);
}

From source file:org.iglootools.hchelpers.java.HttpClientTemplate.java

private HttpErrorHandler findHttpErrorHandlerApplyingToResponse(Iterable<HttpErrorHandler> httpErrorHandlers,
        final HttpResponse httpResponse) {
    try {//from  w w w .  j  ava2 s. com
        return Iterables.find(Iterables.concat(httpErrorHandlers, this.defaultErrorHandlers),
                new Predicate<HttpErrorHandler>() {
                    public boolean apply(HttpErrorHandler input) {
                        return input.apppliesTo(httpResponse.getStatusLine());
                    }
                });
    } catch (NoSuchElementException e) {
        return null;
    }
}

From source file:brooklyn.networking.vclouddirector.PortForwarderVcloudDirector.java

@Override
public void inject(Entity owner, List<Location> locations) {
    subnetTier = (SubnetTier) owner;/*from w w  w. ja  va 2s  .  co  m*/
    jcloudsLocation = (JcloudsLocation) Iterables.find(locations, Predicates.instanceOf(JcloudsLocation.class));
    getClient(); // force load of client: fail fast if configuration is missing
    getPortRange();
    getNatMicroserviceAutoAllocatesPorts();
}

From source file:org.jclouds.cloudservers.compute.functions.ServerToNodeMetadata.java

protected OperatingSystem parseOperatingSystem(Server from) {
    try {/* ww w. ja va2 s .c  o m*/
        return Iterables.find(images.get(), new FindImageForServer(from)).getOperatingSystem();
    } catch (NoSuchElementException e) {
        logger.debug("could not find a matching image for server %s in location %s", from, location.get());
    }
    return null;
}