List of usage examples for org.apache.commons.io FileUtils readFileToByteArray
public static byte[] readFileToByteArray(File file) throws IOException
From source file:com.t3.model.AssetLoader.java
/** * <p>// w w w.ja va 2 s.c om * This method extracts an asset map from the given repository. * </p> * <p> * It starts by checking to see if the repository index is already in the * cache. If not, it makes a network connection and grabs it, calling * {@link #storeIndexFile(String, byte[])} to store it into the cache. * </p> * <p> * Once the index file has been located, {@link #parseIndex(List)} is called * to convert the text file into a <code>Map<String, Sting></code> for * the return value. * </p> * * @param repository * @return */ protected Map<String, String> getIndexMap(String repository) { RepoState status = RepoState.ACTIVE; Map<String, String> indexMap = new HashMap<String, String>(); try { byte[] index = null; if (!hasCurrentIndexFile(repository)) { URL url = new URL(repository); index = FileUtil.getBytes(url); storeIndexFile(repository, index); } else { index = FileUtils.readFileToByteArray(getRepoIndexFile(repository)); } indexMap = parseIndex(decode(index)); } catch (MalformedURLException e) { log.error("Invalid repository URL: " + repository, e); status = RepoState.BAD_URL; } catch (IOException e) { log.error("I/O error retrieving/saving index for '" + repository, e); status = RepoState.UNAVAILABLE; } catch (Throwable t) { log.error("Could not retrieve index for '" + repository, t); t.printStackTrace(); status = RepoState.UNAVAILABLE; } repositoryStateMap.put(repository, status); return indexMap; }
From source file:cz.muni.fi.mir.mathmlcanonicalization.MathMLCanonicalizerCommandLineTool.java
private static void canonicalize(File file, File config, boolean dtdInjectionMode, boolean overwrite) throws ConfigException, FileNotFoundException, JDOMException, IOException, ModuleException, XMLStreamException {/*from w w w. jav a 2s . c om*/ assert file != null; // but config can be null MathMLCanonicalizer mlcan; FileInputStream configInputStream; if (config != null) { configInputStream = new FileInputStream(config); mlcan = new MathMLCanonicalizer(configInputStream); } else { mlcan = MathMLCanonicalizer.getDefaultCanonicalizer(); } mlcan.setEnforcingXHTMLPlusMathMLDTD(dtdInjectionMode); if (overwrite) { Logger.getLogger(MathMLCanonicalizerCommandLineTool.class.getName()).log(Level.INFO, "overwriting the file {0}", file.getAbsolutePath()); ByteArrayInputStream source = new ByteArrayInputStream(FileUtils.readFileToByteArray(file)); mlcan.canonicalize(source, new FileOutputStream(file)); } else { mlcan.canonicalize(new FileInputStream(file), System.out); } }
From source file:com.redhat.red.offliner.ftest.SingleFoloRecordDownloadFTest.java
/** * In general, we should only have one test method per functional test. This allows for the best parallelism when we * execute the tests, especially if the setup takes some time. * * @throws Exception In case anything (anything at all) goes wrong! *///ww w . j av a 2 s.co m @Test public void run() throws Exception { // We only need one repo server. TestRepositoryServer server = newRepositoryServer(); // Generate some test content byte[] content = contentGenerator.newBinaryContent(1024); TrackedContentEntryDTO dto = contentGenerator.newRemoteContentEntry(new StoreKey(StoreType.remote, "test"), "jar", server.getBaseUri(), content); TrackedContentDTO record = new TrackedContentDTO(new TrackingKey("test-record"), Collections.emptySet(), Collections.singleton(dto)); String path = dto.getPath(); // Register the generated content by writing it to the path within the repo server's dir structure. // This way when the path is requested it can be downloaded instead of returning a 404. server.registerContent(path, content); server.registerContent(path + Main.SHA_SUFFIX, sha1Hex(content)); server.registerContent(path + Main.MD5_SUFFIX, md5Hex(content)); // Write the plaintext file we'll use as input. File foloRecord = temporaryFolder.newFile("folo." + getClass().getSimpleName() + ".json"); FileUtils.write(foloRecord, objectMapper.writeValueAsString(record)); Options opts = new Options(); opts.setBaseUrls(Collections.singletonList(server.getBaseUri())); // Capture the downloads here so we can verify the content. File downloads = temporaryFolder.newFolder(); opts.setDownloads(downloads); opts.setLocations(Collections.singletonList(foloRecord.getAbsolutePath())); // run `new Main(opts).run()` and return the Main instance so we can query it for errors, etc. Main finishedMain = run(opts); assertThat("Wrong number of downloads logged. Should have been 3 including checksums.", finishedMain.getDownloaded(), equalTo(3)); assertThat("Errors should be empty!", finishedMain.getErrors().isEmpty(), equalTo(true)); File downloaded = new File(downloads, path); assertThat("File: " + path + " doesn't seem to have been downloaded!", downloaded.exists(), equalTo(true)); assertThat("Downloaded file: " + path + " contains the wrong content!", FileUtils.readFileToByteArray(downloaded), equalTo(content)); }
From source file:com.abstratt.graphviz.GraphViz.java
/** * Higher-level API for launching a GraphViz transformation. * /*from w w w . ja v a2s .c o m*/ * @return the resulting image, never <code>null</code> * @throws CoreException * if any error occurs */ public static byte[] load(final InputStream input, String format, int dimensionX, int dimensionY) throws CoreException { MultiStatus status = new MultiStatus(GraphVizActivator.ID, 0, "Errors occurred while running Graphviz", null); File dotInput = null, dotOutput = null; // we keep the input in memory so we can include it in error messages ByteArrayOutputStream dotContents = new ByteArrayOutputStream(); try { // determine the temp input and output locations dotInput = File.createTempFile(TMP_FILE_PREFIX, DOT_EXTENSION); dotOutput = File.createTempFile(TMP_FILE_PREFIX, "." + format); // we created the output file just so we would know an output // location to pass to dot dotOutput.delete(); // dump the contents from the input stream into the temporary file // to be submitted to dot FileOutputStream tmpDotOutputStream = null; try { IOUtils.copy(input, dotContents); tmpDotOutputStream = new FileOutputStream(dotInput); IOUtils.copy(new ByteArrayInputStream(dotContents.toByteArray()), tmpDotOutputStream); } finally { IOUtils.closeQuietly(tmpDotOutputStream); } IStatus result = runDot(format, dimensionX, dimensionY, dotInput, dotOutput); status.add(result); status.add(logInput(dotContents)); if (dotOutput.isFile()) { if (!result.isOK() && Platform.inDebugMode()) LogUtils.log(status); return FileUtils.readFileToByteArray(dotOutput); } } catch (IOException e) { status.add(new Status(IStatus.ERROR, GraphVizActivator.ID, "", e)); } finally { dotInput.delete(); dotOutput.delete(); IOUtils.closeQuietly(input); } throw new CoreException(status); }
From source file:it.anyplace.sync.httprelay.server.RelaySessionConnection.java
private byte[] popTempFile() { try {/* www . j a v a 2 s .com*/ File newFile; synchronized (inputStream) { if (!hasData()) { return new byte[0]; } newFile = createTempFile(); getTempFile().renameTo(newFile); tempFile = null; } byte[] data = FileUtils.readFileToByteArray(newFile); FileUtils.deleteQuietly(newFile); logger.debug("returning {} bytes of data from relay to peer", data.length); return data; } catch (IOException ex) { throw new RuntimeException(ex); } }
From source file:com.omertron.themoviedbapi.AbstractTests.java
/** * Read the object back from a file/*from w w w.j a v a 2 s . c om*/ * * @param <T> * @param filename * @return */ private static <T> T readObject(final String baseFilename) { String filename = baseFilename + FILENAME_EXT; File serFile = new File(filename); if (serFile.exists()) { long diff = System.currentTimeMillis() - serFile.lastModified(); if (diff < TimeUnit.HOURS.toMillis(1)) { LOG.info("File '{}' is current, no need to reacquire", filename); } else { LOG.info("File '{}' is too old, re-acquiring", filename); return null; } } else { LOG.info("File '{}' doesn't exist", filename); return null; } LOG.info("Reading object from '{}'", filename); try { byte[] serObject = FileUtils.readFileToByteArray(serFile); return (T) SerializationUtils.deserialize(serObject); } catch (IOException ex) { LOG.info("Failed to read {}: {}", filename, ex.getMessage(), ex); return null; } }
From source file:com.redhat.red.offliner.ftest.SinglePOMDepsDownloadFTest.java
/** * In general, we should only have one test method per functional test. This allows for the best parallelism when we * execute the tests, especially if the setup takes some time. * * @throws Exception In case anything (anything at all) goes wrong! *///w ww.ja v a2 s .c o m @Test public void run() throws Exception { // We only need one repo server. TestRepositoryServer server = newRepositoryServer(); // Generate some test content byte[] content = contentGenerator.newBinaryContent(1024); Dependency dep = contentGenerator.newDependency(); Model pom = contentGenerator.newPom(); pom.addDependency(dep); String path = contentGenerator.pathOf(dep); // Register the generated content by writing it to the path within the repo server's dir structure. // This way when the path is requested it can be downloaded instead of returning a 404. server.registerContent(path, content); server.registerContent(path + Main.SHA_SUFFIX, sha1Hex(content)); server.registerContent(path + Main.MD5_SUFFIX, md5Hex(content)); // All deps imply an accompanying POM file when using the POM artifact list reader, so we have to register one of these too. Model pomDep = contentGenerator.newPomFor(dep); String pomPath = contentGenerator.pathOf(pomDep); String md5Path = pomPath + Main.MD5_SUFFIX; String shaPath = pomPath + Main.SHA_SUFFIX; String pomStr = contentGenerator.pomToString(pomDep); server.registerContent(pomPath, pomStr); server.registerContent(md5Path, md5Hex(pomStr)); server.registerContent(shaPath, sha1Hex(pomStr)); // Write the plaintext file we'll use as input. File pomFile = temporaryFolder.newFile(getClass().getSimpleName() + ".pom"); FileUtils.write(pomFile, contentGenerator.pomToString(pom)); Options opts = new Options(); opts.setBaseUrls(Collections.singletonList(server.getBaseUri())); // Capture the downloads here so we can verify the content. File downloads = temporaryFolder.newFolder(); opts.setDownloads(downloads); opts.setLocations(Collections.singletonList(pomFile.getAbsolutePath())); // run `new Main(opts).run()` and return the Main instance so we can query it for errors, etc. Main finishedMain = run(opts); assertThat( "Wrong number of downloads logged. Should have been 6 (declared jar + its corresponding POM + 2 checksums each).", finishedMain.getDownloaded(), equalTo(6)); assertThat("Errors should be empty!", finishedMain.getErrors().isEmpty(), equalTo(true)); File downloaded = new File(downloads, path); assertThat("File: " + path + " doesn't seem to have been downloaded!", downloaded.exists(), equalTo(true)); assertThat("Downloaded file: " + path + " contains the wrong content!", FileUtils.readFileToByteArray(downloaded), equalTo(content)); }
From source file:com.redhat.red.offliner.ftest.SinglePlaintextDownloadNoChecksumFTest.java
/** * In general, we should only have one test method per functional test. This allows for the best parallelism when we * execute the tests, especially if the setup takes some time. * * @throws Exception In case anything (anything at all) goes wrong! *///www . jav a2 s . co m @Test public void run() throws Exception { // We only need one repo server. TestRepositoryServer server = newRepositoryServer(); // Generate some test content String path = contentGenerator.newArtifactPath("jar"); byte[] content = contentGenerator.newBinaryContent(1024); // Register the generated content by writing it to the path within the repo server's dir structure. // This way when the path is requested it can be downloaded instead of returning a 404. server.registerContent(path, content); server.registerContent(path + Main.SHA_SUFFIX, sha1Hex(content)); server.registerContent(path + Main.MD5_SUFFIX, md5Hex(content)); // Write the plaintext file we'll use as input. File plaintextList = temporaryFolder.newFile("artifact-list." + getClass().getSimpleName() + ".txt"); String pathWithChecksum = contentGenerator.newPlaintextEntryWithoutChecksum(path); FileUtils.write(plaintextList, pathWithChecksum); Options opts = new Options(); opts.setBaseUrls(Collections.singletonList(server.getBaseUri())); // Capture the downloads here so we can verify the content. File downloads = temporaryFolder.newFolder(); opts.setDownloads(downloads); opts.setLocations(Collections.singletonList(plaintextList.getAbsolutePath())); opts.setConnections(1); // run `new Main(opts).run()` and return the Main instance so we can query it for errors, etc. Main finishedMain = run(opts); ConcurrentHashMap<String, Throwable> errors = finishedMain.getErrors(); System.out.printf("ERRORS:\n\n%s\n\n\n", StringUtils.join(errors.keySet().stream() .map(k -> "ERROR: " + k + ": " + errors.get(k).getMessage() + "\n " + StringUtils.join(errors.get(k).getStackTrace(), "\n ")) .collect(Collectors.toList()), "\n\n")); assertThat("Wrong number of downloads logged. Should have been 3 including checksums.", finishedMain.getDownloaded(), equalTo(3)); assertThat("Errors should be empty!", finishedMain.getErrors().isEmpty(), equalTo(true)); File downloaded = new File(downloads, path); assertThat("File: " + path + " doesn't seem to have been downloaded!", downloaded.exists(), equalTo(true)); assertThat("Downloaded file: " + path + " contains the wrong content!", FileUtils.readFileToByteArray(downloaded), equalTo(content)); }
From source file:com.chiorichan.http.UploadedFile.java
public String readToString() throws IOException { if (isInMemory() || file == null) return SecureFunc.base64Encode(cachedFileUpload.content().array()); else//from ww w. j a v a2 s . co m return SecureFunc.base64Encode(FileUtils.readFileToByteArray(file)); }
From source file:glluch.com.ontotaxoseeker.TermsTest.java
/** * Test of terms method, of class Terms. * @throws java.io.IOException//w w w . ja va2 s .co m * @throws java.io.FileNotFoundException * @throws java.lang.ClassNotFoundException */ @Test public void testTerms() throws IOException, FileNotFoundException, ClassNotFoundException { TermsTest.resetTs(); System.out.println("Terms.terms"); Terms instance = TermsTest.ts; File file = new File("resources/test/testTermsResults.bin"); byte[] v = FileUtils.readFileToByteArray(file); ArrayList<String> expResult = SerializationUtils.deserialize(v); ArrayList<Term> result = instance.terms(); Iterator iter = result.iterator(); ArrayList<String> lemas = new ArrayList<>(); while (iter.hasNext()) { Term next = (Term) iter.next(); lemas.add(next.getLema()); } Object[] lemas1 = lemas.toArray(); Object[] exp = expResult.toArray(); java.util.Arrays.sort(lemas1); java.util.Arrays.sort(exp); //Out.p(lemas1); //Out.p(exp); Assert.assertArrayEquals(exp, lemas1); }