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

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

Introduction

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

Prototype

public static ByteSource asByteSource(URL url) 

Source Link

Document

Returns a ByteSource that reads from the given URL.

Usage

From source file:com.bsiag.htmltools.maven.CopyDocsMojo.java

@Override
public void execute() throws MojoExecutionException, MojoFailureException {
    //Output Folder:
    if (outputFolder == null) {
        throw new MojoFailureException("outputFolder is undefined.");
    } else if (outputFolder.exists() && !outputFolder.isDirectory()) {
        throw new MojoFailureException("outputFolder is not a directory. " + outputFolder.getAbsolutePath());
    }/*from   w w w .  j a v  a  2s. c o m*/

    //Input Folder:
    if (inputFolder == null) {
        throw new MojoFailureException("inputFolder is undefined.");
    } else if (inputFolder.exists() && !inputFolder.isDirectory()) {
        throw new MojoFailureException("inputFolder is not a directory. " + inputFolder.getAbsolutePath());
    }

    //If the ZipUrl is defined, the zip file will be extracted in the input folder:
    if (inputZipUrl != null) {
        URL zipFile;
        try {
            zipFile = new URL(inputZipUrl);
            InputStream zipInputStream = Resources.asByteSource(zipFile).openBufferedStream();

            ZipUtility.unzip(zipInputStream, inputFolder);
            getLog().info("Zip '" + inputZipUrl + "' unzipped at: " + inputFolder.getAbsolutePath());
        } catch (MalformedURLException e) {
            new MojoFailureException("MalformedURLException in copydocs (unzip)", e);
        } catch (IOException e) {
            new MojoFailureException("IOExectpion in copydocs (unzip)", e);
        }
    }

    //Input work folder:
    File inputWorkFolder;
    if (inputSubFolder != null) {
        inputWorkFolder = new File(inputFolder, inputSubFolder);
        if (inputWorkFolder.exists() && !inputWorkFolder.isDirectory()) {
            throw new MojoFailureException(
                    "inputWorkFolder is not a directory. " + inputFolder.getAbsolutePath());
        }
    } else {
        inputWorkFolder = inputFolder;
    }
    getLog().info("Working with the input folder: " + inputWorkFolder.getAbsolutePath());

    //Execute action:
    try {
        List<FileAction> actions = PublishUtility.computeActions(inputWorkFolder, outputFolder, !partialSync);
        getLog().info(
                "Found '" + actions.size() + "' actions to perform in: " + outputFolder.getAbsolutePath());
        for (FileAction a : actions) {
            getLog().debug("Action : " + a.toString());
        }
        PublishUtility.doActions(actions);
        if (actions.size() > 0) {
            Collection<FileAction> parents = PublishUtility.computeParentFolders(actions);
            for (FileAction a : parents) {
                FileAction child = a.createActionWithSubFolder("images");
                getLog().info("Sync subfolder 'images': " + child.toString());
                child.doAction();
            }
        }
    } catch (IOException e) {
        new MojoFailureException("IOExectpion in copydocs", e);
    }

}

From source file:org.isisaddons.wicket.pdfjs.fixture.scripts.data.DemoObjectsFixture.java

private Blob asBlob(final String documentName, final String urlStr) {
    try {// w ww.  j  ava  2  s  .  co  m
        final URL url = new URL(urlStr);

        final HttpURLConnection httpConn = openConnection(url);
        final String contentType = httpConn.getContentType();
        final MimeType mimeType = determineMimeType(contentType);

        httpConn.disconnect();

        final ByteSource byteSource = Resources.asByteSource(url);
        final byte[] bytes = byteSource.read();

        return new Blob(documentName, mimeType.getBaseType(), bytes);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:exercise.basic.ResponseDemoResource.java

/**
 * @return//from  w  w  w  .j  a  va 2 s  .  c o m
 */
@GET
@Path("sampleimage.png")
public Response anydata() {
    URL resurl = Resources.getResource("exercise/sampleimage.png");
    final ByteSource byteSource = Resources.asByteSource(resurl);
    StreamingOutput stream = new StreamingOutput() {
        @Override
        public void write(OutputStream os) throws IOException, WebApplicationException {
            byteSource.copyTo(os);
            os.flush();
        }
    };
    return Response.status(Status.OK).type("image/png").entity(stream).build();
}

From source file:org.locationtech.geogig.storage.bdbje.EnvironmentBuilder.java

/**
 * @return//from  w  w w.  j  a  v a 2 s  .  com
 * @see com.google.inject.Provider#get()
 */
@Override
public synchronized Environment get() {

    final Optional<URL> repoUrl = new ResolveGeogigDir(platform).call();
    if (!repoUrl.isPresent() && absolutePath == null) {
        throw new IllegalStateException("Can't find geogig repository home");
    }
    final File storeDirectory;

    if (absolutePath != null) {
        storeDirectory = absolutePath;
    } else {
        File currDir;
        try {
            currDir = new File(repoUrl.get().toURI());
        } catch (URISyntaxException e) {
            throw Throwables.propagate(e);
        }
        File dir = currDir;
        for (String subdir : path) {
            dir = new File(dir, subdir);
        }
        storeDirectory = dir;
    }

    if (!storeDirectory.exists() && !storeDirectory.mkdirs()) {
        throw new IllegalStateException(
                "Unable to create Environment directory: '" + storeDirectory.getAbsolutePath() + "'");
    }
    EnvironmentConfig envCfg;
    if (this.forceConfig == null) {
        File conf = new File(storeDirectory, "je.properties");
        if (!conf.exists()) {
            String resource = stagingDatabase ? "je.properties.staging" : "je.properties.objectdb";
            ByteSource from = Resources.asByteSource((getClass().getResource(resource)));
            try {
                from.copyTo(Files.asByteSink(conf));
            } catch (IOException e) {
                Throwables.propagate(e);
            }
        }

        // use the default settings
        envCfg = new EnvironmentConfig();
        envCfg.setAllowCreate(true);
        envCfg.setCacheMode(CacheMode.MAKE_COLD);
        envCfg.setLockTimeout(5, TimeUnit.SECONDS);
        envCfg.setDurability(Durability.COMMIT_SYNC);
        // envCfg.setReadOnly(readOnly);
    } else {
        envCfg = this.forceConfig;
    }

    // // envCfg.setSharedCache(true);
    // //
    // final boolean transactional = false;
    // envCfg.setTransactional(transactional);
    // envCfg.setCachePercent(75);// Use up to 50% of the heap size for the shared db cache
    // envCfg.setConfigParam(EnvironmentConfig.LOG_FILE_MAX, String.valueOf(256 * 1024 * 1024));
    // // check <http://www.oracle.com/technetwork/database/berkeleydb/je-faq-096044.html#35>
    // envCfg.setConfigParam("je.evictor.lruOnly", "false");
    // envCfg.setConfigParam("je.evictor.nodesPerScan", "100");
    //
    // envCfg.setConfigParam(EnvironmentConfig.CLEANER_MIN_UTILIZATION, "25");
    // envCfg.setConfigParam(EnvironmentConfig.CHECKPOINTER_HIGH_PRIORITY, "true");
    //
    // envCfg.setConfigParam(EnvironmentConfig.CLEANER_THREADS, "4");
    // // TODO: check whether we can set is locking to false
    // envCfg.setConfigParam(EnvironmentConfig.ENV_IS_LOCKING, String.valueOf(transactional));
    //
    // envCfg.setConfigParam(EnvironmentConfig.ENV_RUN_CHECKPOINTER,
    // String.valueOf(!transactional));
    // envCfg.setConfigParam(EnvironmentConfig.ENV_RUN_CLEANER, String.valueOf(!transactional));
    //
    // // envCfg.setConfigParam(EnvironmentConfig.ENV_RUN_EVICTOR, "false");

    Environment env;
    try {
        env = new Environment(storeDirectory, envCfg);
    } catch (RuntimeException lockedEx) {
        // lockedEx.printStackTrace();
        if (readOnly) {
            // this happens when trying to open the env in read only mode when its already open
            // in read/write mode inside the same process. So we re-open it read-write but the
            // database itself will be open read-only by JEObjectDatabase.
            envCfg.setReadOnly(true);
            env = new Environment(storeDirectory, envCfg);
        } else {
            throw lockedEx;
        }
    }
    return env;
}

From source file:org.apache.crunch.test.TemporaryPath.java

private static void copy(String resourceName, File dest) throws IOException {
    Resources.asByteSource(Resources.getResource(resourceName)).copyTo(Files.asByteSink(dest));
}

From source file:org.n52.youngs.transform.impl.YamlMappingConfiguration.java

public YamlMappingConfiguration(String fileName, XPathHelper xpathHelper) throws IOException {
    this(Resources.asByteSource(Resources.getResource(fileName)).openStream(), xpathHelper);
    log.info("Created configuration from filename {}", fileName);
}

From source file:org.spka.cursus.publish.website.results.ResultsPagesGenerator.java

public ResultsPagesGenerator(File scoresFile) throws IOException, ImportException, ExportException {
    ScoresXMLFile scores = new TransformResults(Files.asByteSource(scoresFile));
    XSLTHTMLGenerator gen = new XSLTHTMLGenerator(Constants.DATA_FILE_PREFIX + scoresFile.getName(),
            Files.getNameWithoutExtension(scoresFile.getName()), scores);

    gen.getFooters().add("footer.xml");
    gen.getStyleSheets().add("spka.css");
    if (scores.getData().getSeries().getName().startsWith("Celtic Challenge ")) {
        gen.getStyleSheets().add("spka-cc.css");
    }/* w  w w  . j  a v  a 2 s .  c  o m*/
    gen.getFlags().put("compact-race", "10");
    gen.getFlags().put("compact-event", "10");
    if (Constants.TOP_COUNTRY_SCORERS.contains(scores.getData().getSeriesResults().getScorer())) {
        gen.getFlags().put("top-country", null);
    }

    Map<String, String> classes = new TreeMap<String, String>(
            Ordering.explicit(new ArrayList<String>(CLASSES.keySet())));
    for (DataXMLClass class_ : scores.getData().getSeries().getClasses()) {
        if (CLASSES.containsKey(class_.getName())) {
            classes.put(class_.getName(), CLASSES.get(class_.getName()));
        }
    }
    gen.getClasses().putAll(classes);

    ByteArrayOutputStream buf = new ByteArrayOutputStream();
    scores.to(buf);
    buf.close();
    pages.put(Constants.RESULTS_DIR + "/" + Constants.DATA_FILE_PREFIX + scoresFile.getName(),
            ByteSource.wrap(buf.toByteArray()));

    for (String styleSheet : gen.getStyleSheets()) {
        pages.put(Constants.RESULTS_DIR + "/" + styleSheet,
                Resources.asByteSource(Resources.getResource(Constants.RESOURCE_PATH + styleSheet)));
    }

    for (Map.Entry<String, ByteSource> page : Iterables.concat(gen.getMenuPage().entrySet(),
            gen.getSimplePage().entrySet(), gen.getSplitPages().entrySet(), gen.getCodePages().entrySet())) {
        pages.put(Constants.RESULTS_DIR + "/" + page.getKey(), page.getValue());
    }
}

From source file:org.locationtech.geogig.cli.Logging.java

@Nullable
private static URL getOrCreateLoggingConfigFile(final File geogigdir) {

    final File logsDir = new File(geogigdir, "log");
    if (!logsDir.exists() && !logsDir.mkdir()) {
        return null;
    }/*from w  w w  .j av  a  2 s.  c o m*/
    final File configFile = new File(logsDir, "logback.xml");
    if (configFile.exists()) {
        try {
            return configFile.toURI().toURL();
        } catch (MalformedURLException e) {
            throw Throwables.propagate(e);
        }
    }
    ByteSource from;
    final URL resource = GeogigCLI.class.getResource("logback_default.xml");
    try {
        from = Resources.asByteSource(resource);
    } catch (NullPointerException npe) {
        LOGGER.warn("Couldn't obtain default logging configuration file");
        return null;
    }
    try {
        from.copyTo(Files.asByteSink(configFile));
        return configFile.toURI().toURL();
    } catch (Exception e) {
        LOGGER.warn("Error copying logback_default.xml to {}. Using default configuration.", configFile, e);
        return resource;
    }
}

From source file:com.opengamma.strata.collect.io.ResourceLocator.java

/**
 * Creates a resource from a {@code URL}.
 *
 * @param url  path to the file to wrap/*from   www . jav a 2 s  .c o  m*/
 * @return the resource locator
 */
public static ResourceLocator ofUrl(URL url) {
    ArgChecker.notNull(url, "url");
    String filename = url.toString();
    return new ResourceLocator(URL_PREFIX + filename, Resources.asByteSource(url));
}

From source file:talkeeg.bf.schema.SchemaSource.java

public static Schema fromResource(String resourceUri) throws Exception {
    final URL url = Resources.getResource(resourceUri);
    final ByteSource bs = Resources.asByteSource(url);
    try (InputStream is = bs.openStream()) {
        return fromInputStream(is);
    }//from   www  .ja  v a2s.c om
}