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.github.steveash.jg2p.align.InputReader.java

public List<InputRecord> readFromClasspath(String resource) throws IOException {
    return read(Resources.asCharSource(Resources.getResource(resource), Charsets.UTF_8));
}

From source file:free.jin.ui.AboutPanel.java

/**
 * Creates the user interface./*w w w.  j  a va2  s  .c o m*/
 */

private void createUI() {
    I18n i18n = I18n.get(AboutPanel.class);

    setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));

    Icon jinIcon = new ImageIcon(Resources.getResource("logo48.png"));
    JLabel jinLabel = new JLabel(Jin.getAppName() + " " + Jin.getAppVersion(), jinIcon, SwingConstants.CENTER);
    jinLabel.setFont(new Font("Serif", Font.PLAIN, 36));
    jinLabel.setAlignmentX(CENTER_ALIGNMENT);

    add(jinLabel);
    add(Box.createVerticalStrut(5));
    add(new JSeparator());
    add(Box.createVerticalStrut(5));

    String copyright;
    try {
        copyright = IOUtilities.loadText(Jin.class.getResourceAsStream("legal/copyright.txt"));
    } catch (java.io.IOException e) {
        add(i18n.createLabel("unableToLoadCopyright"));
        return;
    }
    StringTokenizer copyrightLines = new StringTokenizer(copyright, "\r\n");

    Font font = new Font("SansSerif", Font.PLAIN, 12);
    while (copyrightLines.hasMoreTokens()) {
        String line = copyrightLines.nextToken();
        JLabel label = new JLabel(line.trim(), SwingConstants.CENTER);
        label.setAlignmentX(CENTER_ALIGNMENT);
        label.setFont(font);
        add(label);
    }

    add(Box.createVerticalStrut(10));

    JLabel dedicationLabel = new JLabel(Jin.getAppProperty("app.dedication", null), SwingConstants.CENTER);
    dedicationLabel.setAlignmentX(CENTER_ALIGNMENT);
    add(dedicationLabel);
    dedicationLabel.setFont(font);

    add(Box.createVerticalStrut(10));

    JButton closeButton = i18n.createButton("closeButton");
    closeButton.addActionListener(new ClosingListener(null));
    closeButton.setAlignmentX(CENTER_ALIGNMENT);
    add(closeButton);

    setDefaultButton(closeButton);
}

From source file:org.mayocat.shop.front.resources.ResourceResource.java

@GET
@Path("{path:.+}")
public Response getResource(@PathParam("path") String resource, @Context Request request) throws Exception {
    ThemeResource themeResource = themeFileResolver.getResource(resource, context.getRequest().getBreakpoint());
    if (themeResource == null) {
        logger.debug("Resource [{}] not found", resource);
        throw new WebApplicationException(404);
    }/*from   www  .  j a v a 2s.  c  o m*/

    File file;

    switch (themeResource.getType()) {
    default:
    case FILE:
        file = themeResource.getPath().toFile();
        break;
    case CLASSPATH_RESOURCE:
        URI uri = Resources.getResource(themeResource.getPath().toString()).toURI();

        if (uri.getScheme().equals("jar")) {
            // Not supported for now
            return Response.status(Response.Status.NOT_FOUND).build();
        }

        file = new File(uri);
        break;
    }

    String tag = Files.hash(file, Hashing.murmur3_128()).toString();
    EntityTag eTag = new EntityTag(tag);

    URL url = file.toURI().toURL();
    long lastModified = ResourceURL.getLastModified(url);
    if (lastModified < 1) {
        // Something went wrong trying to get the last modified time: just use the current time
        lastModified = System.currentTimeMillis();
    }
    // zero out the millis since the date we get back from If-Modified-Since will not have them
    lastModified = (lastModified / 1000) * 1000;

    CacheControl cacheControl = new CacheControl();
    cacheControl.setMaxAge(24 * 3600);
    Response.ResponseBuilder builder = request.evaluatePreconditions(new Date(lastModified), eTag);
    String mimeType = guessMimeType(file).or("application/octet-stream");

    if (builder == null) {
        if (mimeType.equals("application/javascript")) {
            // Handle javascript files as a special case. Something (what ?) is serializing them as URIs instead
            // of file contents.
            // FIXME: find out what at in Jersey or Jackson or DW is doing that and disable that behavior
            builder = Response.ok(Files.toString(file, Charsets.UTF_8), mimeType);
        } else {
            builder = Response.ok(file, mimeType);
        }
    }

    return builder.cacheControl(cacheControl).lastModified(new Date(lastModified)).build();
}

From source file:com.mapr.synth.samplers.ZipSampler.java

public ZipSampler() {
    try {/*from w  w w. j a  v a2s  .co  m*/
        List<String> names = null;
        for (String line : Resources.readLines(Resources.getResource("zip.csv"), Charsets.UTF_8)) {
            CsvSplitter onComma = new CsvSplitter();
            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;
                Iterable<String> fields = onComma.split(line);
                Iterator<String> nx = names.iterator();
                for (String value : fields) {
                    Preconditions.checkState(nx.hasNext());
                    String fieldName = nx.next();
                    List<String> dataList = values.get(fieldName);
                    if (dataList == null) {
                        dataList = Lists.newArrayList();
                        values.put(fieldName, dataList);
                    }
                    dataList.add(value);
                }
                if (!names.iterator().next().equals("V1")) {
                    Preconditions.checkState(!nx.hasNext());
                }
                zipCount++;
            }
        }
    } catch (IOException e) {
        throw new RuntimeException("Couldn't read built-in zip code data file", e);
    }
}

From source file:org.kiji.bento.ConfigurationBuilder.java

/**
 * Constructs a new configuration builder.  The name specified for the configuration will be
 * used to generate a filename for the configuration. The filename will be prefixed with
 * "bento-" and suffixed with ".xml"./*w  ww.  j  a  va 2 s  .c o  m*/
 *
 * @param name The name of the configuration, for example, "mapred-site" or "core-site."
 * @param commentResource The name of a resource that contains a usage comment for the
 *     configuration.
 */
public ConfigurationBuilder(String name, String commentResource) {
    URL resourceURL = Resources.getResource(commentResource);
    String comment;
    try {
        comment = Resources.toString(resourceURL, Charset.forName("UTF-8"));
    } catch (IOException e) {
        throw new RuntimeException("Error when generating a Hadoop site XML file being: "
                + "comment could not be read from resource: " + commentResource);
    }
    mWriter = new ConfigurationWriter(comment);
    mFileName = "bento-" + name + ".xml";
}

From source file:org.openqa.selenium.iphone.IPhoneSimulatorBinary.java

protected static String getIphoneSimPath() {
    String filename = "ios-sim";
    File parentDir = TemporaryFilesystem.getDefaultTmpFS().createTempDir("webdriver", "libs");
    try {/*from  w w w  .j  a va  2s .  c o m*/
        File destination = new File(parentDir, filename);
        FileOutputStream outputStream = new FileOutputStream(destination);
        try {
            URL resource = Resources.getResource(
                    IPhoneSimulatorBinary.class.getPackage().getName().replace('.', '/') + '/' + filename);
            Resources.copy(resource, outputStream);
            FileHandler.makeExecutable(destination);
            return destination.getAbsolutePath();
        } finally {
            outputStream.close();
        }
    } catch (IOException e) {
        throw new WebDriverException(e);
    }
}

From source file:org.n52.youngs.control.Main.java

public static Report dabCsw() throws Exception {
    // http://api.eurogeoss-broker.eu/dab/services/cswiso?service=CSW&version=2.0.2&request=GetCapabilities
    Source source = new KvpCswSource("http://api.eurogeoss-broker.eu/dab/services/cswiso",
            Collections.singleton("http://www.opengis.net/cat/csw/2.0.2"), NamespaceContextImpl.create(),
            "csw:Record", "http://www.opengis.net/cat/csw/2.0.2");

    MappingConfiguration configuration = new YamlMappingConfiguration(
            Resources.asByteSource(Resources.getResource("mappings/csw-record.yml")).openStream(),
            new XPathHelper());
    Mapper mapper = new CswToBuilderMapper(configuration);

    String host = "localhost";
    String cluster = "ConnectinGEO";
    String index = "geodab";
    String type = "dcrecord";
    int port = 9301;
    Sink sink = new ElasticsearchRemoteHttpSink(host, port, cluster, index, type);

    Runner runner = new SingleThreadBulkRunner().setBulkSize(20).setRecordsLimit(10).setStartPosition(1)
            .harvest(source).transform(mapper);
    Report report = runner.load(sink);//from  w ww  .  j a v  a  2  s  .c  om
    return report;
}

From source file:io.hops.hopsworks.common.util.IoUtils.java

public static List<String> readLinesFromClasspath(String url) throws IOException {
    return Resources.readLines(Resources.getResource(url), Charsets.UTF_8);
}

From source file:com.mapr.synth.samplers.NameSampler.java

public NameSampler() {
    try {/*from w  w w.  j  a  va  2 s. c  o  m*/
        if (first.compareAndSet(null, new Multinomial<String>())) {
            Preconditions.checkState(last.getAndSet(new Multinomial<String>()) == null);

            Splitter onTab = Splitter.on(CharMatcher.WHITESPACE).omitEmptyStrings().trimResults();
            for (String resourceName : ImmutableList.of("dist.male.first", "dist.female.first")) {
                for (String line : Resources.readLines(Resources.getResource(resourceName), Charsets.UTF_8)) {
                    if (!line.startsWith("#")) {
                        Iterator<String> parts = onTab.split(line).iterator();
                        String name = initialCap(parts.next());
                        double weight = Double.parseDouble(parts.next());
                        if (first.get().getWeight(name) == 0) {
                            first.get().add(name, weight);
                        } else {
                            // do this instead of add because some first names may appear more than once
                            first.get().set(name, first.get().getWeight(name) + weight);
                        }
                    }
                }
            }

            for (String line : Resources.readLines(Resources.getResource("dist.all.last"), Charsets.UTF_8)) {
                if (!line.startsWith("#")) {
                    Iterator<String> parts = onTab.split(line).iterator();
                    String name = initialCap(parts.next());
                    double weight = Double.parseDouble(parts.next());
                    last.get().add(name, weight);
                }
            }
        }
    } catch (IOException e) {
        throw new RuntimeException("Couldn't read built-in resource file", e);
    }
}

From source file:com.boundary.metrics.vmware.VMWareTestUtils.java

public static VMwarePerfAdapterConfiguration getConfiguration(String resource) throws Exception {

    VMwarePerfAdapterConfiguration configuration = null;
    File configFile = new File(Resources.getResource(resource).toURI());

    Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
    ConfigurationFactory<VMwarePerfAdapterConfiguration> factory = new ConfigurationFactory<VMwarePerfAdapterConfiguration>(
            VMwarePerfAdapterConfiguration.class, validator, Jackson.newObjectMapper(), "dw");

    try {/*ww w.j a va  2 s  .  c  om*/
        configuration = factory.build(configFile);
    } catch (JsonParseException e) {
        e.printStackTrace();
    } catch (JsonMappingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return configuration;
}