Example usage for com.google.common.collect Iterables filter

List of usage examples for com.google.common.collect Iterables filter

Introduction

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

Prototype

@GwtIncompatible("Class.isInstance")
@CheckReturnValue
public static <T> Iterable<T> filter(final Iterable<?> unfiltered, final Class<T> desiredType) 

Source Link

Document

Returns all elements in unfiltered that are of the type desiredType .

Usage

From source file:com.google.devtools.kythe.extractors.java.bazel.JavaExtractor.java

public static void main(String[] args) throws IOException, ExtractionException {
    if (args.length != 3) {
        System.err.println("Usage: java_extractor extra-action-file output-file vname-config");
        System.exit(1);/*w w  w  .  j  a  va2s.c  o  m*/
    }

    String extraActionPath = args[0];
    String outputPath = args[1];
    String vNamesConfigPath = args[2];

    ExtensionRegistry registry = ExtensionRegistry.newInstance();
    ExtraActionsBase.registerAllExtensions(registry);

    ExtraActionInfo info;
    try (InputStream stream = Files.newInputStream(Paths.get(extraActionPath))) {
        CodedInputStream coded = CodedInputStream.newInstance(stream);
        info = ExtraActionInfo.parseFrom(coded, registry);
    }

    if (!info.hasExtension(JavaCompileInfo.javaCompileInfo)) {
        throw new IllegalArgumentException("Given ExtraActionInfo without JavaCompileInfo");
    }

    JavaCompileInfo jInfo = info.getExtension(JavaCompileInfo.javaCompileInfo);

    List<String> javacOpts = Lists.newArrayList(Iterables.filter(jInfo.getJavacOptList(), JAVAC_OPT_FILTER));

    // Set up a fresh output directory
    javacOpts.add("-d");
    Path output = Files.createTempDirectory("output");
    javacOpts.add(output.toString());

    // Add the generated sources directory if any processors could be invoked.
    if (!jInfo.getProcessorList().isEmpty()) {
        String gensrcdir = readGeneratedSourceDirParam(jInfo);
        if (gensrcdir != null) {
            javacOpts.add("-s");
            javacOpts.add(gensrcdir);
            // javac expects the directory to already exist.
            Files.createDirectories(Paths.get(gensrcdir));
        }
    }

    CompilationDescription description = new JavaCompilationUnitExtractor(FileVNames.fromFile(vNamesConfigPath),
            System.getProperty("user.dir")).extract(info.getOwner(), jInfo.getSourceFileList(),
                    jInfo.getClasspathList(), jInfo.getSourcepathList(), jInfo.getProcessorpathList(),
                    jInfo.getProcessorList(), javacOpts, jInfo.getOutputjar());

    IndexInfoUtils.writeIndexInfoToFile(description, outputPath);
}

From source file:Dictconvert_with_elements.java

public static void main(String args[]) throws Exception {

    String targetNameSpace = args[1];
    String targetNameSpaceVar = args[2];

    Map<String, String> namespaces = ImmutableMap.<String, String>of(targetNameSpace, targetNameSpaceVar);

    HashMap<String, String> keys = new HashMap<String, String>();
    DocumentBuilderFactory builderF = DocumentBuilderFactory.newInstance();
    builderF.setNamespaceAware(true);/*  w  ww .  j  a  v  a2  s. c om*/

    DocumentBuilder builder = builderF.newDocumentBuilder();
    Document xmlDictionary = builder.parse(args[0]);

    for (Map.Entry<String, String> e : namespaces.entrySet()) {
        System.out.println("XMLCh " + e.getValue() + "[] = {" + Joiner.on(",")
                .join(Iterables.transform(Lists.charactersOf(e.getKey()), new Function<Character, String>() {
                    public String apply(Character o) {
                        return "\'" + o + "\'";
                    }
                })) + ",\'\\0\'};");
    }

    Map<String, String> localKeys = new HashMap<String, String>();

    for (Element e : Iterables.filter(getElements(xmlDictionary.getDocumentElement()),
            new Predicate<Element>() {
                public boolean apply(Element element) {
                    return element.getAttribute("type").equals("localSet");
                }
            })) {
        String name = e.getLocalName();
        String keyName = "key_" + Joiner.on("").join(e.getAttribute("key").split("\\s"));
        localKeys.put(keyName, keyName + "_name");

        System.out.println("mxfKey " + keyName + " = {" + Joiner.on(",").join(Iterables
                .transform(Arrays.asList(e.getAttribute("key").split("\\s")), new Function<String, String>() {
                    public String apply(String o) {
                        return "0x" + o;
                    }
                })) + "};");
        System.out.println("XMLCh " + keyName + "_name[] = {" + Joiner.on(",")
                .join(Iterables.transform(Lists.charactersOf(name), new Function<Character, String>() {
                    public String apply(Character o) {
                        return "\'" + o + "\'";
                    }
                })) + ",\'\\0\'};");

        //System.out.println("st434dict.insert(std::pair<mxfKey, st434info*>(");
        //System.out.println('\t' + keyName + ',');
        //System.out.println("\tnew st434info(/* " + name + " */ " + keyName + "_name, /* " + targetNameSpace + " */ " + namespaces.get(targetNameSpace) + ")");
        //System.out.println("));");

        for (Element ee : getElements(e)) {

            String elemKeyName = "key_" + Joiner.on("").join(ee.getAttribute("globalKey").split("\\s"));
            localKeys.put(elemKeyName, elemKeyName + "_name");

            System.out.println("mxfKey " + elemKeyName + " = {" + Joiner.on(",").join(Iterables.transform(
                    Arrays.asList(ee.getAttribute("globalKey").split("\\s")), new Function<String, String>() {
                        public String apply(String o) {
                            return "0x" + o;
                        }
                    })) + "};");
            System.out.println("XMLCh " + elemKeyName + "_name[] = {" + Joiner.on(",").join(Iterables
                    .transform(Lists.charactersOf(ee.getLocalName()), new Function<Character, String>() {
                        public String apply(Character o) {
                            return "\'" + o + "\'";
                        }
                    })) + ",\'\\0\'};");

            //System.out.println("st434dict.insert(std::pair<mxfKey, st434info*>(");
            //System.out.println('\t' + elemKeyName + ',');
            //System.out.println("\tnew st434info(/* " + ee.getLocalName() + " */ " + elemKeyName + "_name, /* " + targetNameSpace + " */ " + namespaces.get(targetNameSpace) + ")");
            //System.out.println("));");
        }

    }

    if (localKeys.size() > 0) {
        String arrayName = "arr_" + targetNameSpaceVar;
        System.out.println("const void* " + arrayName + "[][2] = {");

        System.out.println(Joiner.on(", \n").join(
                Iterables.transform(localKeys.entrySet(), new Function<Map.Entry<String, String>, String>() {
                    @Override
                    public String apply(java.util.Map.Entry<String, String> e) {
                        return "{ &" + e.getKey() + ", " + e.getValue() + " }";
                    }
                })));
        System.out.println("};");

        System.out.println("for (int i=0; i<" + localKeys.size() + ";i++) {");
        System.out.println("\tst434dict.insert(std::pair<const mxfKey, st434info*>(");
        System.out.println("\t*(const mxfKey*)" + arrayName + "[i][0], ");
        System.out
                .println("\tnew st434info((const XMLCh*)" + arrayName + "[i][1], " + targetNameSpaceVar + ")");
        System.out.println("));");
        System.out.println("}");
    }

}

From source file:Dictconvert.java

public static void main(String args[]) throws Exception {

    final ImmutableMap<String, String> nameMap = new ImmutableMap.Builder<String, String>()
            .put("ebucoreMainFramework", "ebucoreMainFramework")
            .put("ebucorePartFramework", "ebucorePartFramework")
            .put("ebucoreMetadataSchemeInformation", "ebucoreMetadataSchemeInformation")
            /* List mainly generated using AWK:
               awk '{t=$2; gsub(/ebucore/, "", t); print "\x27"$2"\x27:\x27" tolower(substr(t, 1, 1))substr(t, 2)"\x27," }' < tmp.txt > tmpout.txt
            *//*from   w w  w .j a  v  a  2 s. c  o  m*/
            .put("ebucoreEntity", "entity").put("ebucoreContact", "contact")
            .put("ebucoreContactDetails", "details").put("ebucoreAddress", "address")
            .put("ebucoreRegion", "region").put("ebucoreCompoundName", "compoundName")
            .put("ebucoreRole", "role").put("ebucoreCountry", "country")
            .put("ebucoreTextualAnnotation", "textualAnnotation").put("ebucoreBasicLink", "basicLink")
            .put("ebucoreTypeGroup", "typeGroup").put("ebucoreOrganisation", "organisation")
            .put("ebucoreOrganisationDepartment", "organisationDepartment")
            .put("ebucoreCoreMetadata", "coreMetadata").put("ebucoreIdentifier", "identifier")
            .put("ebucoreTitle", "title").put("ebucoreAlternativeTitle", "alternativeTitle")
            .put("ebucoreFormatGroup", "formatGroup").put("ebucoreStatusGroup", "statusGroup")
            .put("ebucoreSubject", "subject").put("ebucoreDescription", "description")
            .put("ebucoreDate", "date").put("ebucoreDateType", "dateType").put("ebucoreType", "type")
            .put("ebucoreObjectType", "objectType").put("ebucoreGenre", "genre")
            .put("ebucoreTargetAudience", "targetAudience").put("ebucoreLanguage", "language")
            .put("ebucoreCoverage", "coverage").put("ebucoreSpatial", "spatial")
            .put("ebucoreLocation", "location").put("ebucoreCoordinates", "coordinates")
            .put("ebucoreTemporal", "temporal").put("ebucorePeriodOfTime", "periodOfTime")
            .put("ebucoreRights", "rights").put("ebucoreVersion", "version").put("ebucoreRating", "rating")
            .put("ebucorePublicationHistoryEvent", "publicationHistoryEvent")
            .put("ebucorePublicationHistory", "publicationHistory")
            .put("ebucorePublicationChannel", "publicationChannel")
            .put("ebucorePublicationMedium", "publicationMedium")
            .put("ebucorePublicationService", "publicationService")
            .put("ebucoreCustomRelation", "customRelation").put("ebucoreBasicRelation", "basicRelation")
            .put("ebucorePartMetadata", "partMetadata").put("ebucoreFormat", "format")
            .put("ebucoreVideoFormat", "videoFormat").put("ebucoreImageFormat", "imageFormat")
            .put("ebucoreAudioFormat", "audioFormat").put("ebucoreTrack", "track")
            .put("ebucoreDataFormat", "dataFormat").put("ebucoreCaptioning", "captioning")
            .put("ebucoreSubtitling", "subtitling").put("ebucoreAncillaryData", "ancillaryData")
            .put("ebucoreSigningFormat", "signingFormat")
            .put("ebucoreTechnicalAttributeString", "technicalAttributeString")
            .put("ebucoreTechnicalAttributeInt8", "technicalAttributeInt8")
            .put("ebucoreTechnicalAttributeInt16", "technicalAttributeInt16")
            .put("ebucoreTechnicalAttributeInt32", "technicalAttributeInt32")
            .put("ebucoreTechnicalAttributeInt64", "technicalAttributeInt64")
            .put("ebucoreTechnicalAttributeUInt8", "technicalAttributeUInt8")
            .put("ebucoreTechnicalAttributeUInt16", "technicalAttributeUInt16")
            .put("ebucoreTechnicalAttributeUInt32", "technicalAttributeUInt32")
            .put("ebucoreTechnicalAttributeUInt64", "technicalAttributeUInt64")
            .put("ebucoreTechnicalAttributeFloat", "technicalAttributeFloat")
            .put("ebucoreTechnicalAttributeRational", "technicalAttributeRational")
            .put("ebucoreTechnicalAttributeAnyURI", "technicalAttributeAnyURI")
            .put("ebucoreTechnicalAttributeBoolean", "technicalAttributeBoolean")
            .put("ebucoreDimension", "dimension").put("ebucoreWidth", "width").put("ebucoreHeight", "height")
            .put("ebucorePackageInfo", "packageInfo").put("ebucoreMedium", "medium")
            .put("ebucoreCodec", "codec").put("ebucoreRational", "rational")
            .put("ebucoreAspectRatio", "aspectRatio").build();

    String key_ns_ebucore_1 = "urn:ebu:metadata-schema:smpteclass13/groups/ebucore_2013";
    Map<String, String> namespaces = ImmutableMap.<String, String>of(key_ns_ebucore_1, "key_ns_ebucore_1");

    HashMap<String, String> keys = new HashMap<String, String>();
    DocumentBuilderFactory builderF = DocumentBuilderFactory.newInstance();
    builderF.setNamespaceAware(true);

    DocumentBuilder builder = builderF.newDocumentBuilder();
    Document xmlDictionary = builder.parse(args[0]);

    Map<String, String> localKeys = new HashMap<String, String>();

    for (Map.Entry<String, String> e : namespaces.entrySet()) {
        System.out.println("XMLCh " + e.getValue() + "[] = {" + Joiner.on(",")
                .join(Iterables.transform(Lists.charactersOf(e.getKey()), new Function<Character, String>() {
                    public String apply(Character o) {
                        return "\'" + o + "\'";
                    }
                })) + ",\'\\0\'};");
    }

    for (Element e : Iterables.filter(getElements(xmlDictionary.getDocumentElement()),
            new Predicate<Element>() {
                public boolean apply(Element element) {
                    return element.getAttribute("type").equals("localSet");
                }
            })) {
        String name = nameMap.get(e.getLocalName());
        String keyName = "key_" + Joiner.on("").join(e.getAttribute("key").split("\\s"));

        localKeys.put(keyName, keyName + "_name");

        System.out.println("const mxfKey " + keyName + " = {" + Joiner.on(",").join(Iterables
                .transform(Arrays.asList(e.getAttribute("key").split("\\s")), new Function<String, String>() {
                    public String apply(String o) {
                        return "0x" + o;
                    }
                })) + "};");
        System.out.println("const XMLCh " + keyName + "_name[] = {" + Joiner.on(",")
                .join(Iterables.transform(Lists.charactersOf(name), new Function<Character, String>() {
                    public String apply(Character o) {
                        return "\'" + o + "\'";
                    }
                })) + ",\'\\0\'};");

        //System.out.println("st434dict.insert(std::pair<const mxfKey, st434info*>(");
        //System.out.println('\t' + keyName + ',');
        //System.out.println("\tnew st434info(/* " + e.getLocalName() + " */ " + keyName + "_name, /* " + key_ns_ebucore_1 + " */ " + namespaces.get(key_ns_ebucore_1) + ")");
        //System.out.println("));");

    }

    if (localKeys.size() > 0) {
        String arrayName = "arr_ebucore_elems";
        System.out.println("const void* " + arrayName + "[][2] = {");

        System.out.println(Joiner.on(", \n").join(
                Iterables.transform(localKeys.entrySet(), new Function<Map.Entry<String, String>, String>() {
                    @Override
                    public String apply(java.util.Map.Entry<String, String> e) {
                        return "{ &" + e.getKey() + ", " + e.getValue() + " }";
                    }
                })));
        System.out.println("};");

        System.out.println("for (int i=0; i<" + localKeys.size() + ";i++) {");
        System.out.println("\tst434dict.insert(std::pair<const mxfKey, st434info*>(");
        System.out.println("\t*(const mxfKey*)" + arrayName + "[i][0], ");
        System.out.println("\tnew st434info((const XMLCh*)" + arrayName + "[i][1], key_ns_ebucore_1)");
        System.out.println("));");
        System.out.println("}");
    }

}

From source file:com.opengamma.language.object.BeanUtils.java

public static Iterable<MetaProperty<?>> writableMetaProperties(MetaBean metaBean) {
    return Iterables.filter(metaBean.metaPropertyIterable(), new Predicate<MetaProperty<?>>() {
        @Override/*  www .  j a va2s .  com*/
        public boolean apply(MetaProperty<?> property) {
            return property.readWrite().isWritable();
        }
    });
}

From source file:eu.itesla_project.iidm.network.impl.Substations.java

static Iterable<Substation> filter(Iterable<Substation> substations, final Country country, final String tso,
        final String... geographicalTags) {
    if (geographicalTags.length == 0) {
        return substations;
    }//w  w  w.  j a  v a2  s.  c om
    return Iterables.filter(substations, new Predicate<Substation>() {
        @Override
        public boolean apply(Substation substation) {
            if (country != null && country == substation.getCountry()) {
                return false;
            }
            if (tso != null && !tso.equals(substation.getTso())) {
                return false;
            }
            for (String tag : geographicalTags) {
                if (!substation.getGeographicalTags().contains(tag)) {
                    return false;
                }
            }
            return true;
        }
    });
}

From source file:org.robotframework.red.viewers.Selections.java

@SuppressWarnings("unchecked")
public static <T> T[] getElementsArray(final IStructuredSelection selection, final Class<T> elementsClass) {
    final List<?> selectionAsList = selection.toList();
    return newArrayList(Iterables.filter(selectionAsList, elementsClass))
            .toArray((T[]) Array.newInstance(elementsClass, 0));
}

From source file:io.sidecar.util.CollectionUtils.java

public static <T> ImmutableList<T> filterNulls(List<T> orig) {
    if (orig == null) {
        return ImmutableList.of();
    }/*from w  w  w . ja  va  2  s  .co m*/
    return ImmutableList.copyOf(Iterables.filter(orig, new Predicate<T>() {
        @Override
        public boolean apply(T t) {
            return t != null;
        }
    }));
}

From source file:org.zalando.crypto.Decrypters.java

public static List<Decrypter> prefixedDecrypters(List<Decrypter> toFilter) {
    return Lists.newArrayList(Iterables.filter(toFilter, new PrefixedDecrypterPredicate()));
}

From source file:com.datastax.driver.core.DataProviders.java

/**
 * @return A DataProvider that provides all non-serial consistency levels
 *//*w ww .  j a va  2  s  .c  o  m*/
@DataProvider(name = "consistencyLevels")
public static Iterator<Object[]> consistencyLevels() {
    final Iterator<ConsistencyLevel> consistencyLevels = Iterables
            .filter(Arrays.asList(ConsistencyLevel.values()), new Predicate<ConsistencyLevel>() {
                @Override
                public boolean apply(ConsistencyLevel input) {
                    // filter out serial CLs.
                    return !input.isSerial();
                }
            }).iterator();

    return new Iterator<Object[]>() {

        @Override
        public boolean hasNext() {
            return consistencyLevels.hasNext();
        }

        @Override
        public Object[] next() {
            return new Object[] { consistencyLevels.next() };
        }

        @Override
        public void remove() {
            throw new UnsupportedOperationException("This shouldn't happen..");
        }
    };
}

From source file:org.apache.cassandra.concurrent.Stage.java

public static Iterable<Stage> jmxEnabledStages() {
    return Iterables.filter(Arrays.asList(values()), new Predicate<Stage>() {
        public boolean apply(Stage stage) {
            return stage != TRACING;
        }/*from w w  w .  j  av a2s  . c o  m*/
    });
}