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.ning.billing.osgi.bundles.analytics.AnalyticsTestSuiteWithEmbeddedDB.java

@BeforeClass(groups = "slow")
public void setUpClass() throws Exception {
    embeddedDB = new MySQLEmbeddedDB();
    embeddedDB.initialize();/*w  w  w .  j  av  a2 s . c om*/
    embeddedDB.start();

    final String ddl = toString(
            Resources.getResource("com/ning/billing/osgi/bundles/analytics/ddl.sql").openStream());
    embeddedDB.executeScript(ddl);
}

From source file:com.indeed.imhotep.web.BashScriptServlet.java

@RequestMapping("/iql.sh")
@ResponseBody//from w ww  . j  a  v a 2s  .  co m
protected String doGet(final HttpServletRequest req, final HttpServletResponse resp)
        throws ServletException, IOException {
    resp.setHeader("content-disposition", "attachment; filename=iql.sh");
    final String server = req.getServerName();
    final String protocol;
    if (server.contains("qa.indeed") || server.contains("stage.indeed") || server.contains("indeed.com")) {
        protocol = "https://";
    } else {
        protocol = "http://";
    }

    final URL scriptResourceURL = Resources.getResource("iql.sh");
    final String script = Resources.toString(scriptResourceURL, Charsets.UTF_8);
    final String serverURLVariable = "SERVER_URL=" + protocol + server + ":" + req.getServerPort()
            + req.getContextPath() + "/query\n";
    return serverURLVariable + script;
}

From source file:org.killbill.billing.plugin.analytics.http.StaticServlet.java

private void doHandleStaticResource(final String resourceName, final HttpServletResponse resp)
        throws IOException {
    final URL resourceUrl = Resources.getResource("static/" + resourceName);

    final String[] parts = resourceName.split("/");
    if (parts.length >= 2) {
        if (parts[0].equals("javascript")) {
            resp.setContentType("application/javascript");
        } else if (parts[0].equals("styles")) {
            resp.setContentType("text/css");
        }/* ww  w.j  a va  2 s  .co m*/
        Resources.copy(resourceUrl, resp.getOutputStream());
    } else {
        Resources.copy(resourceUrl, resp.getOutputStream());
        resp.setContentType("text/html");
    }
    resp.setStatus(HttpServletResponse.SC_OK);
}

From source file:util.mybatis.comment.CodetemplatesLoader.java

private void loadAndResolveDocument() throws DocumentException, IOException {
    URL url = Resources.getResource("codetemplates.xml");
    URLConnection openConnection = url.openConnection();
    InputStream inputStream = openConnection.getInputStream();
    OutputFormat format = new OutputFormat();
    format.setEncoding("UTF-8");
    SAXReader reader = new SAXReader();
    Document document = reader.read(new BufferedReader(new InputStreamReader(inputStream, "UTF-8")));
    //      Document document = reader.read(url.getFile(), "UTF-8"));
    Element root = document.getRootElement();
    TemplateVisitor visitor = new TemplateVisitor();
    root.accept(visitor);//from www .ja va2s.  c  om
    templates.putAll(visitor.getTemplates());
}

From source file:org.apache.s4.core.S4Node.java

private static void startNode(S4NodeArgs nodeArgs) throws InterruptedException, IOException {
    Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() {

        @Override/*ww w .  j  a  v a2s .  c o m*/
        public void uncaughtException(Thread t, Throwable e) {
            logger.error("Uncaught exception in thread {}", t.getName(), e);

        }
    });

    // inject parameter from the command line, including zk string
    Map<String, String> inlineParameters = Maps
            .newHashMap(ParsingUtils.convertListArgsToMap(nodeArgs.extraNamedParameters));
    inlineParameters.put("s4.cluster.zk_address", nodeArgs.zkConnectionString);

    Injector injector = Guice.createInjector(
            Modules.override(new BaseModule(Resources.getResource("default.s4.base.properties").openStream(),
                    nodeArgs.clusterName)).with(new ParametersInjectionModule(inlineParameters)));

    S4Bootstrap bootstrap = injector.getInstance(S4Bootstrap.class);
    try {
        bootstrap.start(injector);
    } catch (ArchiveFetchException e1) {
        logger.error("Cannot fetch module dependencies.", e1);
    }
}

From source file:org.asciidoctor.asciidoclet.Stylesheets.java

public boolean copy() {
    if (!docletOptions.destDir().isPresent()) {
        // standard doclet must have checked this by the time we are called
        errorReporter.printError("Destination directory not specified, cannot copy stylesheet");
        return false;
    }/*  ww w . j a v  a2s.co  m*/
    String stylesheet = selectStylesheet(System.getProperty("java.version"));
    File destDir = docletOptions.destDir().get();
    try {
        Resources.copy(Resources.getResource(stylesheet),
                new FileOutputStream(new File(destDir, OUTPUT_STYLESHEET)));
        Resources.copy(Resources.getResource(CODERAY_STYLESHEET),
                new FileOutputStream(new File(destDir, CODERAY_STYLESHEET)));
        return true;
    } catch (IOException e) {
        errorReporter.printError(e.getLocalizedMessage());
        return false;
    }
}

From source file:io.divolte.server.BaseEventHandler.java

public BaseEventHandler(final IncomingRequestProcessingPool processingPool) {
    this.processingPool = Objects.requireNonNull(processingPool);

    try {/*w  w  w  .j a  v  a 2  s  .c  o  m*/
        this.transparentImage = ByteBuffer
                .wrap(Resources.toByteArray(Resources.getResource("transparent1x1.gif"))).asReadOnlyBuffer();
    } catch (final IOException e) {
        // Should throw something more specific than this.
        throw new RuntimeException("Could not load transparent image resource.", e);
    }
}

From source file:com.cloudera.cdk.examples.data.CreateUserDatasetGenericPartitioned.java

@Override
public int run(String[] args) throws IOException {

    // Construct a local filesystem dataset repository rooted at /tmp/data
    FileSystem fs = FileSystem.getLocal(new Configuration());
    Path root = new Path("/tmp/data");
    DatasetRepository repo = new FileSystemDatasetRepository(fs, root);

    // Read an Avro schema from the user.avsc file on the classpath
    Schema schema = new Schema.Parser().parse(Resources.getResource("user.avsc").openStream());

    // Create a partition strategy that hash partitions on username with 10 buckets
    PartitionStrategy partitionStrategy = new PartitionStrategy.Builder().hash("username", 10).get();

    // Create a dataset of users with the Avro schema in the repository
    DatasetDescriptor descriptor = new DatasetDescriptor.Builder().schema(schema)
            .partitionStrategy(partitionStrategy).get();
    Dataset users = repo.create("users", descriptor);

    // Get a writer for the dataset and write some users to it
    DatasetWriter<GenericRecord> writer = users.getWriter();
    try {// w  ww  .ja v  a2  s  .  co m
        writer.open();
        String[] colors = { "green", "blue", "pink", "brown", "yellow" };
        Random rand = new Random();
        GenericRecordBuilder builder = new GenericRecordBuilder(schema);
        for (int i = 0; i < 100; i++) {
            GenericRecord record = builder.set("username", "user-" + i)
                    .set("creationDate", System.currentTimeMillis())
                    .set("favoriteColor", colors[rand.nextInt(colors.length)]).build();
            writer.write(record);
        }
    } finally {
        writer.close();
    }

    return 0;
}

From source file:org.apache.drill.plan.physical.operators.ScanJson.java

public ScanJson(Op op, Map<Integer, Operator> bindings) {
    List<Arg> in = op.getInputs();
    if (in.size() != 1) {
        throw new IllegalArgumentException("scan-json should have exactly one argument (a file name)");
    }/*from  w w w.  j  a v  a2s  . com*/
    String inputName = in.get(0).asString();
    if (inputName.startsWith("resource:")) {
        input = Resources.newReaderSupplier(
                Resources.getResource(inputName.substring(inputName.indexOf(':') + 1)), Charsets.UTF_8);
    } else {
        input = Files.newReaderSupplier(new File(inputName), Charsets.UTF_8);
    }

    List<Arg> out = op.getOutputs();
    if (out.size() != 1) {
        throw new IllegalArgumentException("scan-json should have exactly one output");
    }
    bindings.put(out.get(0).asSymbol().getInt(), this);
}

From source file:com.facebook.buck.lua.LuaInPlaceBinary.java

private static String getRunInplaceResource() {
    try {//from w  ww.  j a va2s  .c  o  m
        return Resources.toString(Resources.getResource(RUN_INPLACE_RESOURCE), Charsets.UTF_8);
    } catch (IOException e) {
        throw Throwables.propagate(e);
    }
}