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

@Nullable
public static <T> T find(Iterable<? extends T> iterable, Predicate<? super T> predicate,
        @Nullable T defaultValue) 

Source Link

Document

Returns the first element in iterable that satisfies the given predicate, or defaultValue if none found.

Usage

From source file:com.eviware.loadui.ui.fx.views.workspace.WorkspaceView.java

private void initProjectRefCarousel() {
    final Observables.Group<ReadOnlyStringProperty> group = Observables.group(new ReadOnlyStringProperty[0]);
    final MenuItem[] carouselMenuItems = MenuItemsProvider.createWith(projectRefCarousel, null,
            Options.are().noDelete().noRename().create(ProjectItem.class, CREATE_PROJECT)).items();

    final ContextMenu ctxMenu = ContextMenuBuilder.create().items(carouselMenuItems).build();

    projectRefCarousel.setOnContextMenuRequested(new EventHandler<ContextMenuEvent>() {
        @Override/*from   w ww  .  jav a 2s  . co m*/
        public void handle(ContextMenuEvent event) {
            boolean hasProject = !projectRefCarousel.getItems().isEmpty();
            if (hasProject && NodeUtils.isMouseOn(projectRefCarousel.getSelected().getMenuButton()))
                return; // never show contextMenu when on top of the menuButton

            ctxMenu.getItems()
                    .setAll(hasProject && NodeUtils.isMouseOn(projectRefCarousel.getSelected())
                            ? projectRefCarousel.getSelected().getMenuItemProvider().items()
                            : carouselMenuItems);
            MenuItemsProvider.showContextMenu(projectRefCarousel, ctxMenu);
            event.consume();
        }
    });

    bindSorted(projectRefCarousel.getItems(), projectRefViews, Ordering.usingToString(), group);

    labelProperties = ObservableLists.transform(projectRefCarousel.getItems(),
            new Function<ProjectRefView, ReadOnlyStringProperty>() {
                @Override
                public ReadOnlyStringProperty apply(ProjectRefView projectRefView) {
                    return projectRefView.labelProperty();
                }
            });

    bindContent(group.getObservables(), labelProperties);

    final String lastProject = workspace.getAttribute("lastOpenProject", "");
    projectRefCarousel
            .setSelected(Iterables.find(projectRefCarousel.getItems(), new Predicate<ProjectRefView>() {
                @Override
                public boolean apply(@Nullable ProjectRefView view) {
                    return lastProject.equals(view.getProjectRef().getProjectFile().getAbsolutePath());
                }
            }, Iterables.getFirst(projectRefCarousel.getItems(), null)));

    projectRefCarousel.addEventHandler(DraggableEvent.ANY, new EventHandler<DraggableEvent>() {
        @Override
        public void handle(DraggableEvent event) {
            if (event.getEventType() == DraggableEvent.DRAGGABLE_ENTERED
                    && event.getData() instanceof NewProjectIcon) {
                event.accept();
            } else if (event.getEventType() == DraggableEvent.DRAGGABLE_DROPPED) {
                fireEvent(IntentEvent.create(IntentEvent.INTENT_CREATE, ProjectItem.class));
            }
        }
    });
}

From source file:edu.sabanciuniv.sentilab.sare.controllers.entitymanagers.LexiconBuilderController.java

/**
 * Sets the provided document and all tokens contained therein as having been seen.
 * @param em the {@link EntityManager} to use.
 * @param document the {@link LexiconBuilderDocument} object to mark as seen.
 * @param seenTags a delimited list of POS tags to mark as seen.
 * @return the supplied {@link LexiconBuilderDocument}.
 *//*  w  w  w .j  a v  a  2 s .  co m*/
public LexiconBuilderDocument setSeenDocument(EntityManager em, LexiconBuilderDocument document,
        String seenTags) {
    Validate.notNull(em, CannedMessages.NULL_ARGUMENT, "em");
    Validate.notNull(document, CannedMessages.NULL_ARGUMENT, "document");
    Validate.notNull(document.getStore(), CannedMessages.NULL_ARGUMENT, "document.store");
    Validate.notNull(document.getBaseDocument(), CannedMessages.NULL_ARGUMENT, "document.baseDocument");

    document.setSeen(true);

    if (document.getBaseDocument() instanceof FullTextDocument
            && document.getStore() instanceof LexiconBuilderDocumentStore) {
        List<LexiconDocument> seenTokens = this.getSeenTokens(em,
                (LexiconBuilderDocumentStore) document.getStore());
        FullTextDocument ftDoc = (FullTextDocument) document.getBaseDocument();
        for (final LinguisticToken token : ftDoc.getParsedContent().getTokens()) {
            if (seenTags != null && !token.getPosTag().is(seenTags)) {
                continue;
            }

            LexiconDocument seenToken = Iterables.find(seenTokens, new Predicate<LexiconDocument>() {
                @Override
                public boolean apply(LexiconDocument seenToken) {
                    return seenToken.getContent().equalsIgnoreCase(token.toString());
                }
            }, null);

            if (seenToken == null) {
                seenToken = (LexiconDocument) new LexiconDocument().setContent(token.toString())
                        .setStore(document.getStore());

                em.persist(seenToken);
            }
        }
    }

    if (em.contains(document)) {
        em.refresh(document);
    } else {
        em.persist(document);
    }

    return document;
}

From source file:org.tzi.use.uml.mm.MAssociationImpl.java

@Override
public MNavigableElement navigableEnd(final String rolename) {
    return Iterables.find(this.fAssociationEnds, new Predicate<MAssociationEnd>() {
        @Override//from ww w .j  ava 2s  . c  o  m
        public boolean apply(MAssociationEnd end) {
            return rolename.equals(end.name());
        }
    }, null);
}

From source file:org.sonar.server.issue.filter.IssueFilterService.java

@CheckForNull
private static IssueFilterDto findFilterWithSameName(List<IssueFilterDto> dtos, String name) {
    return Iterables.find(dtos, new IssueFilterDtoMatchName(name), null);
}

From source file:com.dianping.puma.taskexecutor.DefaultTaskExecutor.java

protected SrcDbEntity initSrcDbByServerId(final long binlogServerId) throws IOException {
    if (this.currentSrcDbEntity != null) {
        return this.currentSrcDbEntity;
    }/*from  w w  w  . jav a  2  s.co m*/

    List<SrcDbEntity> avaliableSrcDb = FluentIterable
            .from(instanceManager.getUrlByCluster(instanceTask.getInstance()))
            .filter(new Predicate<SrcDbEntity>() {
                @Override
                public boolean apply(SrcDbEntity input) {
                    return input.getServerId() > 0;
                }
            }).toList();

    if (avaliableSrcDb.size() == 0) {
        throw new IOException("No Avaliable SrcDB");
    }

    SrcDbEntity srcDbEntity = Iterables.find(avaliableSrcDb, new Predicate<SrcDbEntity>() {
        @Override
        public boolean apply(SrcDbEntity input) {
            return input.getServerId() == binlogServerId;
        }
    }, null);

    if (srcDbEntity != null) {
        return srcDbEntity;
    }

    srcDbEntity = Iterables.find(avaliableSrcDb, new Predicate<SrcDbEntity>() {
        @Override
        public boolean apply(SrcDbEntity input) {
            return input.getTags().contains(SrcDbEntity.TAG_WRITE);
        }
    }, null);

    if (srcDbEntity != null) {
        return srcDbEntity;
    }

    return avaliableSrcDb.get(0);
}

From source file:controllers.modules.SetCoverBuilder.java

@BodyParser.Of(play.mvc.BodyParser.Json.class)
public static Result update(final UUID corpus, UUID setcover) {
    DocumentCorpus corpusObj = null;/*www .j a va2s . c o m*/
    if (corpus != null) {
        corpusObj = fetchResource(corpus, DocumentCorpus.class);
    }

    // make sure we have the right combination.
    DocumentSetCover setCoverObj = null;
    if (setcover != null) {
        setCoverObj = fetchResource(setcover, DocumentSetCover.class);
        if (corpusObj == null) {
            corpusObj = setCoverObj.getBaseCorpus();
        } else if (ObjectUtils.notEqual(corpusObj, setCoverObj.getBaseCorpus())) {
            throw new IllegalArgumentException();
        }
    } else if (corpusObj == null) {
        throw new IllegalArgumentException();
    }

    JsonNode jsonBody = request().body().asJson();
    if (jsonBody == null && setcover != null) {
        throw new IllegalArgumentException();
    }
    if (jsonBody == null) {
        jsonBody = JsonNodeFactory.instance.objectNode();
    }

    DocumentSetCoverModel setCoverVM = null;
    setCoverVM = Json.fromJson(jsonBody, DocumentSetCoverModel.class);
    final SetCoverFactory factory = (SetCoverFactory) setCoverVM.toFactory().setOwnerId(getUsername());

    // set the default title.
    if (setcover == null && StringUtils.isEmpty(factory.getTitle())) {
        factory.setTitle("Optimized " + corpusObj.getTitle());
    }

    SetCoverFactory tmpFactory = (SetCoverFactory) new SetCoverFactory().setStore(corpusObj)
            .setTitle(factory.getTitle()).setDescription(factory.getDescription())
            .setOwnerId(factory.getOwnerId());

    // make basic creation/updation first.
    if (setcover == null) {
        setCoverObj = tmpFactory.create();
        em().persist(setCoverObj);
        setCoverVM = (DocumentSetCoverModel) createViewModel(setCoverObj);

        // if this is a simple change, just return from here.
        if (ObjectUtils.equals(
                ObjectUtils.defaultIfNull(factory.getTokenizingOptions(), new TokenizingOptions()),
                new TokenizingOptions())
                && factory.getWeightCoverage() == SetCoverFactory.DEFAULT_WEIGHT_COVERAGE) {
            return created(setCoverVM.asJson());
        }
        setcover = setCoverObj.getIdentifier();
    } else if (!StringUtils.equals(StringUtils.defaultString(tmpFactory.getTitle(), setCoverObj.getTitle()),
            setCoverObj.getTitle())
            || !StringUtils.equals(
                    StringUtils.defaultString(tmpFactory.getDescription(), setCoverObj.getDescription()),
                    setCoverObj.getDescription())) {

        tmpFactory.setEm(em()).setExistingId(setcover);
        setCoverObj = tmpFactory.create();
        em().merge(setCoverObj);
        setCoverVM = (DocumentSetCoverModel) createViewModel(setCoverObj);
        setCoverVM.populateSize(em(), setCoverObj);

        // if this is a simple change, just return from here.
        if (ObjectUtils.equals(
                ObjectUtils.defaultIfNull(factory.getTokenizingOptions(), new TokenizingOptions()),
                ObjectUtils.defaultIfNull(setCoverObj.getTokenizingOptions(), new TokenizingOptions()))
                && ObjectUtils.equals(factory.getWeightCoverage(), ObjectUtils.defaultIfNull(
                        setCoverObj.getWeightCoverage(), SetCoverFactory.DEFAULT_WEIGHT_COVERAGE))) {
            return ok(setCoverVM.asJson());
        }
    }

    // get rid of any old progress observer tokens and create a new one.
    finalizeProgress(setCoverObj.getId());
    createProgressObserverToken(setCoverObj.getId());
    watchProgress(factory, "create", setCoverObj.getId());

    final Context ctx = Context.current();
    final UUID setCoverId = setcover;

    Akka.future(new Callable<DocumentSetCover>() {
        @Override
        public DocumentSetCover call() throws Exception {
            try {
                return execute(new SareTxRunnable<DocumentSetCover>() {
                    @Override
                    public DocumentSetCover run(EntityManager em) throws Throwable {
                        bindEntityManager(em);
                        Context.current.set(ctx);

                        DocumentSetCover setCoverObj = null;
                        UUID corpusId = corpus;
                        if (corpusId == null) {
                            setCoverObj = fetchResource(setCoverId, DocumentSetCover.class);
                            corpusId = setCoverObj.getBaseCorpus().getIdentifier();
                        }

                        factory.setStore(fetchResource(corpusId, DocumentCorpus.class))
                                .setExistingId(setCoverId).setEm(em);

                        List<SetCoverDocument> oldDocuments = Lists.newArrayList(setCoverObj.getAllDocuments());
                        setCoverObj = factory.create();

                        em.flush();
                        em.merge(setCoverObj);
                        em.getTransaction().commit();
                        em.clear();

                        em.getTransaction().begin();
                        for (SetCoverDocument oldDocument : oldDocuments) {
                            if (Iterables.find(setCoverObj.getAllDocuments(), Predicates.equalTo(oldDocument),
                                    null) == null) {
                                SetCoverDocument tmpDocument = em.find(SetCoverDocument.class,
                                        oldDocument.getId());
                                em.remove(tmpDocument);
                            }
                        }

                        return setCoverObj;
                    }
                }, ctx);
            } catch (Throwable e) {
                Logger.error(LoggedAction.getLogEntry(ctx, "failed to build set cover"), e);
                throw new IllegalArgumentException(e);
            } finally {
                setProgressFinished(UuidUtils.toBytes(setCoverId));
            }
        }
    });

    return ok(setCoverVM.asJson());
}

From source file:org.jfrog.build.api.builder.BuildInfoMavenBuilder.java

private Dependency findDependency(List<Dependency> existingDependencies, final String dependencyId) {
    return Iterables.find(existingDependencies, new Predicate<Dependency>() {
        public boolean apply(Dependency input) {
            return input.getId().equals(dependencyId);
        }//from   www .ja va2s  .  c  o  m
    }, null);
}

From source file:org.sonar.server.issue.filter.IssueFilterService.java

@CheckForNull
private IssueFilterFavouriteDto selectFavouriteFilterForUser(Long filterId, final String user) {
    return Iterables.find(selectFavouriteFilters(filterId), new IssueFilterFavouriteDtoMatchUser(user), null);
}