Example usage for com.google.common.collect Iterators find

List of usage examples for com.google.common.collect Iterators find

Introduction

In this page you can find the example usage for com.google.common.collect Iterators find.

Prototype

public static <T> T find(Iterator<T> iterator, Predicate<? super T> predicate) 

Source Link

Document

Returns the first element in iterator that satisfies the given predicate; use this method only when such an element is known to exist.

Usage

From source file:org.eclipse.emf.eson.tests.util.Find.java

public static <T> T child(final Class<T> candidateClass, final String candidateName, EObject rootObject) {
    final TreeIterator<EObject> contents = rootObject.eAllContents();
    //      if (!contents.hasNext()) {
    //         throw new IllegalArgumentException();
    //      }//from w  w  w .jav a 2s .c  om
    EObject result = Iterators.find(contents, new Predicate<EObject>() {

        public boolean apply(EObject input) {
            return candidateClass.isInstance(input) && (candidateName == null
                    || candidateName.equals(SimpleAttributeResolver.NAME_RESOLVER.apply(input)));
        }
    });
    return candidateClass.cast(result);
}

From source file:com.googlecode.efactory.util.Find.java

public static <T> T child(final Class<T> candidateClass, final String candidateName, EObject rootObject) {
    EObject result = Iterators.find(rootObject.eAllContents(), new Predicate<EObject>() {

        public boolean apply(EObject input) {
            return candidateClass.isInstance(input) && candidateName
                    .equals(org.eclipse.xtext.util.SimpleAttributeResolver.NAME_RESOLVER.apply(input));
        }/*from  ww w  .j  a  v a 2  s  . c o  m*/
    });
    return candidateClass.cast(result);
}

From source file:org.sonar.db.dialect.DialectUtils.java

@CheckForNull
private static Dialect findDialect(Predicate<Dialect> predicate) {
    try {//  w ww .  j  av  a  2  s.com
        return Iterators.find(Iterators.forArray(DIALECTS), predicate);
    } catch (NoSuchElementException ex) {
        return null;
    }
}

From source file:org.sonar.core.persistence.dialect.DialectUtils.java

private static Dialect findDialect(Predicate<Dialect> predicate) {
    try {//  w ww .  j  a  v  a2 s.co m
        return Iterators.find(Iterators.forArray(DIALECTS), predicate);
    } catch (NoSuchElementException ex) {
        return null;
    }
}

From source file:org.sonar.jpa.dialect.DialectRepository.java

private static Dialect findDialect(Collection<Dialect> dialects, Predicate<Dialect> predicate) {
    try {/*from ww  w .  j av  a 2  s .c  o  m*/
        return Iterators.find(dialects.iterator(), predicate);
    } catch (NoSuchElementException ex) {
        return null;
    }
}

From source file:org.eclipse.incquery.patternlanguage.emf.ui.contentassist.PatternImporter.java

@Override
public void apply(final IDocument document, final ConfigurableCompletionProposal proposal)
        throws BadLocationException {
    if (document instanceof IXtextDocument) {
        IXtextDocument xtextDocument = (IXtextDocument) document;
        if (targetPattern == null || Strings.isNullOrEmpty(targetPattern.getName()))
            return;
        importStatus = ((IXtextDocument) document).readOnly(new IUnitOfWork<ImportState, XtextResource>() {

            @Override//from  w  w  w .  j a  v  a2  s .c  o m
            public ImportState exec(XtextResource state) throws Exception {
                final PatternModel model = (PatternModel) Iterators.find(state.getAllContents(),
                        Predicates.instanceOf(PatternModel.class));
                if (targetPackage.equals(model.getPackageName())) {
                    return ImportState.SAMEPACKAGE;
                }
                final XImportSection importSection = model.getImportPackages();
                PatternImport relatedImport = Iterables.find(importSection.getPatternImport(),
                        new Predicate<PatternImport>() {

                            @Override
                            public boolean apply(PatternImport decl) {
                                return targetPattern.equals(decl.getPattern())
                                        || targetPattern.getName().equals(decl.getPattern().getName());
                            }
                        }, null);
                if (relatedImport == null) {

                    return ImportState.NONE;
                }
                // Checking whether found pattern definition equals to different pattern
                if (targetPattern.equals(relatedImport.getPattern())) {
                    return ImportState.FOUND;
                } else {
                    return ImportState.CONFLICTING;
                }
            }
        });

        String replacementString = getActualReplacementString(proposal) + "();";
        ReplaceEdit edit = new ReplaceEdit(proposal.getReplacementOffset(), proposal.getReplacementLength(),
                replacementString);
        edit.apply(document);
        //+2 is used to put the cursor inside the parentheses
        int cursorOffset = getActualReplacementString(proposal).length() + 2;
        if (importStatus == ImportState.NONE) {
            xtextDocument.modify(new Void<XtextResource>() {

                @Override
                public void process(XtextResource state) throws Exception {
                    XImportSection importSection = (XImportSection) Iterators.find(state.getAllContents(),
                            Predicates.instanceOf(XImportSection.class), null);
                    if (importSection.getImportDeclarations().size() + importSection.getPackageImport().size()
                            + importSection.getPatternImport().size() == 0) {
                        //Empty import sections need to be replaced to generate white space after the package declaration
                        XImportSection newSection = EMFPatternLanguageFactory.eINSTANCE.createXImportSection();
                        ((PatternModel) importSection.eContainer()).setImportPackages(newSection);
                        importSection = newSection;
                    }
                    PatternImport newImport = EMFPatternLanguageFactory.eINSTANCE.createPatternImport();
                    newImport.setPattern(targetPattern);
                    importSection.getPatternImport().add(newImport);

                }
            });
            //Two new lines + "import " + pattern fqn
            cursorOffset += 2 + 7 + CorePatternLanguageHelper.getFullyQualifiedName(targetPattern).length();
        }
        proposal.setCursorPosition(cursorOffset);
    }
}

From source file:org.eclipse.viatra.query.patternlanguage.emf.ui.builder.OldVersionHelper.java

private URI getCopiedURI(IProject project, IPath relativePath) throws JavaModelException {
    try {//  www.  j  a  v  a 2s .  c o m
        if (!copiedURIMap.containsKey(relativePath)) {
            IJavaProject javaProject = JavaCore.create(project);
            IClasspathEntry sourceEntry = Iterators.find(
                    Iterators.forArray(javaProject.getResolvedClasspath(true)),
                    new SourceFolderFinder(relativePath));
            IPath outputLocation = sourceEntry.getOutputLocation();
            if (outputLocation == null) {
                outputLocation = javaProject.getOutputLocation();
            }
            IPath path = outputLocation.append(relativePath.makeRelativeTo(sourceEntry.getPath()));
            URI copiedURI = (project.getWorkspace().getRoot().findMember(path) != null)
                    ? URI.createPlatformResourceURI(path.toString(), true)
                    : null;
            if (copiedURI != null) {
                copiedURIMap.put(relativePath, copiedURI);
            }
            return copiedURI;
        }
        return copiedURIMap.get(relativePath);
    } catch (NoSuchElementException e) {
        return null;
    }
}

From source file:org.geoserver.importer.mosaic.MosaicIndex.java

public void write() throws IOException {
    //delete if already exists
    delete();/* www .  ja v a  2s . co m*/

    Collection<Granule> granules = mosaic.granules();
    if (granules.isEmpty()) {
        LOGGER.warning("No granules in mosaic, nothing to write");
        return;
    }

    Granule first = Iterators.find(granules.iterator(), new Predicate<Granule>() {
        @Override
        public boolean apply(Granule input) {
            return input.getEnvelope() != null && input.getEnvelope().getCoordinateReferenceSystem() != null;
        }
    });
    if (first == null) {
        throw new IOException("Unable to determine CRS for mosaic");
    }

    Envelope2D envelope = new Envelope2D(first.getEnvelope());

    //create index schema
    SimpleFeatureTypeBuilder typeBuilder = new SimpleFeatureTypeBuilder();
    typeBuilder.setName(mosaic.getName());
    typeBuilder.setCRS(envelope.getCoordinateReferenceSystem());
    typeBuilder.add("the_geom", Polygon.class);
    typeBuilder.add("location", String.class);

    if (mosaic.getTimeMode() != TimeMode.NONE) {
        typeBuilder.add("time", Date.class);
    }

    //create a new shapefile feature store
    ShapefileDataStoreFactory shpFactory = new ShapefileDataStoreFactory();
    DirectoryDataStore dir = new DirectoryDataStore(mosaic.getFile(),
            new ShapefileDataStoreFactory.ShpFileStoreFactory(shpFactory, new HashMap()));

    try {
        dir.createSchema(typeBuilder.buildFeatureType());

        FeatureWriter<SimpleFeatureType, SimpleFeature> w = dir.getFeatureWriterAppend(mosaic.getName(),
                Transaction.AUTO_COMMIT);

        try {
            for (Granule g : mosaic.granules()) {
                if (g.getEnvelope() == null) {
                    LOGGER.warning("Skipping " + g.getFile().getAbsolutePath() + ", no envelope");
                }

                SimpleFeature f = w.next();
                f.setDefaultGeometry(JTS.toGeometry((BoundingBox) g.getEnvelope()));
                f.setAttribute("location", g.getFile().getName());
                if (mosaic.getTimeMode() != TimeMode.NONE) {
                    f.setAttribute("time", g.getTimestamp());
                }
                w.write();

                //track total bounds
                envelope.include(g.getEnvelope());
            }

        } finally {
            w.close();
        }
    } finally {
        dir.dispose();
    }

    double width = first.getGrid().getGridRange2D().getWidth();
    double height = first.getGrid().getGridRange2D().getHeight();

    //write out the properties file
    Properties props = new Properties();
    props.setProperty("Name", mosaic.getName());
    props.setProperty("Levels", String.format("%f,%f", first.getEnvelope().getWidth() / width,
            first.getEnvelope().getHeight() / height));
    props.setProperty("LevelsNum", "1");
    props.setProperty("LocationAttribute", "location");

    if (mosaic.getTimeMode() != TimeMode.NONE) {
        props.setProperty("TimeAttribute", "time");
    }

    FileOutputStream fout = new FileOutputStream(new File(mosaic.getFile(), mosaic.getName() + ".properties"));
    try {
        props.store(fout, null);
        fout.flush();
    } finally {
        fout.close();
    }
}

From source file:org.eclipse.viatra.query.patternlanguage.emf.ui.contentassist.PatternImporter.java

@Override
public void apply(final IDocument document, final ConfigurableCompletionProposal proposal)
        throws BadLocationException {
    if (document instanceof IXtextDocument) {
        IXtextDocument xtextDocument = (IXtextDocument) document;
        targetPattern = getTargetPattern(proposal);
        if (targetPattern == null || Strings.isNullOrEmpty(targetPattern.getName()))
            return;
        final String targetPackage = PatternLanguageHelper.getPackageName(targetPattern);
        importStatus = ((IXtextDocument) document).readOnly(new IUnitOfWork<ImportState, XtextResource>() {

            @Override/*from  www. j av  a2s . c  om*/
            public ImportState exec(XtextResource state) throws Exception {
                final PatternModel model = (PatternModel) Iterators.find(state.getAllContents(),
                        Predicates.instanceOf(PatternModel.class));
                if (Objects.equals(targetPackage, model.getPackageName())) {
                    return ImportState.SAMEPACKAGE;
                }
                final VQLImportSection importSection = model.getImportPackages();
                PatternImport relatedImport = importSection.getPatternImport().stream()
                        .filter(decl -> targetPattern.equals(decl.getPattern())
                                || targetPattern.getName().equals(decl.getPattern().getName()))
                        .findFirst().orElse(null);
                if (relatedImport == null) {

                    return ImportState.NONE;
                }
                // Checking whether found pattern definition equals to different pattern
                if (targetPattern.equals(relatedImport.getPattern())) {
                    return ImportState.FOUND;
                } else {
                    return ImportState.CONFLICTING;
                }
            }
        });

        String replacementString = getActualReplacementString(proposal) + "();";
        ReplaceEdit edit = new ReplaceEdit(proposal.getReplacementOffset(), proposal.getReplacementLength(),
                replacementString);
        edit.apply(document);
        //+2 is used to put the cursor inside the parentheses
        int cursorOffset = getActualReplacementString(proposal).length() + 2;
        if (importStatus == ImportState.NONE) {
            xtextDocument.modify(new Void<XtextResource>() {

                @Override
                public void process(XtextResource state) throws Exception {
                    VQLImportSection importSection = (VQLImportSection) Iterators.find(state.getAllContents(),
                            Predicates.instanceOf(VQLImportSection.class), null);
                    if (importSection.getImportDeclarations().size() + importSection.getPackageImport().size()
                            + importSection.getPatternImport().size() == 0) {
                        //Empty import sections need to be replaced to generate white space after the package declaration
                        VQLImportSection newSection = PatternLanguageFactory.eINSTANCE.createVQLImportSection();
                        ((PatternModel) importSection.eContainer()).setImportPackages(newSection);
                        importSection = newSection;
                    }
                    PatternImport newImport = PatternLanguageFactory.eINSTANCE.createPatternImport();
                    newImport.setPattern(targetPattern);
                    importSection.getPatternImport().add(newImport);

                }
            });
            //Two new lines + "import " + pattern fqn
            cursorOffset += 2 + 7 + PatternLanguageHelper.getFullyQualifiedName(targetPattern).length();
        }
        proposal.setCursorPosition(cursorOffset);
    }
}

From source file:de.griffel.confluence.plugins.plantuml.PlantUmlMacroParams.java

public DiagramType getDiagramType() {
    /* final */DiagramType result;
    try {//from ww w .  j  av a  2 s  .  c  om
        final String type = get(Param.type);
        result = Iterators.find(Iterators.forArray(DiagramType.values()), new Predicate<DiagramType>() {
            public boolean apply(DiagramType diagramType) {
                return diagramType.name().equalsIgnoreCase(type);
            }
        });
    } catch (NoSuchElementException e) {
        result = DiagramType.UML; /* default type */
    }
    return result;
}