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

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

Introduction

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

Prototype

public static <T> Iterable<T> concat(Iterable<? extends T> a, Iterable<? extends T> b,
        Iterable<? extends T> c) 

Source Link

Document

Combines three iterables into a single iterable.

Usage

From source file:io.druid.server.sql.SQLRunner.java

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

    Options options = new Options();
    options.addOption("h", "help", false, "help");
    options.addOption("v", false, "verbose");
    options.addOption("e", "host", true, "endpoint [hostname:port]");

    CommandLine cmd = new GnuParser().parse(options, args);

    if (cmd.hasOption("h")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("SQLRunner", options);
        System.exit(2);//from w ww  .  j av a  2 s  .c  o  m
    }

    String hostname = cmd.getOptionValue("e", "localhost:8080");
    String sql = cmd.getArgs().length > 0 ? cmd.getArgs()[0] : STATEMENT;

    ObjectMapper objectMapper = new DefaultObjectMapper();
    ObjectWriter jsonWriter = objectMapper.writerWithDefaultPrettyPrinter();

    CharStream stream = new ANTLRInputStream(sql);
    DruidSQLLexer lexer = new DruidSQLLexer(stream);
    TokenStream tokenStream = new CommonTokenStream(lexer);
    DruidSQLParser parser = new DruidSQLParser(tokenStream);
    lexer.removeErrorListeners();
    parser.removeErrorListeners();

    lexer.addErrorListener(ConsoleErrorListener.INSTANCE);
    parser.addErrorListener(ConsoleErrorListener.INSTANCE);

    try {
        DruidSQLParser.QueryContext queryContext = parser.query();
        if (parser.getNumberOfSyntaxErrors() > 0)
            throw new IllegalStateException();
        //      parser.setBuildParseTree(true);
        //      System.err.println(q.toStringTree(parser));
    } catch (Exception e) {
        String msg = e.getMessage();
        if (msg != null)
            System.err.println(e);
        System.exit(1);
    }

    final Query query;
    final TypeReference typeRef;
    boolean groupBy = false;
    if (parser.groupByDimensions.isEmpty()) {
        query = Druids.newTimeseriesQueryBuilder().dataSource(parser.getDataSource())
                .aggregators(new ArrayList<AggregatorFactory>(parser.aggregators.values()))
                .postAggregators(parser.postAggregators).intervals(parser.intervals)
                .granularity(parser.granularity).filters(parser.filter).build();

        typeRef = new TypeReference<List<Result<TimeseriesResultValue>>>() {
        };
    } else {
        query = GroupByQuery.builder().setDataSource(parser.getDataSource())
                .setAggregatorSpecs(new ArrayList<AggregatorFactory>(parser.aggregators.values()))
                .setPostAggregatorSpecs(parser.postAggregators).setInterval(parser.intervals)
                .setGranularity(parser.granularity).setDimFilter(parser.filter)
                .setDimensions(new ArrayList<DimensionSpec>(parser.groupByDimensions.values())).build();

        typeRef = new TypeReference<List<Row>>() {
        };
        groupBy = true;
    }

    String queryStr = jsonWriter.writeValueAsString(query);
    if (cmd.hasOption("v"))
        System.err.println(queryStr);

    URL url = new URL(String.format("http://%s/druid/v2/?pretty", hostname));
    final URLConnection urlConnection = url.openConnection();
    urlConnection.addRequestProperty("content-type", MediaType.APPLICATION_JSON);
    urlConnection.getOutputStream().write(StringUtils.toUtf8(queryStr));
    BufferedReader stdInput = new BufferedReader(
            new InputStreamReader(urlConnection.getInputStream(), Charsets.UTF_8));

    Object res = objectMapper.readValue(stdInput, typeRef);

    Joiner tabJoiner = Joiner.on("\t");

    if (groupBy) {
        List<Row> rows = (List<Row>) res;
        Iterable<String> dimensions = Iterables.transform(parser.groupByDimensions.values(),
                new Function<DimensionSpec, String>() {
                    @Override
                    public String apply(@Nullable DimensionSpec input) {
                        return input.getOutputName();
                    }
                });

        System.out.println(
                tabJoiner.join(Iterables.concat(Lists.newArrayList("timestamp"), dimensions, parser.fields)));
        for (final Row r : rows) {
            System.out.println(tabJoiner.join(Iterables.concat(
                    Lists.newArrayList(parser.granularity.toDateTime(r.getTimestampFromEpoch())),
                    Iterables.transform(parser.groupByDimensions.values(),
                            new Function<DimensionSpec, String>() {
                                @Override
                                public String apply(@Nullable DimensionSpec input) {
                                    return Joiner.on(",").join(r.getDimension(input.getOutputName()));
                                }
                            }),
                    Iterables.transform(parser.fields, new Function<String, Object>() {
                        @Override
                        public Object apply(@Nullable String input) {
                            return r.getFloatMetric(input);
                        }
                    }))));
        }
    } else {
        List<Result<TimeseriesResultValue>> rows = (List<Result<TimeseriesResultValue>>) res;
        System.out.println(tabJoiner.join(Iterables.concat(Lists.newArrayList("timestamp"), parser.fields)));
        for (final Result<TimeseriesResultValue> r : rows) {
            System.out.println(tabJoiner.join(Iterables.concat(Lists.newArrayList(r.getTimestamp()),
                    Lists.transform(parser.fields, new Function<String, Object>() {
                        @Override
                        public Object apply(@Nullable String input) {
                            return r.getValue().getMetric(input);
                        }
                    }))));
        }
    }

    CloseQuietly.close(stdInput);
}

From source file:com.mrd.bitlib.crypto.FortunaRandomSource.java

public FortunaRandomSource() {
    fortuna = Fortuna.createInstance(Iterables.concat(jmxSources(), defaultSources(), platformSource()));
}

From source file:com.facebook.buck.versions.TargetGraphVersionTransformations.java

public static <A, B extends Description<A>> Iterable<BuildTarget> getDeps(TargetNode<A, B> node) {
    return Iterables.concat(node.getDeclaredDeps(), node.getExtraDeps(), getVersionedDeps(node).keySet());
}

From source file:io.brooklyn.camp.CampRestResources.java

public static Iterable<Object> getAllResources() {
    return Iterables.concat(getCampRestResources(), getApidocResources(), getMiscResources());
}

From source file:org.eclipse.sirius.business.internal.session.danalysis.SessionLazyCrossReferencer.java

@Override
protected void initialize() {
    super.initialize();

    Collection<Resource> semanticResources = session.getSemanticResources();
    EList<Resource> controlledResources = session.getControlledResources();
    Set<Resource> allSessionResources = session.getAllSessionResources();

    Iterable<Resource> resources = Iterables.concat(semanticResources, controlledResources,
            allSessionResources);/*from ww w . j  a va 2  s  .c  om*/
    for (Resource resource : resources) {
        List<Adapter> adapters = resource.eAdapters();
        // add only if it was not added between creation and
        // initialization
        if (!adapters.contains(this)) {
            adapters.add(this);
        }
    }
}

From source file:dagger.internal.codegen.writer.FieldWriter.java

@Override
public Set<ClassName> referencedClasses() {
    Iterable<? extends HasClassReferences> concat = Iterables.concat(ImmutableList.of(type()),
            initializer.asSet(), annotations);
    return FluentIterable.from(concat).transformAndConcat(new Function<HasClassReferences, Set<ClassName>>() {
        @Override/*from  ww w.  jav  a2 s .c  om*/
        public Set<ClassName> apply(HasClassReferences input) {
            return input.referencedClasses();
        }
    }).toSet();
}

From source file:com.google.gerrit.server.mail.CreateChangeSender.java

@Override
protected void init() throws EmailException {
    super.init();

    try {/*  w  w  w  .  j a v a2s  . c om*/
        // Try to mark interested owners with TO and CC or BCC line.
        Watchers matching = getWatchers(NotifyType.NEW_CHANGES);
        for (Account.Id user : Iterables.concat(matching.to.accounts, matching.cc.accounts,
                matching.bcc.accounts)) {
            if (isOwnerOfProjectOrBranch(user)) {
                add(RecipientType.TO, user);
            }
        }

        // Add everyone else. Owners added above will not be duplicated.
        add(RecipientType.TO, matching.to);
        add(RecipientType.CC, matching.cc);
        add(RecipientType.BCC, matching.bcc);
    } catch (OrmException err) {
        // Just don't CC everyone. Better to send a partial message to those
        // we already have queued up then to fail deliver entirely to people
        // who have a lower interest in the change.
        log.warn("Cannot notify watchers for new change", err);
    }

    includeWatchers(NotifyType.NEW_PATCHSETS);
}

From source file:com.google.devtools.build.lib.skyframe.TransitiveTargetCycleReporter.java

@Override
protected boolean canReportCycle(SkyKey topLevelKey, CycleInfo cycleInfo) {
    return Iterables.all(
            Iterables.concat(ImmutableList.of(topLevelKey), cycleInfo.getPathToCycle(), cycleInfo.getCycle()),
            IS_TRANSITIVE_TARGET_SKY_KEY);
}

From source file:com.atlassian.jira.rest.client.api.domain.OperationGroup.java

@Override
public <T> Optional<T> accept(final OperationVisitor<T> visitor) {
    final Optional<T> result = visitor.visit(this);
    if (result.isPresent()) {
        return result;
    } else {/*from w w w . ja va2  s .c  o  m*/
        final Iterable<Operation> operations = Iterables.concat(
                header != null ? Collections.singleton(header) : Collections.<Operation>emptyList(), links,
                groups);
        return accept(operations, visitor);
    }
}

From source file:com.synflow.cx.internal.compiler.ActorBuilder.java

public ActorBuilder(IInstantiator instantiator, Typer typer, Actor actor) {
    super(instantiator, typer, actor);

    existingSet = ImmutableSet.copyOf(//from   ww w.  ja  v a 2 s  .co m
            Iterables.transform(Iterables.concat(actor.getInputs(), actor.getOutputs(), actor.getVariables()),
                    new Function<Var, String>() {
                        @Override
                        public String apply(Var var) {
                            return var.getName();
                        }
                    }));
}