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:org.jclouds.chef.filters.SignedHeaderAuth.java

private Payload useTheFilePartIfForm(Payload payload) {
    if (payload instanceof MultipartForm) {
        Iterable<? extends Part> parts = MultipartForm.class.cast(payload).getRawContent();
        try {/* w w  w.j a v  a2  s.  c o m*/
            payload = Iterables.find(parts, new Predicate<Part>() {

                @Override
                public boolean apply(Part input) {
                    return "file".equals(input.getName());
                }

            });
        } catch (NoSuchElementException e) {

        }
    }
    return payload;
}

From source file:org.eclipse.sirius.tests.unit.api.layers.MultipleMappingImportTests2.java

private DDiagramElement findByTargetName(final List<DDiagramElement> list, final String targetName) {
    DDiagramElement found = Iterables.find(list, new Predicate<DDiagramElement>() {
        public boolean apply(DDiagramElement input) {
            return input.getTarget() instanceof ENamedElement
                    && targetName.equals(((ENamedElement) input.getTarget()).getName());
        }/*from  ww  w  .  ja va 2s  .  c om*/
    });
    assertNotNull("'" + targetName + "' element not found", found);
    return found;
}

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

public VmVolumeAttachment lookupVolumeAttachmentByDevice(String volumeDevice) {
    return Iterables.find(this.attachments, VmVolumeAttachment.volumeDeviceFilter(volumeDevice));
}

From source file:org.opentestsystem.authoring.testauth.publish.PublisherRunner.java

@Async
public void publishAndSend(final Assessment assessment, final PublishingRecord publishingRecord) {
    final List<Purpose> specTypesToPublish = Lists.newArrayList(publishingRecord.getPurpose());
    try {//from  w  ww  . java2s .c  om
        TestSpecification<? extends PurposeBaseContent> seedingTestSpec = null;
        if (specTypesToPublish.contains(Purpose.COMPLETE)) {
            seedingTestSpec = createTestSpec(assessment, publishingRecord, Purpose.COMPLETE, false, null);
            final byte[] processedXml = generateAndValidateXml(seedingTestSpec);
            sendToTestSpecBank(seedingTestSpec, processedXml, assessment);
        }
        if (specTypesToPublish.contains(Purpose.ADMINISTRATION)) {
            final TestSpecification<? extends PurposeBaseContent> adminTestSpec = createTestSpec(assessment,
                    publishingRecord, Purpose.ADMINISTRATION, false, seedingTestSpec);
            final byte[] processedXml = generateAndValidateXml(adminTestSpec);
            sendToTestSpecBank(adminTestSpec, processedXml, assessment);
            if (!specTypesToPublish.contains(Purpose.COMPLETE)) {
                seedingTestSpec = adminTestSpec;
            } else {
                specTypesToPublish.remove(Purpose.COMPLETE);
            }
            specTypesToPublish.remove(Purpose.ADMINISTRATION);
        }
        for (final Purpose purpose : specTypesToPublish) {
            final TestSpecification<? extends PurposeBaseContent> testSpec = createTestSpec(assessment,
                    publishingRecord, purpose, false, seedingTestSpec);
            final byte[] processedXml = generateAndValidateXml(testSpec);
            sendToTestSpecBank(testSpec, processedXml, assessment);
        }

        publishingRecord.setPublishingStatus(PublishingStatus.PUBLISHED);
        publishingRecord.setErrorMessageText("");
        publishingRecord.setLastUpdatedDate(new DateTime());
        this.publishingRecordRepository.save(publishingRecord);

    } catch (final Exception e) {
        // publishing failed somewhere in creating elements for XML, marshalling, validating, or sending to TSB
        publishingRecord.setPublishingStatus(PublishingStatus.AWAITING_APPROVAL);

        // attempt to render the error code from within the publisher helpers/tsb/validation into a user-readable message
        String messageText = "Specification XML could not be published";
        if (e instanceof LocalizedException) {
            final LocalizedException le = (LocalizedException) e;
            messageText = this.messageSource.getMessage(le.getMessageCode(), le.getMessageArgs(), Locale.US);
        }
        publishingRecord.setErrorMessageText(messageText);
        publishingRecord.setLastUpdatedDate(new DateTime());
        this.publishingRecordRepository.save(publishingRecord);

        final List<Approval> approvalList = this.approvalService
                .retrieveLatestApprovals(publishingRecord.getId());
        final Approval qaLeadApproval = Iterables.find(approvalList, QA_LEAD_FILTER);
        if (qaLeadApproval != null) {
            qaLeadApproval.setStatus(ApprovalStatus.PENDING);
            this.approvalRepository.save(qaLeadApproval);
        }

        LOGGER.error("Test Specification XML publishing failed; error: ["
                + publishingRecord.getErrorMessageText() + "]", e);
    } finally {
        assessment.setStatus(publishingRecord.getPublishingStatus());
        this.assessmentRepository.save(assessment);
    }
}

From source file:org.richfaces.cdk.generate.freemarker.ModelElementBaseTemplateModel.java

private TemplateModel defaultEvent() throws TemplateModelException {
    Set<EventName> names = getEventNames();

    try {//from  ww w. j  a v  a2 s  .c  o m
        EventName defaultEvent = Iterables.find(names, new Predicate<EventName>() {
            @Override
            public boolean apply(EventName event) {
                return event.isDefaultEvent();
            }
        });

        return wrapper.wrap(defaultEvent);
    } catch (NoSuchElementException e) {
        return wrapper.wrap(null);
    }
}

From source file:com.eucalyptus.reporting.ReportingDataVerifier.java

/**
 * Get the events neccessary to align the current view with the target view.
 *
 * @param target The desired "event" state
 * @param current The current state//  ww  w.  ja va2 s  .c om
 * @return The bag describing the necessary events
 */
public static EventDescriptionBag getEventDifferences(final View target, final View current) {
    final EventDescriptionBag description = new EventDescriptionBag();

    final Set<Class<?>> types = Sets.newHashSet(Iterables
            .transform(Iterables.concat(target.typedResourceHolders, current.typedResourceHolders), type()));
    for (final Class<?> type : types) {
        final TypedResourceHolder targetHolder = target.getHolderOrNull(type);
        final TypedResourceHolder currentHolder = current.getHolderOrNull(type);

        if (targetHolder == null) {
            description.delete.add(currentHolder);
        } else if (currentHolder == null) {
            description.create.add(targetHolder);
        } else { // determine difference
            final TypedResourceHolder add = new TypedResourceHolder(type);
            final TypedResourceHolder del = new TypedResourceHolder(type);
            final TypedResourceHolder att = new TypedResourceHolder(type);
            final TypedResourceHolder det = new TypedResourceHolder(type);

            // create copies containing only items that differ
            List<ResourceWithRelation<?>> targetCopy = Lists.newArrayList(targetHolder.resources);
            List<ResourceWithRelation<?>> currentCopy = Lists.newArrayList(currentHolder.resources);
            targetCopy.removeAll(currentHolder.resources);
            currentCopy.removeAll(targetHolder.resources);

            final Set<ResourceKey> keys = Sets
                    .newHashSet(Iterables.transform(Iterables.concat(targetCopy, currentCopy), key()));
            for (final ResourceKey key : keys) {
                final List<ResourceWithRelation<?>> findIn;
                final TypedResourceHolder addTo;
                if (!Iterables.contains(Iterables.transform(targetCopy, key()), key)) {
                    findIn = currentCopy;
                    addTo = del;
                } else if (!Iterables.contains(Iterables.transform(currentCopy, key()), key)) {
                    findIn = targetCopy;
                    addTo = add;
                } else if (Iterables.find(targetCopy, withKeyMatching(key)).relationId == null) {
                    findIn = currentCopy;
                    addTo = det;
                } else {
                    findIn = targetCopy;
                    addTo = att;
                }
                addTo.resources.add(Iterables.find(findIn, withKeyMatching(key)));
            }

            if (!add.resources.isEmpty())
                description.create.add(add);
            if (!del.resources.isEmpty())
                description.delete.add(del);
            if (!att.resources.isEmpty())
                description.attach.add(att);
            if (!det.resources.isEmpty())
                description.detach.add(det);
        }
    }

    return description;
}

From source file:gov.nih.nci.firebird.selenium2.pages.components.tags.SponsorReviewRegistrationFormsTable.java

private WebElement getTable() {
    return Iterables.find(findElements(By.id(TABLE_ID)), new Predicate<WebElement>() {
        public boolean apply(WebElement table) {
            return table.isDisplayed();
        }// w w  w .j  a v a2 s. c o  m
    });
}

From source file:org.jclouds.blobstore.integration.internal.StubAsyncBlobStore.java

public Future<? extends ListContainerResponse<? extends ResourceMetadata>> list(final String name,
        ListContainerOptions... optionsList) {
    final ListContainerOptions options = (optionsList.length == 0) ? new ListContainerOptions()
            : optionsList[0];//from  w  w w  .j av  a  2 s .co m
    return new FutureBase<ListContainerResponse<ResourceMetadata>>() {
        public ListContainerResponse<ResourceMetadata> get() throws InterruptedException, ExecutionException {
            final Map<String, Blob> realContents = getContainerToBlobs().get(name);

            if (realContents == null)
                throw new ContainerNotFoundException(name);

            SortedSet<ResourceMetadata> contents = Sets.newTreeSet(
                    Iterables.transform(realContents.keySet(), new Function<String, ResourceMetadata>() {
                        public ResourceMetadata apply(String key) {
                            return copy(realContents.get(key).getMetadata());
                        }
                    }));

            if (options.getMarker() != null) {
                final String finalMarker = options.getMarker();
                ResourceMetadata lastMarkerMetadata = Iterables.find(contents,
                        new Predicate<ResourceMetadata>() {
                            public boolean apply(ResourceMetadata metadata) {
                                return metadata.getName().equals(finalMarker);
                            }
                        });
                contents = contents.tailSet(lastMarkerMetadata);
                contents.remove(lastMarkerMetadata);
            }

            final String prefix = options.getPath();
            if (prefix != null) {
                contents = Sets.newTreeSet(Iterables.filter(contents, new Predicate<ResourceMetadata>() {
                    public boolean apply(ResourceMetadata o) {
                        return (o != null && o.getName().startsWith(prefix));
                    }
                }));
            }

            int maxResults = contents.size();
            boolean truncated = false;
            String marker = null;
            if (options.getMaxResults() != null && contents.size() > 0) {
                SortedSet<ResourceMetadata> contentsSlice = firstSliceOfSize(contents,
                        options.getMaxResults().intValue());
                maxResults = options.getMaxResults();
                if (!contentsSlice.contains(contents.last())) {
                    // Partial listing
                    truncated = true;
                    marker = contentsSlice.last().getName();
                } else {
                    marker = null;
                }
                contents = contentsSlice;
            }

            final String delimiter = options.isRecursive() ? null : "/";
            if (delimiter != null) {
                SortedSet<String> commonPrefixes = null;
                Iterable<String> iterable = Iterables.transform(contents,
                        new CommonPrefixes(prefix != null ? prefix : null, delimiter));
                commonPrefixes = iterable != null ? Sets.newTreeSet(iterable) : new TreeSet<String>();
                commonPrefixes.remove(CommonPrefixes.NO_PREFIX);

                contents = Sets.newTreeSet(Iterables.filter(contents,
                        new DelimiterFilter(prefix != null ? prefix : null, delimiter)));

                Iterables.<ResourceMetadata>addAll(contents,
                        Iterables.transform(commonPrefixes, new Function<String, ResourceMetadata>() {
                            public ResourceMetadata apply(String o) {
                                MutableResourceMetadata md = new MutableResourceMetadataImpl();
                                md.setType(ResourceType.RELATIVE_PATH);
                                md.setName(o);
                                return md;
                            }
                        }));
            }
            return new ListContainerResponseImpl<ResourceMetadata>(contents, prefix, marker, maxResults,
                    truncated);
        }
    };
}

From source file:com.eucalyptus.empyrean.EmpyreanService.java

public static ServiceConfiguration findService(final String name) {
    checkParam(name, notNullValue());//ww  w .j a v  a 2  s .  c  o  m
    Predicate<ServiceConfiguration> nameOrFullName = new Predicate<ServiceConfiguration>() {

        @Override
        public boolean apply(ServiceConfiguration input) {
            return name.equals(input.getName()) || name.equals(input.getFullName().toString());
        }
    };
    for (final ComponentId compId : ComponentIds.list()) {
        ServiceConfiguration a;
        try {
            return Iterables.find(Components.lookup(compId).services(), nameOrFullName);
        } catch (NoSuchElementException ex) {
            if (compId.isRegisterable()) {
                try {
                    return ServiceConfigurations.lookupByName(compId.getClass(), name);
                } catch (Exception ex1) {
                }
            }
        }
    }
    throw new NoSuchElementException("Failed to lookup service named: " + name);
}

From source file:org.alkemy.instr.DefaultAlkemizableVisitor.java

@Override
public boolean isClassAlkemizable() {
    return Iterables.find(fieldMap.values(), p -> p.alkemizable) != null
            || Iterables.find(methodMap.values(), p -> p.alkemizable) != null;
}