Example usage for com.google.common.io Resources asCharSource

List of usage examples for com.google.common.io Resources asCharSource

Introduction

In this page you can find the example usage for com.google.common.io Resources asCharSource.

Prototype

public static CharSource asCharSource(URL url, Charset charset) 

Source Link

Document

Returns a CharSource that reads from the given URL using the given character set.

Usage

From source file:de.monticore.templateclassgenerator.TemplateClassGenerator.java

public static void main(String[] args) {
    if (args.length % 2 == 1 || args.length > 4) {
        System.out.println(/*from  w  w  w.  j a v  a  2  s .c o  m*/
                "TemplateClassGenerator CLI Usage: java -jar monticore-templateclassgenerator.jar <templatepath> <out>");
        return;
    }

    CLIArguments arguments = CLIArguments.forArguments(args);
    TemplateClassGeneratorConfiguration config = TemplateClassGeneratorConfiguration.fromArguments(arguments);
    TemplateClassGeneratorScript script = new TemplateClassGeneratorScript();

    try {
        ClassLoader l = TemplateClassGenerator.class.getClassLoader();
        String scriptPath = Resources.asCharSource(
                l.getResource("de/monticore/templateclassgenerator/templateclassgenerator.groovy"),
                Charset.forName("UTF-8")).read();
        script.run(scriptPath, config);
    } catch (IOException e) {
        e.printStackTrace();
    }

}

From source file:com.acme.scramble.ScrambleScorerMain.java

public static void main(String[] args) throws IOException, URISyntaxException {
    ScrambleScorerMain scorerMain = new ScrambleScorerMain(new ScrambleScorer(), new ImmutableList.Builder<>());

    if (args == null || args.length == 1) {
        File file = new File(args[0]);
        if (file.exists()) {
            Files.readLines(file, UTF_8, scorerMain);
            return;
        }//from ww  w .ja  va 2s. co  m

        System.err.println("Input file '" + file + "' not found.");
    } else {
        URL resource = Resources.getResource("sample_input.txt");
        CharSource charSource = Resources.asCharSource(resource, UTF_8);
        charSource.readLines(scorerMain);
    }

}

From source file:com.mapr.PurchaseLog.java

public static void main(String[] args) throws IOException {
    Options opts = new Options();
    CmdLineParser parser = new CmdLineParser(opts);
    try {/*ww w .  j a  va  2  s  .  c o  m*/
        parser.parseArgument(args);
    } catch (CmdLineException e) {
        System.err.println("Usage: -count <number>G|M|K [ -users number ]  log-file user-profiles");
        return;
    }

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

    // first generate lots of user definitions
    SchemaSampler users = new SchemaSampler(
            Resources.asCharSource(Resources.getResource("user-schema.txt"), Charsets.UTF_8).read());
    File userFile = File.createTempFile("user", "tsv");
    BufferedWriter out = Files.newBufferedWriter(userFile.toPath(), Charsets.UTF_8);
    for (int i = 0; i < opts.users; i++) {
        out.write(withTab.join(users.sample()));
        out.newLine();
    }
    out.close();

    // now generate a session for each user
    Splitter onTabs = Splitter.on("\t");
    Splitter onComma = Splitter.on(",");

    Random gen = new Random();
    SchemaSampler intermediate = new SchemaSampler(
            Resources.asCharSource(Resources.getResource("hit_step.txt"), Charsets.UTF_8).read());

    final int COUNTRY = users.getFieldNames().indexOf("country");
    final int CAMPAIGN = intermediate.getFieldNames().indexOf("campaign_list");
    final int SEARCH_TERMS = intermediate.getFieldNames().indexOf("search_keywords");
    Preconditions.checkState(COUNTRY >= 0, "Need country field in user schema");
    Preconditions.checkState(CAMPAIGN >= 0, "Need campaign_list field in step schema");
    Preconditions.checkState(SEARCH_TERMS >= 0, "Need search_keywords field in step schema");

    out = Files.newBufferedWriter(new File(opts.out).toPath(), Charsets.UTF_8);

    for (String line : Files.readAllLines(userFile.toPath(), Charsets.UTF_8)) {
        long t = (long) (TimeUnit.MILLISECONDS.convert(30, TimeUnit.DAYS) * gen.nextDouble());
        List<String> user = Lists.newArrayList(onTabs.split(line));

        // pick session length
        int n = (int) Math.floor(-30 * Math.log(gen.nextDouble()));

        for (int i = 0; i < n; i++) {
            // time on page
            int dt = (int) Math.floor(-20000 * Math.log(gen.nextDouble()));
            t += dt;

            // hit specific values
            JsonNode step = intermediate.sample();

            // check for purchase
            double p = 0.01;
            List<String> campaigns = Lists.newArrayList(onComma.split(step.get("campaign_list").asText()));
            List<String> keywords = Lists.newArrayList(onComma.split(step.get("search_keywords").asText()));
            if ((user.get(COUNTRY).equals("us") && campaigns.contains("5"))
                    || (user.get(COUNTRY).equals("jp") && campaigns.contains("7")) || keywords.contains("homer")
                    || keywords.contains("simpson")) {
                p = 0.5;
            }

            String events = gen.nextDouble() < p ? "1" : "-";

            out.write(Long.toString(t));
            out.write("\t");
            out.write(line);
            out.write("\t");
            out.write(withTab.join(step));
            out.write("\t");
            out.write(events);
            out.write("\n");
        }
    }
    out.close();
}

From source file:de.monticore.cli.MontiCoreCLI.java

/**
 * Main method.//from ww w .  ja  v a  2 s.  c o m
 * 
 * @param args the CLI arguments
 */
public static void main(String[] args) {
    if (args.length == 0) {
        // the only required input are the grammar file(s)/directories
        System.out.println("MontiCore CLI Usage: java -jar monticore-cli.jar <grammar files> <options>");
        return;
    }
    // check if the input model(s) are specified without option and add it for
    // further processing
    if (!args[0].startsWith("-")) {
        ArrayList<String> fixedArgs = new ArrayList<String>(Arrays.asList(args));
        fixedArgs.add(0, "-" + MontiCoreConfiguration.Options.GRAMMARS_SHORT.toString());
        args = fixedArgs.toArray(new String[fixedArgs.size()]);
    }

    CLIArguments arguments = CLIArguments.forArguments(args);
    MontiCoreCLIConfiguration configuration = MontiCoreCLIConfiguration.fromArguments(arguments);

    // this will be CLI's default model path if none is specified
    Iterable<String> mp = Arrays.asList("monticore-cli.jar");
    Iterable<String> mpArg = arguments.asMap().get(MontiCoreConfiguration.Options.MODELPATH.toString());
    Iterable<String> mpShortArg = arguments.asMap()
            .get(MontiCoreConfiguration.Options.MODELPATH_SHORT.toString());
    if ((mpArg == null || Iterables.isEmpty(mpArg)) && (mpShortArg == null || Iterables.isEmpty(mpShortArg))) {
        // prepare args which contain the fixed model path
        Map<String, Iterable<String>> wrappedArgs = new HashMap<>();
        wrappedArgs.put(MontiCoreConfiguration.Options.MODELPATH.toString(), mp);
        wrappedArgs.putAll(arguments.asMap());
        // use this fixed configuration
        configuration = MontiCoreCLIConfiguration.fromMap(wrappedArgs);
    }

    // we store the requested output directory as a system variable such that we
    // can inject it into the logback configuration
    System.setProperty(MC_OUT, configuration.getInternal().getOut().getAbsolutePath());

    // this should always happen first in order to use any custom configurations
    if (System.getProperty(LOGBACK_CONFIGURATIONFILE) == null) {
        initLogging(configuration);
    }

    // this needs to be called after the statement above; otherwise logback will
    // ignore custom configurations supplied via system property
    Slf4jLog.init();

    if (System.getProperty(LOGBACK_CONFIGURATIONFILE) != null) {
        Log.debug(
                "Using system property logback configuration " + System.getProperty(LOGBACK_CONFIGURATIONFILE),
                MontiCoreCLI.class.getName());
    }

    // before we launch MontiCore we check if there are any ".mc4" files in the
    // input argument (source path)
    Iterator<Path> inputPaths = configuration.getInternal().getGrammars().getResolvedPaths();
    if (!inputPaths.hasNext()) {
        System.clearProperty(MC_OUT);
        Log.error("0xA1000 There are no \".mc4\" files to parse. Please check the \"grammars\" option.");
        return;
    }

    try {
        // since this is the default we load the default script
        ClassLoader l = MontiCoreScript.class.getClassLoader();
        String script = Resources
                .asCharSource(l.getResource("de/monticore/monticore_emf.groovy"), Charset.forName("UTF-8"))
                .read();

        // BUT if the user specifies another script to use, we check if it is
        // there and load its content
        if (configuration.getScript().isPresent()) {
            if (!configuration.getScript().get().exists()) {
                System.clearProperty(MC_OUT);
                Log.error("0xA1001 Custom script \"" + configuration.getScript().get().getPath()
                        + "\" not found!");
                return;
            }
            script = Files.toString(configuration.getScript().get(), Charset.forName("UTF-8"));
        }

        // execute the scripts (either default or custom)
        new MontiCoreScript().run(script, configuration.getInternal());
    } catch (IOException e) {
        System.clearProperty(MC_OUT);
        Log.error("0xA1002 Failed to load Groovy script.", e);
    }
}

From source file:com.totango.discoveryagent.ResourceLoader.java

public static String load(String resourceName) {
    try {//from  w ww  .j av a2 s.  c o m
        URL healthJsonURI = Resources.getResource(resourceName);
        CharSource healthJsonSource = Resources.asCharSource(healthJsonURI, Charsets.UTF_8);
        return healthJsonSource.read();
    } catch (Throwable t) {
        throw new RuntimeException(t);
    }
}

From source file:google.registry.rde.imports.RdeImportsTestData.java

/**
 * Loads data from file in {@code rde/imports/testdata/} as a String (assuming file is UTF-8).
 *
 * @throws IOException if the file couldn't be loaded from the jar.
 *//*from www .j  av  a 2s .  c om*/
public static String loadUtf8(String filename) throws IOException {
    return Resources.asCharSource(getUrl(filename), UTF_8).read();
}

From source file:ch.ethz.system.mt.tpch.Distributions.java

public static synchronized Distributions getDefaultDistributions() {
    if (DEFAULT_DISTRIBUTIONS == null) {
        try {// w w  w  .  ja  v  a 2  s  .  c o  m
            URL resource = Resources.getResource(Distribution.class, "dists.dss");
            checkState(resource != null, "Distribution file 'dists.dss' not found");
            DEFAULT_DISTRIBUTIONS = new Distributions(
                    loadDistribution(Resources.asCharSource(resource, Charsets.UTF_8)));
        } catch (IOException e) {
            throw Throwables.propagate(e);
        }
    }
    return DEFAULT_DISTRIBUTIONS;
}

From source file:org.trnltk.morphology.lexicon.DictionaryLoader.java

public static HashSet<Lexeme> loadDefaultMasterDictionary() {
    final CharSource charSource = Resources.asCharSource(Resources.getResource("master-dictionary.dict"),
            Charset.forName("utf-8"));
    return new DictionaryLoader().load(charSource);
}

From source file:org.eclipse.che.plugin.docker.client.DockerfileParser.java

/** Parse content of Dockerfile from the specified URL. */
public static Dockerfile parse(final URL file) throws DockerFileException {
    try {/* w w w  . j a v a2  s . c o m*/
        return parse(
                CharStreams.readLines(Resources.asCharSource(file, Charset.defaultCharset()).openStream()));
    } catch (IOException e) {
        throw new DockerFileException("Error happened parsing the Docker file:" + e.getMessage(), e);
    }
}

From source file:org.trnltk.morphology.lexicon.DictionaryLoader.java

public static HashSet<Lexeme> loadDefaultNumeralMasterDictionary() {
    final CharSource charSource = Resources
            .asCharSource(Resources.getResource("master-numeral-dictionary.dict"), Charset.forName("utf-8"));
    return new DictionaryLoader().load(charSource);
}