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

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

Introduction

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

Prototype

public static URL getResource(String resourceName) 

Source Link

Document

Returns a URL pointing to resourceName if the resource is found using the Thread#getContextClassLoader() context class loader .

Usage

From source file:at.ac.univie.isc.asio.munin.Munin.java

/**
 * Run the client with parameters from the command line.
 *///from w w w .  j a va2 s. c  om
public static void main(String[] args) throws Exception {
    try {
        Locale.setDefault(Locale.ENGLISH);

        try (final InputStream stream = Resources.getResource(LOGGING_PROPERTIES).openStream()) {
            LogManager.getLogManager().readConfiguration(stream);
        }

        final Properties props = new PropertyHierarchy().loadEmbedded(CLI_PROPERTIES).loadSystem()
                .loadExternal(CLI_PROPERTIES).parseCommandLine(args).loadEmbedded(APPLICATION_PROPERTIES).get();

        if (Boolean.parseBoolean(props.getProperty("debug"))) {
            Logger.getLogger("at.ac.univie.isc.asio").setLevel(Level.FINE);
        }

        System.exit(new Munin(Settings.fromProperties(props)).run(args));

    } catch (final Exception e) {
        System.err.println("[ERROR] fatal - " + e.getMessage());
        System.exit(1);
    }
}

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   w  w  w  .  j  ava  2s.  c o 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.bouncestorage.chaoshttpproxy.Main.java

public static void main(String[] args) throws Exception {
    Options options = new Options();
    CmdLineParser parser = new CmdLineParser(options);
    try {//from   w w  w.  j  a v  a  2  s.c o m
        parser.parseArgument(args);
    } catch (CmdLineException cle) {
        usage(parser);
    }

    if (options.version) {
        System.err.println(Main.class.getPackage().getImplementationVersion());
        System.exit(0);
    }

    ByteSource byteSource;
    if (options.propertiesFile == null) {
        byteSource = Resources.asByteSource(Resources.getResource("chaos-http-proxy.conf"));
    } else {
        byteSource = Files.asByteSource(options.propertiesFile);
    }

    ChaosConfig config;
    try (InputStream is = byteSource.openStream()) {
        config = ChaosConfig.loadFromPropertyStream(is);
    } catch (IOException ioe) {
        System.err.println(ioe.getMessage());
        System.exit(1);
        return;
    }

    URI proxyEndpoint = new URI("http", null, options.address, options.port, null, null, null);
    ChaosHttpProxy proxy = new ChaosHttpProxy(proxyEndpoint, config);
    try {
        proxy.start();
    } catch (Exception e) {
        System.err.println(e.getMessage());
        System.exit(1);
    }
}

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 {//  w  ww  .jav a2  s .c  om
        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:org.apache.s4.tools.CreateApp.java

public static void main(String[] args) {

    final CreateAppArgs appArgs = new CreateAppArgs();
    Tools.parseArgs(appArgs, args);/*from  w w  w .  j  a  va  2  s .  c o  m*/

    if (new File(appArgs.getAppDir() + "/" + appArgs.appName.get(0)).exists()) {
        System.err.println("There is already a directory called " + appArgs.appName.get(0) + " in the "
                + appArgs.getAppDir()
                + " directory. Please specify another name for your project or specify another parent directory");
        System.exit(1);
    }
    // create project structure
    try {
        createDir(appArgs, "/src/main/java");
        createDir(appArgs, "/src/main/resources");
        createDir(appArgs, "/src/main/java/hello");

        // copy gradlew script (redirecting to s4 gradlew)
        File gradlewTempFile = File.createTempFile("gradlew", "tmp");
        gradlewTempFile.deleteOnExit();
        Files.copy(Resources.newInputStreamSupplier(Resources.getResource("templates/gradlew")),
                gradlewTempFile);
        String gradlewScriptContent = Files.readLines(gradlewTempFile, Charsets.UTF_8,
                new PathsReplacer(appArgs));
        Files.write(gradlewScriptContent, gradlewTempFile, Charsets.UTF_8);
        Files.copy(gradlewTempFile, new File(appArgs.getAppDir() + "/gradlew"));
        new File(appArgs.getAppDir() + "/gradlew").setExecutable(true);

        // copy build file contents
        String buildFileContents = Resources.toString(Resources.getResource("templates/build.gradle"),
                Charsets.UTF_8);
        buildFileContents = buildFileContents.replace("<s4_install_dir>",
                "'" + new File(appArgs.s4ScriptPath).getParent() + "'");
        Files.write(buildFileContents, new File(appArgs.getAppDir() + "/build.gradle"), Charsets.UTF_8);

        // copy lib
        FileUtils.copyDirectory(new File(new File(appArgs.s4ScriptPath).getParentFile(), "lib"),
                new File(appArgs.getAppDir() + "/lib"));

        // update app settings
        String settingsFileContents = Resources.toString(Resources.getResource("templates/settings.gradle"),
                Charsets.UTF_8);
        settingsFileContents = settingsFileContents.replaceFirst("rootProject.name=<project-name>",
                "rootProject.name=\"" + appArgs.appName.get(0) + "\"");
        Files.write(settingsFileContents, new File(appArgs.getAppDir() + "/settings.gradle"), Charsets.UTF_8);
        // copy hello app files
        Files.copy(Resources.newInputStreamSupplier(Resources.getResource("templates/HelloPE.java.txt")),
                new File(appArgs.getAppDir() + "/src/main/java/hello/HelloPE.java"));
        Files.copy(Resources.newInputStreamSupplier(Resources.getResource("templates/HelloApp.java.txt")),
                new File(appArgs.getAppDir() + "/src/main/java/hello/HelloApp.java"));
        // copy hello app adapter
        Files.copy(
                Resources.newInputStreamSupplier(Resources.getResource("templates/HelloInputAdapter.java.txt")),
                new File(appArgs.getAppDir() + "/src/main/java/hello/HelloInputAdapter.java"));

        File s4TmpFile = File.createTempFile("s4Script", "template");
        s4TmpFile.deleteOnExit();
        Files.copy(Resources.newInputStreamSupplier(Resources.getResource("templates/s4")), s4TmpFile);

        // create s4
        String preparedS4Script = Files.readLines(s4TmpFile, Charsets.UTF_8, new PathsReplacer(appArgs));

        File s4Script = new File(appArgs.getAppDir() + "/s4");
        Files.write(preparedS4Script, s4Script, Charsets.UTF_8);
        s4Script.setExecutable(true);

        File readmeTmpFile = File.createTempFile("newApp", "README");
        readmeTmpFile.deleteOnExit();
        Files.copy(Resources.newInputStreamSupplier(Resources.getResource("templates/newApp.README")),
                readmeTmpFile);
        // display contents from readme
        Files.readLines(readmeTmpFile, Charsets.UTF_8, new LineProcessor<Boolean>() {

            @Override
            public boolean processLine(String line) throws IOException {
                if (!line.startsWith("#")) {
                    System.out.println(line.replace("<appDir>", appArgs.getAppDir()));
                }
                return true;
            }

            @Override
            public Boolean getResult() {
                return true;
            }

        });
    } catch (Exception e) {
        logger.error("Could not create project due to [{}]. Please check your configuration.", e.getMessage());
    }
}

From source file:com.technobium.MultinomialLogisticRegression.java

public static void main(String[] args) throws Exception {
    // this test trains a 3-way classifier on the famous Iris dataset.
    // a similar exercise can be accomplished in R using this code:
    //    library(nnet)
    //    correct = rep(0,100)
    //    for (j in 1:100) {
    //      i = order(runif(150))
    //      train = iris[i[1:100],]
    //      test = iris[i[101:150],]
    //      m = multinom(Species ~ Sepal.Length + Sepal.Width + Petal.Length + Petal.Width, train)
    //      correct[j] = mean(predict(m, newdata=test) == test$Species)
    //    }/*w w  w  .j a  v  a 2s. c o m*/
    //    hist(correct)
    //
    // Note that depending on the training/test split, performance can be better or worse.
    // There is about a 5% chance of getting accuracy < 90% and about 20% chance of getting accuracy
    // of 100%
    //
    // This test uses a deterministic split that is neither outstandingly good nor bad

    RandomUtils.useTestSeed();
    Splitter onComma = Splitter.on(",");

    // read the data
    List<String> raw = Resources.readLines(Resources.getResource("iris.csv"), Charsets.UTF_8);

    // holds features
    List<Vector> data = Lists.newArrayList();

    // holds target variable
    List<Integer> target = Lists.newArrayList();

    // for decoding target values
    Dictionary dict = new Dictionary();

    // for permuting data later
    List<Integer> order = Lists.newArrayList();

    for (String line : raw.subList(1, raw.size())) {
        // order gets a list of indexes
        order.add(order.size());

        // parse the predictor variables
        Vector v = new DenseVector(5);
        v.set(0, 1);
        int i = 1;
        Iterable<String> values = onComma.split(line);
        for (String value : Iterables.limit(values, 4)) {
            v.set(i++, Double.parseDouble(value));
        }
        data.add(v);

        // and the target
        target.add(dict.intern(Iterables.get(values, 4)));
    }

    // randomize the order ... original data has each species all together
    // note that this randomization is deterministic
    Random random = RandomUtils.getRandom();
    Collections.shuffle(order, random);

    // select training and test data
    List<Integer> train = order.subList(0, 100);
    List<Integer> test = order.subList(100, 150);
    logger.warn("Training set = {}", train);
    logger.warn("Test set = {}", test);

    // now train many times and collect information on accuracy each time
    int[] correct = new int[test.size() + 1];
    for (int run = 0; run < 200; run++) {
        OnlineLogisticRegression lr = new OnlineLogisticRegression(3, 5, new L2(1));
        // 30 training passes should converge to > 95% accuracy nearly always but never to 100%
        for (int pass = 0; pass < 30; pass++) {
            Collections.shuffle(train, random);
            for (int k : train) {
                lr.train(target.get(k), data.get(k));
            }
        }

        // check the accuracy on held out data
        int x = 0;
        int[] count = new int[3];
        for (Integer k : test) {
            Vector vt = lr.classifyFull(data.get(k));
            int r = vt.maxValueIndex();
            count[r]++;
            x += r == target.get(k) ? 1 : 0;
        }
        correct[x]++;

        if (run == 199) {

            Vector v = new DenseVector(5);
            v.set(0, 1);
            int i = 1;
            Iterable<String> values = onComma.split("6.0,2.7,5.1,1.6,versicolor");
            for (String value : Iterables.limit(values, 4)) {
                v.set(i++, Double.parseDouble(value));
            }

            Vector vt = lr.classifyFull(v);
            for (String value : dict.values()) {
                System.out.println("target:" + value);
            }
            int t = dict.intern(Iterables.get(values, 4));

            int r = vt.maxValueIndex();
            boolean flag = r == t;
            lr.close();

            Closer closer = Closer.create();

            try {
                FileOutputStream byteArrayOutputStream = closer
                        .register(new FileOutputStream(new File("model.txt")));
                DataOutputStream dataOutputStream = closer
                        .register(new DataOutputStream(byteArrayOutputStream));
                PolymorphicWritable.write(dataOutputStream, lr);
            } finally {
                closer.close();
            }
        }
    }

    // verify we never saw worse than 95% correct,
    for (int i = 0; i < Math.floor(0.95 * test.size()); i++) {
        System.out.println(String.format("%d trials had unacceptable accuracy of only %.0f%%: ", correct[i],
                100.0 * i / test.size()));
    }
    // nor perfect
    System.out.println(String.format("%d trials had unrealistic accuracy of 100%%", correct[test.size() - 1]));
}

From source file:com.github.fhirschmann.clozegen.lib.examples.NGramWriterExample.java

/**
 * Runs all examples.//  w  ww  .ja  va  2  s .c om
 *
 * @param args unused
 * @throws Exception on errors
 */
public static void main(final String[] args) throws Exception {
    CollectionReader cr = CollectionReaderFactory.createCollectionReader(BrownCorpusReader.class,
            BrownCorpusReader.PARAM_PATH, Resources.getResource("brown_tei_test"),
            BrownCorpusReader.PARAM_PATTERNS, new String[] { "[+]*.xml" });
    Pipeline pipeline = new Pipeline();
    pipeline.add(example1());
    pipeline.add(example2());
    pipeline.add(example3());
    pipeline.run(cr);
}

From source file:org.testcontainers.utility.LicenseAcceptance.java

public static void assertLicenseAccepted(final String imageName) {
    try {//  w  w  w  .j a  v  a 2 s .co  m
        final URL url = Resources.getResource(ACCEPTANCE_FILE_NAME);
        final List<String> acceptedLicences = Resources.readLines(url, Charsets.UTF_8);

        if (acceptedLicences.stream().map(String::trim).anyMatch(imageName::equals)) {
            return;
        }
    } catch (Exception ignored) {
        // suppressed
    }

    throw new IllegalStateException("The image " + imageName + " requires you to accept a license agreement. "
            + "Please place a file at the root of the classpath named " + ACCEPTANCE_FILE_NAME + ", e.g. at "
            + "src/test/resources/" + ACCEPTANCE_FILE_NAME + ". This file should contain the line:\n  "
            + imageName);

}

From source file:com.djd.fun.util.ExpectData.java

/**
 * @param resourceName file path under resources dir
 * @return string represents content of the file
 *//*w  w  w  .ja  va  2s .co  m*/
public static String toString(String resourceName) {
    URL url = Resources.getResource(resourceName);
    try {
        return Resources.toString(url, Charsets.UTF_8);
    } catch (IOException e) {
        throw Throwables.propagate(e);
    }
}

From source file:org.jon.ivmark.graphit.core.io.util.ResourceUtils.java

public static File resourceFile(String path) {
    URL url = Resources.getResource(path);
    return new File(url.getFile());
}