Example usage for com.google.common.collect FluentIterable from

List of usage examples for com.google.common.collect FluentIterable from

Introduction

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

Prototype

@Deprecated
@CheckReturnValue
public static <E> FluentIterable<E> from(FluentIterable<E> iterable) 

Source Link

Document

Construct a fluent iterable from another fluent iterable.

Usage

From source file:com.github.jsdossier.tools.WriteDeps.java

public static void main(String[] args) throws CmdLineException, IOException {
    Flags flags = new Flags();

    CmdLineParser parser = new CmdLineParser(flags);
    parser.setUsageWidth(79);//w w  w .  j  a  v  a  2s .  com
    parser.parseArgument(args);

    FileSystem fs = FileSystems.getDefault();
    Path closure = fs.getPath(flags.closure);
    Path output = fs.getPath(flags.output);

    ImmutableList<SourceFile> depsFile = ImmutableList
            .of(SourceFile.fromFile(closure.resolve("deps.js").toString()));
    ImmutableList<SourceFile> sourceFiles = FluentIterable.from(flags.inputs)
            .transform(new Function<String, SourceFile>() {
                @Override
                public SourceFile apply(String input) {
                    return SourceFile.fromFile(input);
                }
            }).toList();

    DepsGenerator generator = new DepsGenerator(depsFile, sourceFiles,
            DepsGenerator.InclusionStrategy.DO_NOT_DUPLICATE, closure.toAbsolutePath().toString(),
            new PrintStreamErrorManager(System.err));
    try (BufferedWriter writer = Files.newBufferedWriter(output, UTF_8)) {
        writer.write(generator.computeDependencyCalls());
        writer.flush();
    }
}

From source file:com.github.jsdossier.tools.Compile.java

public static void main(String[] args) throws Exception {
    Flags flags = new Flags();

    CmdLineParser parser = new CmdLineParser(flags);
    parser.setUsageWidth(79);//w w w.  java2 s  .co  m
    parser.parseArgument(args);

    FileSystem fs = FileSystems.getDefault();
    final Path closure = fs.getPath(flags.closure).toAbsolutePath();

    ErrorManager errorManager = new PrintStreamErrorManager(System.err);
    JsFileParser jsFileParser = new JsFileParser(errorManager);

    List<DependencyInfo> info = new ArrayList<>(flags.inputs.size());
    for (String path : flags.inputs) {
        Path absPath = fs.getPath(path).toAbsolutePath();
        Path closureRelativePath = closure.relativize(absPath);
        info.add(jsFileParser.parseFile(absPath.toString(), closureRelativePath.toString(),
                new String(Files.readAllBytes(absPath), UTF_8)));
    }

    List<DependencyInfo> allDeps = new LinkedList<>(info);
    allDeps.addAll(new DepsFileParser(errorManager).parseFile(closure.resolve("deps.js").toString()));
    List<DependencyInfo> sortedDeps = new SortedDependencies<>(allDeps).getSortedDependenciesOf(info);

    ImmutableSet<String> compilerFlags = FluentIterable.from(sortedDeps)
            .transform(new Function<DependencyInfo, String>() {
                @Override
                public String apply(DependencyInfo input) {
                    return "--js=" + closure.resolve(input.getPathRelativeToClosureBase()).toAbsolutePath()
                            .normalize().toString();
                }
            }).append("--js=" + closure.resolve("base.js")).append(flags.flags).toSet();

    CommandLineRunner.main(compilerFlags.toArray(new String[compilerFlags.size()]));
}

From source file:com.mmounirou.spotirss.SpotiRss.java

/**
 * @param args//from ww  w. j  a  v  a  2  s  .c o  m
 * @throws IOException 
 * @throws ClassNotFoundException 
 * @throws IllegalAccessException 
 * @throws InstantiationException 
 * @throws SpotifyClientException 
 * @throws ChartRssException 
 * @throws SpotifyException 
 */
public static void main(String[] args) throws IOException, InstantiationException, IllegalAccessException,
        ClassNotFoundException, SpotifyClientException {
    if (args.length == 0) {
        System.err.println("usage : java -jar spotiboard.jar <charts-folder>");
        return;
    }

    Properties connProperties = new Properties();
    InputStream inStream = SpotiRss.class.getResourceAsStream("/spotify-server.properties");
    try {
        connProperties.load(inStream);
    } finally {
        IOUtils.closeQuietly(inStream);
    }

    String host = connProperties.getProperty("host");
    int port = Integer.parseInt(connProperties.getProperty("port"));
    String user = connProperties.getProperty("user");

    final SpotifyClient spotifyClient = new SpotifyClient(host, port, user);
    final Map<String, Playlist> playlistsByTitle = getPlaylistsByTitle(spotifyClient);

    final File outputDir = new File(args[0]);
    outputDir.mkdirs();
    TrackCache cache = new TrackCache();
    try {

        for (String strProvider : PROVIDERS) {
            String providerClassName = EntryToTrackConverter.class.getPackage().getName() + "."
                    + StringUtils.capitalize(strProvider);
            final EntryToTrackConverter converter = (EntryToTrackConverter) SpotiRss.class.getClassLoader()
                    .loadClass(providerClassName).newInstance();
            Iterable<String> chartsRss = getCharts(strProvider);
            final File resultDir = new File(outputDir, strProvider);
            resultDir.mkdir();

            final SpotifyHrefQuery hrefQuery = new SpotifyHrefQuery(cache);
            Iterable<String> results = FluentIterable.from(chartsRss).transform(new Function<String, String>() {

                @Override
                @Nullable
                public String apply(@Nullable String chartRss) {

                    try {

                        long begin = System.currentTimeMillis();
                        ChartRss bilboardChartRss = ChartRss.getInstance(chartRss, converter);
                        Map<Track, String> trackHrefs = hrefQuery.getTrackHrefs(bilboardChartRss.getSongs());

                        String strTitle = bilboardChartRss.getTitle();
                        File resultFile = new File(resultDir, strTitle);
                        List<String> lines = Lists.newLinkedList(FluentIterable.from(trackHrefs.keySet())
                                .transform(Functions.toStringFunction()));
                        lines.addAll(trackHrefs.values());
                        FileUtils.writeLines(resultFile, Charsets.UTF_8.displayName(), lines);

                        Playlist playlist = playlistsByTitle.get(strTitle);
                        if (playlist != null) {
                            playlist.getTracks().clear();
                            playlist.getTracks().addAll(trackHrefs.values());
                            spotifyClient.patch(playlist);
                            LOGGER.info(String.format("%s chart exported patched", strTitle));
                        }

                        LOGGER.info(String.format("%s chart exported in %s in %d s", strTitle,
                                resultFile.getAbsolutePath(),
                                (int) TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis() - begin)));

                    } catch (Exception e) {
                        LOGGER.error(String.format("fail to export %s charts", chartRss), e);
                    }

                    return "";
                }
            });

            // consume iterables
            Iterables.size(results);

        }

    } finally {
        cache.close();
    }

}

From source file:com.github.rinde.vanlon15prima.PerformExperiment.java

public static void main(String[] args) {
    final long time = System.currentTimeMillis();
    final Experiment.Builder experimentBuilder = Experiment.build(SUM).computeLocal().withRandomSeed(123)
            .withThreads(Runtime.getRuntime().availableProcessors()).repeat(1)
            .addScenarios(FileProvider.builder().add(Paths.get(DATASET)).filter("glob:**[09].scen"))
            .addResultListener(new CommandLineProgress(System.out))
            .usePostProcessor(PostProcessors.statisticsPostProcessor())
            // central: cheapest insertion configuration
            .addConfiguration(/* w  w  w  .  j  a  va  2 s . c o m*/
                    Central.solverConfiguration(CheapestInsertionHeuristic.supplier(SUM), "CheapInsert"))
            // central: random
            .addConfiguration(Central.solverConfiguration(RandomSolver.supplier()))
            // mas: auction cheapest insertion with 2-opt per vehicle
            .addConfiguration(MASConfiguration.pdptwBuilder().setName("Auction-R-opt2cih-B-cih")
                    .addEventHandler(AddVehicleEvent.class, new VehicleHandler(
                            SolverRoutePlanner.supplier(
                                    Opt2.breadthFirstSupplier(CheapestInsertionHeuristic.supplier(SUM), SUM)),
                            SolverBidder.supplier(SUM, CheapestInsertionHeuristic.supplier(SUM))))
                    .addModel(SolverModel.builder()).addModel(AuctionCommModel.builder()).build());

    final Optional<ExperimentResults> results = experimentBuilder.perform(System.out, args);
    final long duration = System.currentTimeMillis() - time;
    if (!results.isPresent()) {
        return;
    }

    System.out.println("Done, computed " + results.get().getResults().size() + " simulations in "
            + duration / 1000d + "s");

    final Multimap<MASConfiguration, SimulationResult> groupedResults = LinkedHashMultimap.create();
    for (final SimulationResult sr : results.get().sortedResults()) {
        groupedResults.put(sr.getSimArgs().getMasConfig(), sr);
    }

    for (final MASConfiguration config : groupedResults.keySet()) {
        final Collection<SimulationResult> group = groupedResults.get(config);

        final File configResult = new File(RESULTS + config.getName() + ".csv");
        try {
            Files.createParentDirs(configResult);
        } catch (final IOException e1) {
            throw new IllegalStateException(e1);
        }
        // deletes the file in case it already exists
        configResult.delete();
        try {
            Files.append(
                    "dynamism,urgency,scale,cost,travel_time,tardiness,over_time,is_valid,scenario_id,random_seed,comp_time,num_vehicles,num_orders\n",
                    configResult, Charsets.UTF_8);
        } catch (final IOException e1) {
            throw new IllegalStateException(e1);
        }

        for (final SimulationResult sr : group) {
            final String pc = sr.getSimArgs().getScenario().getProblemClass().getId();
            final String id = sr.getSimArgs().getScenario().getProblemInstanceId();
            final int numVehicles = FluentIterable.from(sr.getSimArgs().getScenario().getEvents())
                    .filter(AddVehicleEvent.class).size();
            try {
                final String scenarioName = Joiner.on("-").join(pc, id);
                final List<String> propsStrings = Files
                        .readLines(new File(DATASET + scenarioName + ".properties"), Charsets.UTF_8);
                final Map<String, String> properties = Splitter.on("\n").withKeyValueSeparator(" = ")
                        .split(Joiner.on("\n").join(propsStrings));

                final double dynamism = Double.parseDouble(properties.get("dynamism_bin"));
                final long urgencyMean = Long.parseLong(properties.get("urgency"));
                final double scale = Double.parseDouble(properties.get("scale"));

                final StatisticsDTO stats = (StatisticsDTO) sr.getResultObject();
                final double cost = SUM.computeCost(stats);
                final double travelTime = SUM.travelTime(stats);
                final double tardiness = SUM.tardiness(stats);
                final double overTime = SUM.overTime(stats);
                final boolean isValidResult = SUM.isValidResult(stats);
                final long computationTime = stats.computationTime;

                final long numOrders = Long.parseLong(properties.get("AddParcelEvent"));

                final String line = Joiner.on(",")
                        .appendTo(new StringBuilder(),
                                asList(dynamism, urgencyMean, scale, cost, travelTime, tardiness, overTime,
                                        isValidResult, scenarioName, sr.getSimArgs().getRandomSeed(),
                                        computationTime, numVehicles, numOrders))
                        .append(System.lineSeparator()).toString();
                if (!isValidResult) {
                    System.err.println("WARNING: FOUND AN INVALID RESULT: ");
                    System.err.println(line);
                }
                Files.append(line, configResult, Charsets.UTF_8);
            } catch (final IOException e) {
                throw new IllegalStateException(e);
            }
        }
    }
}

From source file:com.github.rinde.dynurg.Experimentation.java

public static void main(String[] args) {
    System.out.println(System.getProperty("jppf.config"));

    final long time = System.currentTimeMillis();
    final Experiment.Builder experimentBuilder = Experiment.build(SUM).computeDistributed().withRandomSeed(123)
            .repeat(10).numBatches(10)/*from w  w w.  j ava 2 s  .c  o  m*/
            .addScenarios(
                    FileProvider.builder().add(Paths.get(DATASET)).filter("glob:**[01].[0-9]0#[0-5].scen"))
            .addResultListener(new CommandLineProgress(System.out))
            .addConfiguration(
                    Central.solverConfiguration(CheapestInsertionHeuristic.supplier(SUM), "-CheapInsert"))
            .addConfiguration(Central.solverConfiguration(CheapestInsertionHeuristic.supplier(TARDINESS),
                    "-CheapInsert-Tard"))
            .addConfiguration(Central.solverConfiguration(CheapestInsertionHeuristic.supplier(DISTANCE),
                    "-CheapInsert-Dist"))
            .addConfiguration(Central.solverConfiguration(
                    Opt2.breadthFirstSupplier(CheapestInsertionHeuristic.supplier(SUM), SUM),
                    "-bfsOpt2-CheapInsert"))
            .addConfiguration(Central.solverConfiguration(
                    Opt2.breadthFirstSupplier(CheapestInsertionHeuristic.supplier(TARDINESS), TARDINESS),
                    "-bfsOpt2-CheapInsert-Tard"))
            .addConfiguration(Central.solverConfiguration(
                    Opt2.breadthFirstSupplier(CheapestInsertionHeuristic.supplier(DISTANCE), DISTANCE),
                    "-bfsOpt2-CheapInsert-Dist"))
            .addConfiguration(Central.solverConfiguration(
                    Opt2.depthFirstSupplier(CheapestInsertionHeuristic.supplier(SUM), SUM),
                    "-dfsOpt2-CheapInsert"))
            .addConfiguration(Central.solverConfiguration(
                    Opt2.depthFirstSupplier(CheapestInsertionHeuristic.supplier(TARDINESS), TARDINESS),
                    "-dfsOpt2-CheapInsert-Tard"))
            .addConfiguration(Central.solverConfiguration(
                    Opt2.depthFirstSupplier(CheapestInsertionHeuristic.supplier(DISTANCE), DISTANCE),
                    "-dfsOpt2-CheapInsert-Dist"));

    final Menu m = ExperimentCli.createMenuBuilder(experimentBuilder)
            .add(Option.builder("nv", ArgumentParser.INTEGER).longName("number-of-vehicles")
                    .description("Changes the number of vehicles in all scenarios.").build(), experimentBuilder,
                    new ArgHandler<Experiment.Builder, Integer>() {
                        @Override
                        public void execute(Experiment.Builder subject, Optional<Integer> argument) {
                            subject.setScenarioReader(new NumVehiclesScenarioParser(argument.get()));
                        }
                    })
            .build();

    final Optional<String> error = m.safeExecute(args);
    if (error.isPresent()) {
        System.err.println(error.get());
        return;
    }
    final ExperimentResults results = experimentBuilder.perform();

    final long duration = System.currentTimeMillis() - time;
    System.out
            .println("Done, computed " + results.results.size() + " simulations in " + duration / 1000d + "s");

    final Multimap<MASConfiguration, SimulationResult> groupedResults = LinkedHashMultimap.create();
    for (final SimulationResult sr : results.sortedResults()) {
        groupedResults.put(sr.masConfiguration, sr);
    }

    for (final MASConfiguration config : groupedResults.keySet()) {
        final Collection<SimulationResult> group = groupedResults.get(config);

        final File configResult = new File(RESULTS + config.toString() + ".csv");
        try {
            Files.createParentDirs(configResult);
        } catch (final IOException e1) {
            throw new IllegalStateException(e1);
        }
        // deletes the file in case it already exists
        configResult.delete();
        try {
            Files.append(
                    "dynamism,urgency_mean,urgency_sd,cost,travel_time,tardiness,over_time,is_valid,scenario_id,random_seed,comp_time,num_vehicles\n",
                    configResult, Charsets.UTF_8);
        } catch (final IOException e1) {
            throw new IllegalStateException(e1);
        }

        for (final SimulationResult sr : group) {
            final String pc = sr.scenario.getProblemClass().getId();
            final String id = sr.scenario.getProblemInstanceId();
            final int numVehicles = FluentIterable.from(sr.scenario.asList()).filter(AddVehicleEvent.class)
                    .size();
            try {
                final List<String> propsStrings = Files
                        .readLines(new File("files/dataset/" + pc + id + ".properties"), Charsets.UTF_8);
                final Map<String, String> properties = Splitter.on("\n").withKeyValueSeparator(" = ")
                        .split(Joiner.on("\n").join(propsStrings));

                final double dynamism = Double.parseDouble(properties.get("dynamism"));
                final double urgencyMean = Double.parseDouble(properties.get("urgency_mean"));
                final double urgencySd = Double.parseDouble(properties.get("urgency_sd"));

                final double cost = SUM.computeCost(sr.stats);
                final double travelTime = SUM.travelTime(sr.stats);
                final double tardiness = SUM.tardiness(sr.stats);
                final double overTime = SUM.overTime(sr.stats);
                final boolean isValidResult = SUM.isValidResult(sr.stats);
                final long computationTime = sr.stats.computationTime;

                final String line = Joiner.on(",")
                        .appendTo(new StringBuilder(),
                                asList(dynamism, urgencyMean, urgencySd, cost, travelTime, tardiness, overTime,
                                        isValidResult, pc + id, sr.seed, computationTime, numVehicles))
                        .append(System.lineSeparator()).toString();
                if (!isValidResult) {
                    System.err.println("WARNING: FOUND AN INVALID RESULT: ");
                    System.err.println(line);
                }
                Files.append(line, configResult, Charsets.UTF_8);
            } catch (final IOException e) {
                throw new IllegalStateException(e);
            }
        }
    }
}

From source file:ratpack.site.SiteMain.java

public static void main(String... args) throws Exception {
    RxRatpack.initialize();//from   w w w.j a v a 2  s.c om
    RatpackServer.start(b -> b
            .serverConfig(
                    s -> s.baseDir(BaseDir.find()).env().require("/github", SiteModule.GitHubConfig.class))
            .registry(Guice.registry(s -> s.module(NewRelicModule.class).module(new AssetPipelineModule())
                    .module(new CodaHaleMetricsModule(), c -> c.csv(csv -> csv.enable(false)))
                    .module(SiteModule.class).module(MarkupTemplateModule.class, conf -> {
                        conf.setAutoNewLine(true);
                        conf.setUseDoubleQuotes(true);
                        conf.setAutoIndent(true);
                    }).module(TextTemplateModule.class, conf -> conf.setStaticallyCompile(true))))
            .handlers(c -> {

                int longCache = 60 * 60 * 24 * 365; // one year
                int shortCache = 60 * 10; // ten mins

                c.all(ctx -> {
                    //noinspection ConstantConditions
                    String host = ctx.getRequest().getHeaders().get("host");
                    if (host != null
                            && (host.endsWith("ratpack-framework.org") || host.equals("www.ratpack.io"))) {
                        ctx.redirect(301, "http://ratpack.io" + ctx.getRequest().getRawUri());
                        return;
                    }

                    if (ctx.getRequest().getPath().isEmpty()
                            || ctx.getRequest().getPath().equals("index.html")) {
                        ctx.getResponse().getHeaders().set("X-UA-Compatible", "IE=edge,chrome=1");
                    }

                    ctx.next();
                })

                        .prefix("assets", assets -> assets.all(ctx -> {
                            int cacheFor = ctx.getRequest().getQuery().isEmpty() ? shortCache : longCache;
                            ctx.getResponse().getHeaders().add("Cache-Control",
                                    "max-age=" + cacheFor + ", public");
                            ctx.next();
                        }).files(f -> f.dir("assets").indexFiles("index.html")))

                        .get("index.html", ctx -> {
                            ctx.redirect(301, "/");
                        })

                        .get(ctx -> ctx.render(groovyMarkupTemplate("index.gtpl")))

                        .path("reset", ctx -> ctx.byMethod(methods -> {
                            Block impl = () -> {
                                ctx.get(GitHubData.class).forceRefresh();
                                ctx.render("ok");
                            };
                            if (ctx.getServerConfig().isDevelopment()) {
                                methods.get(impl);
                            }
                            methods.post(impl);
                        }))

                        .prefix("versions", v -> v
                                .get(ctx -> ctx.render(ctx.get(RatpackVersions.class).getAll()
                                        .map(all -> groovyMarkupTemplate("versions.gtpl",
                                                m -> m.put("versions", all)))))
                                .get(":version", ctx -> ctx.render(ctx.get(RatpackVersions.class).getAll()
                                        .map(all -> all.version(ctx.getAllPathTokens().get("version")))
                                        .onNull(() -> ctx.clientError(404))
                                        .flatMap(version -> ctx.get(GitHubData.class).closed(version)
                                                .map(i -> Pair.of(version, i)))
                                        .map(p -> groovyMarkupTemplate("version.gtpl",
                                                m -> m.put("version", p.left).put("issues", p.right))))))

                        .prefix("manual",
                                c1 -> c1.fileSystem("manual",
                                        c2 -> c2.get(ctx -> ctx.redirect(301, "manual/current"))
                                                .prefix(":label", c3 -> c3.all(ctx -> {
                                                    String label = ctx.getPathTokens().get("label");

                                                    ctx.get(RatpackVersions.class).getAll().then(all -> {
                                                        if (label.equals("current") || all.isReleased(label)) {
                                                            ctx.getResponse().getHeaders().add("Cache-Control",
                                                                    "max-age=" + longCache + ", public");
                                                        } else if (label.equals("snapshot")
                                                                || all.isUnreleased(label)) {
                                                            ctx.getResponse().getHeaders().add("Cache-Control",
                                                                    "max-age=" + shortCache + ", public");
                                                        }

                                                        RatpackVersion version;
                                                        switch (label) {
                                                        case "current":
                                                            version = all.getCurrent();
                                                            break;
                                                        case "snapshot":
                                                            version = all.getSnapshot();
                                                            break;
                                                        default:
                                                            version = all.version(label);
                                                            if (version == null) {
                                                                ctx.clientError(404);
                                                                return;
                                                            }
                                                            break;
                                                        }

                                                        ctx.next(Registry.single(ctx.getFileSystemBinding()
                                                                .binding(version.getVersion())));
                                                    });
                                                }).files(f -> f.indexFiles("index.html"))))

                        )

                        .get("robots.txt",
                                ctx -> ctx.get(RatpackVersions.class).getAll().map(RatpackVersions.All::getAll)
                                        .map(v -> FluentIterable.from(v)
                                                .transform(i -> "Disallow: /manual/" + i.getVersion())
                                                .join(Joiner.on("\n")))
                                        .map(s -> "User-agent: *\nDisallow: /manual/snapshot\n" + s)
                                        .then(ctx::render))
                        .get("favicon.ico", ctx -> {
                            ctx.getResponse().getHeaders().add("Cache-Control",
                                    "max-age=" + longCache + ", public");
                            ctx.next();
                        }).files(f -> f.dir("public").indexFiles("index.html"));
            }));
}

From source file:com.b2international.commons.functions.StringToLongFunction.java

public static List<Long> copyOf(Iterable<String> stringIterable) {
    return FluentIterable.from(stringIterable).transform(new StringToLongFunction()).toList();
}

From source file:com.b2international.commons.functions.LongToStringFunction.java

public static List<String> copyOf(Iterable<Long> stringIterable) {
    return FluentIterable.from(stringIterable).transform(new LongToStringFunction()).toList();
}

From source file:org.incode.eurocommercial.contactapp.dom.number.ContactNumberType.java

public static Set<String> titles() {
    return FluentIterable.from(Arrays.asList(values())).transform(ContactNumberType::title).toSet();
}

From source file:com.google.cloud.tools.gradle.appengine.BuildResultFilter.java

/** Extract task as a list of path strings. */
public static List<String> extractTasks(BuildResult buildResult) {

    return FluentIterable.from(buildResult.getTasks()).transform(new Function<BuildTask, String>() {
        @Override/*w ww. jav a  2s.com*/
        public String apply(BuildTask buildTask) {
            return buildTask.getPath();
        }
    }).toList();
}