List of usage examples for com.google.common.io Resources toByteArray
public static byte[] toByteArray(URL url) throws IOException
From source file:com.khannedy.sajikeun.servlet.AssetServlet.java
private Asset loadAsset(String key) throws URISyntaxException, IOException { checkArgument(key.startsWith(uriPath)); File file = new File(resourcePath, key); if (file.isDirectory()) { if (indexFile != null) { file = new File(file, indexFile); } else {/* w w w. ja v a 2 s . c o m*/ // directory requested but no index file defined logger.info("[FAILED] " + file.getAbsolutePath()); return null; } } if (!file.exists()) { logger.info("[FAILED] " + file.getAbsolutePath()); return null; } logger.info("[SUCCESS] " + file.getAbsolutePath()); long lastModified = file.lastModified(); 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; return new Asset(Resources.toByteArray(file.toURI().toURL()), lastModified); }
From source file:domainapp.app.services.export.PublishContributionsForSupplier.java
private void initializeIfNecessary() { if (wordprocessingMLPackage == null) { try {//from ww w .j a v a 2s. c om final byte[] bytes = Resources .toByteArray(Resources.getResource(this.getClass(), "SupplierReport.docx")); wordprocessingMLPackage = docxService.loadPackage(new ByteArrayInputStream(bytes)); } catch (IOException | LoadTemplateException e) { throw new RuntimeException(e); } } }
From source file:domainapp.app.services.export.PublishContributionsForOrder.java
private void initializeIfNecessary() { if (wordprocessingMLPackage == null) { try {/*from w ww .j a v a2 s.co m*/ final byte[] bytes = Resources .toByteArray(Resources.getResource(this.getClass(), "OrderReport.docx")); wordprocessingMLPackage = docxService.loadPackage(new ByteArrayInputStream(bytes)); } catch (IOException | LoadTemplateException e) { throw new RuntimeException(e); } } }
From source file:org.apache.hive.ptest.api.client.PTestClient.java
public boolean testStart(String profile, String testHandle, String jira, String patch, boolean clearLibraryCache) throws Exception { patch = Strings.nullToEmpty(patch).trim(); if (!patch.isEmpty()) { byte[] bytes = Resources.toByteArray(new URL(patch)); if (bytes.length == 0) { throw new IllegalArgumentException("Patch " + patch + " was zero bytes"); }/* w ww.jav a 2s . co m*/ } TestStartRequest startRequest = new TestStartRequest(profile, testHandle, jira, patch, clearLibraryCache); post(startRequest, false); boolean result = false; try { result = testTailLog(testHandle); if (testOutputDir != null) { downloadTestResults(testHandle, testOutputDir); } } finally { System.out.println("\n\nLogs are located: " + mLogsEndpoint + testHandle + "\n\n"); } return result; }
From source file:domainapp.app.services.export.PublishContributionsForMenu.java
private void initializeIfNecessary() { if (wordprocessingMLPackage == null) { try {/*from w w w . j av a 2 s . co m*/ final byte[] bytes = Resources .toByteArray(Resources.getResource(this.getClass(), "MenuReport.docx")); wordprocessingMLPackage = docxService.loadPackage(new ByteArrayInputStream(bytes)); } catch (IOException | LoadTemplateException e) { throw new RuntimeException(e); } } }
From source file:test.APIexample.java
private static void populateFileWithTuneTags(File file, Track track) throws IOException { try {/* www . j av a 2 s.co m*/ AudioFile f = AudioFileIO.read(file); Tag tag = f.getTag(); if (tag == null) { tag = new ID3v24Tag(); } tag.setField(FieldKey.ALBUM, track.getAlbum()); tag.setField(FieldKey.ALBUM_ARTIST, track.getAlbumArtist()); tag.setField(FieldKey.ARTIST, track.getArtist()); tag.setField(FieldKey.COMPOSER, track.getComposer()); tag.setField(FieldKey.DISC_NO, String.valueOf(track.getDiscNumber())); tag.setField(FieldKey.DISC_TOTAL, String.valueOf(track.getTotalDiscCount())); tag.setField(FieldKey.GENRE, track.getGenre()); tag.setField(FieldKey.TITLE, track.getTitle()); tag.setField(FieldKey.TRACK, String.valueOf(track.getTrackNumber())); tag.setField(FieldKey.TRACK_TOTAL, String.valueOf(track.getTotalTrackCount())); tag.setField(FieldKey.YEAR, String.valueOf(track.getYear())); if (track.getAlbumArtRef() != null && !track.getAlbumArtRef().isEmpty()) { AlbumArtRef[] array = track.getAlbumArtRef() .toArray(new AlbumArtRef[track.getAlbumArtRef().size()]); for (int i = 0; i < array.length; i++) { Artwork artwork = new Artwork(); File imageFile = new File( new File(".") + System.getProperty("path.separator") + track.getId() + ".im"); Files.write(Resources.toByteArray(array[i].getUrlAsURI().toURL()), imageFile); artwork.setFromFile(imageFile); tag.addField(artwork); artwork.setFromFile(imageFile); tag.addField(artwork); } } f.setTag(tag); AudioFileIO.write(f); } catch (Exception e) { throw new IOException(e); } }
From source file:org.incode.module.document.fixture.seed.DocumentTypeAndTemplatesApplicableForDemoObjectFixture.java
private static byte[] loadResourceBytes(final String resourceName) { final URL templateUrl = Resources.getResource(DocumentTypeAndTemplatesApplicableForDemoObjectFixture.class, resourceName);/*w w w .j ava2s . c o m*/ try { return Resources.toByteArray(templateUrl); } catch (IOException e) { throw new IllegalStateException(String.format("Unable to read resource URL '%s'", templateUrl)); } }
From source file:org.glowroot.local.ui.ClasspathCache.java
private List<UiAnalyzedMethod> getAnalyzedMethods(URI uri) throws IOException { AnalyzingClassVisitor cv = new AnalyzingClassVisitor(); byte[] bytes = Resources.toByteArray(uri.toURL()); ClassReader cr = new ClassReader(bytes); cr.accept(cv, 0);/*from w w w. j av a2 s.c o m*/ return cv.getAnalyzedMethods(); }
From source file:com.cloudera.livy.client.local.LocalClient.java
private Thread startDriver(final RpcServer rpcServer, final String clientId, final String secret) throws IOException { Runnable runnable;/* www .java 2 s .com*/ final String serverAddress = rpcServer.getAddress(); final String serverPort = String.valueOf(rpcServer.getPort()); if (conf.get(CLIENT_IN_PROCESS) != null) { // Mostly for testing things quickly. Do not do this in production. LOG.warn("!!!! Running remote driver in-process. !!!!"); runnable = new Runnable() { @Override public void run() { List<String> args = Lists.newArrayList(); args.add("--remote-host"); args.add(serverAddress); args.add("--remote-port"); args.add(serverPort); args.add("--client-id"); args.add(clientId); args.add("--secret"); args.add(secret); for (Map.Entry<String, String> e : conf) { String key = e.getKey(); if (!key.startsWith("spark.")) { key = LocalConf.SPARK_CONF_PREFIX + key; } args.add("--conf"); args.add(String.format("%s=%s", key, e.getValue())); } try { RemoteDriver.main(args.toArray(new String[args.size()])); } catch (Exception e) { LOG.error("Error running driver.", e); } } }; } else { // If a Spark installation is provided, use the spark-submit script. Otherwise, call the // SparkSubmit class directly, which has some caveats (like having to provide a proper // version of Guava on the classpath depending on the deploy mode). String sparkHome = conf.get(SPARK_HOME_KEY); if (sparkHome == null) { sparkHome = System.getenv(SPARK_HOME_ENV); } if (sparkHome == null) { sparkHome = System.getProperty(SPARK_HOME_KEY); } String osxTestOpts = ""; if (Strings.nullToEmpty(System.getProperty("os.name")).toLowerCase().contains("mac")) { osxTestOpts = Strings.nullToEmpty(System.getenv(OSX_TEST_OPTS)); } String driverJavaOpts = Joiner.on(" ").skipNulls().join(osxTestOpts, conf.get(DRIVER_OPTS_KEY)); String executorJavaOpts = Joiner.on(" ").skipNulls().join(osxTestOpts, conf.get(EXECUTOR_OPTS_KEY)); // Create a file with all the job properties to be read by spark-submit. Change the // file's permissions so that only the owner can read it. This avoid having the // connection secret show up in the child process's command line. File properties = File.createTempFile("spark-submit.", ".properties"); if (!properties.setReadable(false) || !properties.setReadable(true, true)) { throw new IOException("Cannot change permissions of job properties file."); } properties.deleteOnExit(); Properties allProps = new Properties(); // first load the defaults from spark-defaults.conf if available try { URL sparkDefaultsUrl = Thread.currentThread().getContextClassLoader() .getResource("spark-defaults.conf"); if (sparkDefaultsUrl != null) { LOG.info("Loading spark defaults: " + sparkDefaultsUrl); allProps.load(new ByteArrayInputStream(Resources.toByteArray(sparkDefaultsUrl))); } } catch (Exception e) { String msg = "Exception trying to load spark-defaults.conf: " + e; throw new IOException(msg, e); } // then load the SparkClientImpl config for (Map.Entry<String, String> e : conf) { String key = e.getKey(); if (!key.startsWith("spark.")) { key = LocalConf.SPARK_CONF_PREFIX + key; } allProps.put(key, e.getValue()); } allProps.put(LocalConf.SPARK_CONF_PREFIX + CLIENT_ID.key, clientId); allProps.put(LocalConf.SPARK_CONF_PREFIX + CLIENT_SECRET.key, secret); allProps.put(DRIVER_OPTS_KEY, driverJavaOpts); allProps.put(EXECUTOR_OPTS_KEY, executorJavaOpts); Writer writer = new OutputStreamWriter(new FileOutputStream(properties), Charsets.UTF_8); try { allProps.store(writer, "Spark Context configuration"); } finally { writer.close(); } // Define how to pass options to the child process. If launching in client (or local) // mode, the driver options need to be passed directly on the command line. Otherwise, // SparkSubmit will take care of that for us. String master = conf.get("spark.master"); Preconditions.checkArgument(master != null, "spark.master is not defined."); List<String> argv = Lists.newArrayList(); if (sparkHome != null) { argv.add(new File(sparkHome, "bin/spark-submit").getAbsolutePath()); } else { LOG.info("No spark.home provided, calling SparkSubmit directly."); argv.add(new File(System.getProperty("java.home"), "bin/java").getAbsolutePath()); if (master.startsWith("local") || master.startsWith("mesos") || master.endsWith("-client") || master.startsWith("spark")) { String mem = conf.get("spark.driver.memory"); if (mem != null) { argv.add("-Xms" + mem); argv.add("-Xmx" + mem); } String cp = conf.get("spark.driver.extraClassPath"); if (cp != null) { argv.add("-classpath"); argv.add(cp); } String libPath = conf.get("spark.driver.extraLibPath"); if (libPath != null) { argv.add("-Djava.library.path=" + libPath); } String extra = conf.get(DRIVER_OPTS_KEY); if (extra != null) { for (String opt : extra.split("[ ]")) { if (!opt.trim().isEmpty()) { argv.add(opt.trim()); } } } } argv.add("org.apache.spark.deploy.SparkSubmit"); } if (master.equals("yarn-cluster")) { String executorCores = conf.get("spark.executor.cores"); if (executorCores != null) { argv.add("--executor-cores"); argv.add(executorCores); } String executorMemory = conf.get("spark.executor.memory"); if (executorMemory != null) { argv.add("--executor-memory"); argv.add(executorMemory); } String numOfExecutors = conf.get("spark.executor.instances"); if (numOfExecutors != null) { argv.add("--num-executors"); argv.add(numOfExecutors); } } argv.add("--properties-file"); argv.add(properties.getAbsolutePath()); argv.add("--class"); argv.add(RemoteDriver.class.getName()); String jar = "spark-internal"; String livyJars = conf.get(LIVY_JARS); if (livyJars == null) { String livyHome = System.getenv("LIVY_HOME"); Preconditions.checkState(livyHome != null, "Need one of LIVY_HOME or %s set.", LIVY_JARS.key); File clientJars = new File(livyHome, "client-jars"); Preconditions.checkState(clientJars.isDirectory(), "Cannot find 'client-jars' directory under LIVY_HOME."); List<String> jars = new ArrayList<>(); for (File f : clientJars.listFiles()) { jars.add(f.getAbsolutePath()); } livyJars = Joiner.on(",").join(jars); } String userJars = conf.get(SPARK_JARS_KEY); if (userJars != null) { String allJars = Joiner.on(",").join(livyJars, userJars); conf.set(SPARK_JARS_KEY, allJars); } else { argv.add("--jars"); argv.add(livyJars); } argv.add(jar); argv.add("--remote-host"); argv.add(serverAddress); argv.add("--remote-port"); argv.add(serverPort); LOG.info("Running client driver with argv: {}", Joiner.on(" ").join(argv)); final Process child = new ProcessBuilder(argv.toArray(new String[argv.size()])).start(); int childId = childIdGenerator.incrementAndGet(); redirect("stdout-redir-" + childId, child.getInputStream()); redirect("stderr-redir-" + childId, child.getErrorStream()); runnable = new Runnable() { @Override public void run() { try { int exitCode = child.waitFor(); if (exitCode != 0) { rpcServer.cancelClient(clientId, "Child process exited before connecting back"); LOG.warn("Child process exited with code {}.", exitCode); } } catch (InterruptedException ie) { LOG.warn("Waiting thread interrupted, killing child process."); Thread.interrupted(); child.destroy(); } catch (Exception e) { LOG.warn("Exception while waiting for child process.", e); } } }; } Thread thread = new Thread(runnable); thread.setDaemon(true); thread.setName("Driver"); thread.start(); return thread; }
From source file:gmusic.api.api.impl.GoogleMusicAPI.java
protected File downloadTune(final Tune song) throws MalformedURLException, IOException, URISyntaxException { final File file = new File( storageDirectory.getAbsolutePath() + System.getProperty("path.separator") + song.getId() + ".mp3"); if (!file.exists()) { Files.write(Resources.toByteArray(getTuneURL(song).toURL()), file); }//from ww w . ja v a2s . c o m return file; }