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:com.mapr.synth.samplers.SsnSampler.java

public SsnSampler() {
    Splitter onComma = Splitter.on(",").trimResults();
    try {//from w w  w . j a v  a  2 s  .  c  o m
        names = null;
        for (String line : Resources.readLines(Resources.getResource("ssn-seeds"), Charsets.UTF_8)) {
            if (line.startsWith("#")) {
                // last comment line contains actual field names
                names = Lists.newArrayList(onComma.split(line.substring(1)));
            } else {
                Preconditions.checkState(names != null);
                assert names != null;

                List<String> fields = Lists.newArrayList(onComma.split(line));
                for (int i = Integer.parseInt(fields.get(1)); i <= Integer.parseInt(fields.get(1)); i++) {
                    String key = String.format("%03d", i);
                    values.put(key, fields.subList(2, fields.size()));
                    codes.add(key);
                }

            }
        }
        assert names != null;
        names = names.subList(2, names.size());
    } catch (IOException e) {
        throw new RuntimeException("Couldn't read built-in resource", e);
    }
}

From source file:com.feedeo.shopify.web.client.rest.ShopifyOAuth2RestClient.java

private static Properties getProperties() {
    final Properties properties = new Properties();

    final URL url = Resources.getResource("jopify.properties");
    final ByteSource byteSource = Resources.asByteSource(url);

    InputStream inputStream = null;
    try {/*from w  w  w  .jav a  2s . co  m*/
        inputStream = byteSource.openBufferedStream();
        properties.load(inputStream);
    } catch (final IOException ioException) {
        ioException.printStackTrace();
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (final IOException ioException) {
                ioException.printStackTrace();
            }
        }
    }

    return properties;
}

From source file:zipkin.elasticsearch.ElasticsearchConfig.java

ElasticsearchConfig(Builder builder) {
    clusterName = checkNotNull(builder.cluster, "builder.cluster");
    hosts = checkNotNull(builder.hosts, "builder.hosts");
    index = checkNotNull(builder.index, "builder.index");

    try {/* w  w  w  .ja va  2s.c  om*/
        indexTemplate = Resources.toString(Resources.getResource("zipkin/elasticsearch/zipkin_template.json"),
                StandardCharsets.UTF_8).replace("${__INDEX__}", index);
    } catch (IOException e) {
        throw new AssertionError("Error reading jar resource, shouldn't happen.", e);
    }
}

From source file:org.thingsboard.server.dao.CustomSqlUnit.java

@Override
public void before() {
    cleanUpDb();//w ww.j  a  va2 s . c o m

    Connection conn = null;
    try {
        conn = DriverManager.getConnection(dbUrl, dbUserName, dbPassword);
        for (String sqlFile : sqlFiles) {
            URL sqlFileUrl = Resources.getResource(sqlFile);
            String sql = Resources.toString(sqlFileUrl, Charsets.UTF_8);
            conn.createStatement().execute(sql);
        }
    } catch (IOException | SQLException e) {
        throw new RuntimeException("Unable to start embedded hsqldb. Reason: " + e.getMessage(), e);
    } finally {
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                log.error(e.getMessage(), e);
            }
        }
    }
}

From source file:com.ning.billing.catalog.io.VersionedCatalogLoader.java

@Override
public VersionedCatalog load(final String uriString) throws ServiceException {
    try {/*from w w w  . java 2  s  . c o m*/
        List<URI> xmlURIs = null;

        if (uriString.endsWith(XML_EXTENSION)) { // Assume its an xml file
            xmlURIs = new ArrayList<URI>();
            URI uri = new URI(uriString);

            // Try to expand the full path, if possible
            final String schemeSpecificPart = uri.getSchemeSpecificPart();
            if (schemeSpecificPart != null) {
                final String[] split = schemeSpecificPart.split("/");
                final String fileName = split[split.length - 1];
                try {
                    uri = new URI(Resources.getResource(fileName).toExternalForm());
                } catch (IllegalArgumentException ignored) {
                }
            }

            xmlURIs.add(uri);
        } else { // Assume its a directory
            final String directoryContents = UriAccessor.accessUriAsString(uriString);
            xmlURIs = findXmlReferences(directoryContents, new URL(uriString));
        }

        final VersionedCatalog result = new VersionedCatalog(clock);
        for (final URI u : xmlURIs) {
            final StandaloneCatalog catalog = XMLLoader.getObjectFromUri(u, StandaloneCatalog.class);
            result.add(catalog);
        }

        return result;
    } catch (Exception e) {
        throw new ServiceException("Problem encountered loading catalog", e);
    }
}

From source file:com.proofpoint.rack.RackServlet.java

@Inject
public RackServlet(RackServletConfig config) throws IOException {
    Preconditions.checkNotNull(config);/*from  w ww  .  ja  v  a  2s. c o m*/

    File rackScriptFile = new File(config.getRackConfigPath());

    Preconditions.checkArgument(rackScriptFile.exists(), "Could not find rack script specified by ["
            + config.getRackConfigPath() + "] and resolved to [" + rackScriptFile.getAbsolutePath() + "]");

    runtime = JavaEmbedUtils.initialize(ImmutableList.of(rackScriptFile.getParentFile().getCanonicalPath()),
            createRuntimeConfig());

    InputStream stream = Resources.getResource("proofpoint/rack.rb").openStream();
    try {
        runtime.loadFile("rack.rb", stream, false);
    } finally {
        stream.close();
    }

    IRubyObject builder = runtime.evalScriptlet("Proofpoint::RackServer::Builder.new");

    rackApplication = adapter.callMethod(builder, "build",
            new IRubyObject[] { javaToRuby(runtime, rackScriptFile.getCanonicalPath()) });
}

From source file:com.arcbees.website.server.HomeServlet.java

private Properties loadVelocityProperties() {
    Properties properties = new Properties();

    try {//from   w  w  w. ja va 2  s .  co  m
        URL url = Resources.getResource(VELOCITY_PROPERTIES);
        ByteSource byteSource = Resources.asByteSource(url);

        properties.load(byteSource.openStream());
    } catch (Exception e) {
        throw new RuntimeException("Unable to load velocity properties from '" + VELOCITY_PROPERTIES + "'.", e);
    }

    return properties;
}

From source file:com.stratio.decision.unit.engine.action.CassandraServer.java

/**
 * Set embedded cassandra up and spawn it in a new thread.
 * /*from ww  w  .  j  av a 2 s  . com*/
 * @throws TTransportException
 * @throws IOException
 * @throws InterruptedException
 */
public void start() throws TTransportException, IOException, InterruptedException, ConfigurationException {

    File dir = Files.createTempDir();
    String dirPath = dir.getAbsolutePath();
    System.out.println("Storing Cassandra files in " + dirPath);

    URL url = Resources.getResource("cassandra.yaml");
    String yaml = Resources.toString(url, Charsets.UTF_8);
    yaml = yaml.replaceAll("REPLACEDIR", dirPath);
    String yamlPath = dirPath + File.separatorChar + "cassandra.yaml";
    org.apache.commons.io.FileUtils.writeStringToFile(new File(yamlPath), yaml);

    // make a tmp dir and copy cassandra.yaml and log4j.properties to it
    copy("/log4j.properties", dir.getAbsolutePath());
    System.setProperty("cassandra.config", "file:" + dirPath + yamlFilePath);
    System.setProperty("log4j.configuration", "file:" + dirPath + "/log4j.properties");
    System.setProperty("cassandra-foreground", "true");

    cleanupAndLeaveDirs();

    try {
        executor.execute(new CassandraRunner());
    } catch (RejectedExecutionException e) {
        log.error("RejectError", e);
        return;
    }

    try {
        TimeUnit.SECONDS.sleep(WAIT_SECONDS);
    } catch (InterruptedException e) {
        log.error("InterrputedError", e);
        throw new AssertionError(e);
    }
}

From source file:org.kitesdk.tools.CombinedLogFormatConverter.java

@Override
public int run(String... args) throws Exception {
    if (args.length != 3) {
        System.err.println("Usage: " + CombinedLogFormatConverter.class.getSimpleName()
                + " <input> <dataset_uri> <dataset name>");
        return 1;
    }/*from  w w  w. ja  v  a 2 s. c om*/
    String input = args[0];
    String datasetUri = args[1];
    String datasetName = args[2];

    Schema schema = new Schema.Parser().parse(Resources.getResource("combined_log_format.avsc").openStream());

    // Create the dataset
    DatasetRepository repo = DatasetRepositories.open(datasetUri);
    DatasetDescriptor datasetDescriptor = new DatasetDescriptor.Builder().schema(schema).build();
    Dataset<Object> dataset = repo.create(datasetName, datasetDescriptor);

    // Run the job
    final String schemaString = schema.toString();
    AvroType<GenericData.Record> outputType = Avros.generics(schema);
    PCollection<String> lines = readTextFile(input);
    PCollection<GenericData.Record> records = lines.parallelDo(new ConvertFn(schemaString), outputType);
    getPipeline().write(records, CrunchDatasets.asTarget(dataset), Target.WriteMode.APPEND);
    run();
    return 0;
}

From source file:org.apache.provisionr.api.util.BuilderWithOptions.java

/**
 * Load options from a properties file available as a resource on the classpath
 *//*from  w w w . j a v a2 s. c om*/
public P optionsFromResource(String resource) {
    Properties properties = new Properties();
    ByteArrayInputStream in = null;
    try {
        in = new ByteArrayInputStream(Resources.toByteArray(Resources.getResource(resource)));
        properties.load(in);
        return options(properties);

    } catch (IOException e) {
        throw Throwables.propagate(e);
    } finally {
        Closeables.closeQuietly(in);
    }
}