List of usage examples for org.apache.commons.io FileUtils readFileToByteArray
public static byte[] readFileToByteArray(File file) throws IOException
From source file:com.r573.enfili.common.resource.cloud.aws.s3.S3Manager.java
public void uploadFile(String bucketName, String objectName, File file) { try {// w w w . ja v a2s . c om byte[] fileData = FileUtils.readFileToByteArray(file); StorageObject storageObject = new StorageObject(objectName, fileData); s3Client.putObject(bucketName, storageObject); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } catch (ServiceException e) { throw new RuntimeException(e); } }
From source file:com.xpn.xwiki.util.Util.java
/** @deprecated Use {@link org.apache.commons.io.FileUtils#readFileToByteArray(File)} */ @Deprecated/*from w ww.jav a2s . c om*/ public static byte[] getFileContentAsBytes(File file) throws IOException { return FileUtils.readFileToByteArray(file); }
From source file:gov.nih.nci.nbia.wadosupport.WADOSupportDAOImpl.java
@Transactional(propagation = Propagation.REQUIRED) public WADOSupportDTO getWADOSupportForSingleImageDTO(String series, String image, String user) { WADOSupportDTO returnValue = new WADOSupportDTO(); log.info("series-" + series + " image-" + image); try {/* w ww . j av a 2 s. c om*/ List<Object[]> images = this.getHibernateTemplate().getSessionFactory().getCurrentSession() .createSQLQuery(WADO_SINGLE_QUERY).setParameter("series", series).setParameter("image", image) .list(); if (images.size() == 0) { log.info("image not found"); return null; //nothing to do } List<SiteData> authorizedSites; UserObject uo = userTable.get(user); if (uo != null) { authorizedSites = uo.getAuthorizedSites(); if (authorizedSites == null) { AuthorizationManager manager = new AuthorizationManager(user); authorizedSites = manager.getAuthorizedSites(); uo.setAuthorizedSites(authorizedSites); } } else { AuthorizationManager manager = new AuthorizationManager(user); authorizedSites = manager.getAuthorizedSites(); uo = new UserObject(); uo.setAuthorizedSites(authorizedSites); userTable.put(user, uo); } returnValue.setCollection((String) images.get(0)[0]); returnValue.setSite((String) images.get(0)[1]); boolean isAuthorized = false; for (SiteData siteData : authorizedSites) { if (siteData.getCollection().equals(returnValue.getCollection())) { if (siteData.getSiteName().equals(returnValue.getSite())) { isAuthorized = true; break; } } } if (!isAuthorized) { System.out.println("User: " + user + " not authorized"); return null; //not authorized } String filePath = (String) images.get(0)[2]; File imageFile = new File(filePath); if (!imageFile.exists()) { log.error("File " + filePath + " does not exist"); return null; } returnValue.setImage(FileUtils.readFileToByteArray(imageFile)); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } return returnValue; }
From source file:com.redhat.red.offliner.ftest.SinglePlaintextDownloadOfTarballFTest.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 w w. ja v a 2 s .c o m @Test public void run() throws Exception { // Generate some test content String path = contentGenerator.newArtifactPath("tar.gz"); Map<String, byte[]> entries = new HashMap<>(); entries.put(contentGenerator.newArtifactPath("jar"), contentGenerator.newBinaryContent(2400)); entries.put(contentGenerator.newArtifactPath("jar"), contentGenerator.newBinaryContent(2400)); final File tgz = makeTarball(entries); System.out.println("tar content array has length: " + tgz.length()); // We only need one repo server. ExpectationServer server = new ExpectationServer(); server.start(); // 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.expect("GET", server.formatUrl(path), (req, resp) -> { // Content-Length: 47175 // Content-Type: application/x-gzip resp.setHeader("Content-Encoding", "gzip"); resp.setHeader("Content-Type", "application/x-gzip"); byte[] raw = FileUtils.readFileToByteArray(tgz); ByteArrayOutputStream baos = new ByteArrayOutputStream(); GzipCompressorOutputStream gzout = new GzipCompressorOutputStream(baos); gzout.write(raw); gzout.finish(); byte[] content = baos.toByteArray(); resp.setHeader("Content-Length", Long.toString(content.length)); OutputStream respStream = resp.getOutputStream(); respStream.write(content); respStream.flush(); System.out.println("Wrote content with length: " + content.length); }); byte[] content = FileUtils.readFileToByteArray(tgz); server.expect("GET", server.formatUrl(path + Main.SHA_SUFFIX), 200, sha1Hex(content)); server.expect("GET", server.formatUrl(path + Main.MD5_SUFFIX), 200, md5Hex(content)); // Write the plaintext file we'll use as input. File plaintextList = temporaryFolder.newFile("artifact-list." + getClass().getSimpleName() + ".txt"); String pathWithChecksum = contentGenerator.newPlaintextEntryWithChecksum(path, content); 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")); 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 ) ); File tarball = new File(downloads, path); System.out.println("Length of downloaded file: " + tarball.length()); File tmp = new File("/tmp/download.tar.gz"); File tmp2 = new File("/tmp/content.tar.gz"); FileUtils.writeByteArrayToFile(tmp2, content); FileUtils.copyFile(tarball, tmp); try (TarArchiveInputStream tarIn = new TarArchiveInputStream( new GzipCompressorInputStream(new FileInputStream(tarball)))) { TarArchiveEntry entry = null; while ((entry = tarIn.getNextTarEntry()) != null) { byte[] entryData = new byte[(int) entry.getSize()]; int read = tarIn.read(entryData, 0, entryData.length); assertThat("Not enough bytes read for: " + entry.getName(), read, equalTo((int) entry.getSize())); assertThat(entry.getName() + ": data doesn't match input", Arrays.equals(entries.get(entry.getName()), entryData), equalTo(true)); } } assertThat("Wrong number of downloads logged. Should have been 3 including checksums.", finishedMain.getDownloaded(), equalTo(3)); assertThat("Errors should be empty!", errors.isEmpty(), equalTo(true)); }
From source file:com.bittorrent.mpetazzoni.tracker.TrackedTorrent.java
/** * Load a tracked torrent from the given torrent file. * * @param torrent The abstract {@link File} object representing the * <tt>.torrent</tt> file to load. * @throws IOException When the torrent file cannot be read. *//*from w w w .ja v a 2 s .c om*/ public static TrackedTorrent load(File torrent) throws IOException { byte[] data = FileUtils.readFileToByteArray(torrent); return new TrackedTorrent(data); }
From source file:edu.unc.lib.dl.update.MODSUIPFilterTest.java
@Test public void replaceMODSOnObjectWithMODS() throws Exception { InputStream entryPart = new FileInputStream(new File("src/test/resources/atompub/metadataUpdateMODS.xml")); Abdera abdera = new Abdera(); Parser parser = abdera.getParser(); Document<Entry> entryDoc = parser.parse(entryPart); Entry entry = entryDoc.getRoot();/* www.ja va2 s . c om*/ AccessClient accessClient = mock(AccessClient.class); MIMETypedStream modsStream = new MIMETypedStream(); File raf = new File("src/test/resources/testmods.xml"); byte[] bytes = FileUtils.readFileToByteArray(raf); modsStream.setStream(bytes); modsStream.setMIMEType("text/xml"); when(accessClient.getDatastreamDissemination(any(PID.class), eq(ContentModelHelper.Datastream.MD_DESCRIPTIVE.getName()), anyString())).thenReturn(modsStream); PID pid = new PID("uuid:test"); AtomPubMetadataUIP uip = new AtomPubMetadataUIP(pid, "testuser", UpdateOperation.REPLACE, entry); uip.storeOriginalDatastreams(accessClient); assertTrue(uip.getOriginalData().containsKey(ContentModelHelper.Datastream.MD_DESCRIPTIVE.getName())); assertFalse(uip.getModifiedData().containsKey(ContentModelHelper.Datastream.MD_DESCRIPTIVE.getName())); assertTrue(uip.getIncomingData().containsKey(ContentModelHelper.Datastream.MD_DESCRIPTIVE.getName())); int incomingChildrenCount = uip.getIncomingData() .get(ContentModelHelper.Datastream.MD_DESCRIPTIVE.getName()).getChildren().size(); filter.doFilter(uip); for (Object elementObject : uip.getModifiedData() .get(ContentModelHelper.Datastream.MD_DESCRIPTIVE.getName()).getChildren()) { Element element = (Element) elementObject; System.out.println(element.getName()); } XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat()); outputter.output(uip.getModifiedData().get(ContentModelHelper.Datastream.MD_DESCRIPTIVE.getName()), System.out); assertEquals(incomingChildrenCount, uip.getIncomingData() .get(ContentModelHelper.Datastream.MD_DESCRIPTIVE.getName()).getChildren().size()); assertEquals(incomingChildrenCount, uip.getModifiedData() .get(ContentModelHelper.Datastream.MD_DESCRIPTIVE.getName()).getChildren().size()); // Assert that the new modified object isn't the incoming object assertFalse(uip.getModifiedData().get(ContentModelHelper.Datastream.MD_DESCRIPTIVE.getName()) .equals(uip.getIncomingData().get(ContentModelHelper.Datastream.MD_DESCRIPTIVE.getName()))); }
From source file:com.turn.ttorrent.tracker.TrackedTorrent.java
/** * Load a tracked torrent from the given torrent file. * * @param torrent The abstract {@link File} object representing the * <tt>.torrent</tt> file to load. * @throws IOException When the torrent file cannot be read. *///from w ww .j av a2s . c om public static TrackedTorrent load(File torrent) throws IOException, NoSuchAlgorithmException { byte[] data = FileUtils.readFileToByteArray(torrent); return new TrackedTorrent(data); }
From source file:com.sysunite.weaver.nifi.CreateValuePropertyTest.java
@Test public void testOnTrigger() { /********* TEST OUTPUTS ********/ /*******/*from w w w . j av a 2s . c o m*/ * * * /Library/Java/JavaVirtualMachines/jdk1.8.0_60.jdk/Contents/Home/bin/java -ea -Xmx1G -Djava.net.preferIPv4Stack=true -Didea.launcher.port=7535 "-Didea.launcher.bin.path=/Applications/IntelliJ IDEA 14.app/Contents/bin" -Dfile.encoding=UTF-8 -classpath "/Applications/IntelliJ IDEA 14.app/Contents/lib/idea_rt.jar:/Applications/IntelliJ IDEA 14.app/Contents/plugins/junit/lib/junit-rt.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_60.jdk/Contents/Home/lib/ant-javafx.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_60.jdk/Contents/Home/lib/dt.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_60.jdk/Contents/Home/lib/javafx-mx.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_60.jdk/Contents/Home/lib/jconsole.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_60.jdk/Contents/Home/lib/packager.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_60.jdk/Contents/Home/lib/sa-jdi.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_60.jdk/Contents/Home/lib/tools.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_60.jdk/Contents/Home/jre/lib/charsets.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_60.jdk/Contents/Home/jre/lib/deploy.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_60.jdk/Contents/Home/jre/lib/javaws.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_60.jdk/Contents/Home/jre/lib/jce.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_60.jdk/Contents/Home/jre/lib/jfr.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_60.jdk/Contents/Home/jre/lib/jfxswt.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_60.jdk/Contents/Home/jre/lib/jsse.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_60.jdk/Contents/Home/jre/lib/management-agent.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_60.jdk/Contents/Home/jre/lib/plugin.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_60.jdk/Contents/Home/jre/lib/resources.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_60.jdk/Contents/Home/jre/lib/rt.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_60.jdk/Contents/Home/jre/lib/ext/cldrdata.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_60.jdk/Contents/Home/jre/lib/ext/dnsns.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_60.jdk/Contents/Home/jre/lib/ext/jaccess.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_60.jdk/Contents/Home/jre/lib/ext/jfxrt.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_60.jdk/Contents/Home/jre/lib/ext/localedata.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_60.jdk/Contents/Home/jre/lib/ext/nashorn.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_60.jdk/Contents/Home/jre/lib/ext/sunec.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_60.jdk/Contents/Home/jre/lib/ext/sunjce_provider.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_60.jdk/Contents/Home/jre/lib/ext/sunpkcs11.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_60.jdk/Contents/Home/jre/lib/ext/zipfs.jar:/Users/jonathansmit/Documents/nifiproj/weaver-createvalueproperty/nifi-weaver-createvalueproperty-processors/target/test-classes:/Users/jonathansmit/Documents/nifiproj/weaver-createvalueproperty/nifi-weaver-createvalueproperty-processors/target/classes:/Users/jonathansmit/.m2/repository/org/apache/nifi/nifi-api/0.6.0/nifi-api-0.6.0.jar:/Users/jonathansmit/.m2/repository/org/apache/nifi/nifi-processor-utils/0.6.0/nifi-processor-utils-0.6.0.jar:/Users/jonathansmit/.m2/repository/org/apache/nifi/nifi-utils/0.6.0/nifi-utils-0.6.0.jar:/Users/jonathansmit/.m2/repository/org/apache/nifi/nifi-security-utils/0.6.0/nifi-security-utils-0.6.0.jar:/Users/jonathansmit/.m2/repository/org/apache/commons/commons-lang3/3.4/commons-lang3-3.4.jar:/Users/jonathansmit/.m2/repository/commons-io/commons-io/2.4/commons-io-2.4.jar:/Users/jonathansmit/.m2/repository/org/apache/nifi/nifi-mock/0.6.0/nifi-mock-0.6.0.jar:/Users/jonathansmit/.m2/repository/org/apache/nifi/nifi-expression-language/0.6.0/nifi-expression-language-0.6.0.jar:/Users/jonathansmit/.m2/repository/org/antlr/antlr-runtime/3.5.2/antlr-runtime-3.5.2.jar:/Users/jonathansmit/.m2/repository/org/apache/nifi/nifi-data-provenance-utils/0.6.0/nifi-data-provenance-utils-0.6.0.jar:/Users/jonathansmit/.m2/repository/org/slf4j/slf4j-simple/1.7.12/slf4j-simple-1.7.12.jar:/Users/jonathansmit/.m2/repository/org/slf4j/slf4j-api/1.7.12/slf4j-api-1.7.12.jar:/Users/jonathansmit/.m2/repository/junit/junit/4.11/junit-4.11.jar:/Users/jonathansmit/.m2/repository/org/hamcrest/hamcrest-core/1.3/hamcrest-core-1.3.jar:/Users/jonathansmit/.m2/repository/com/jcabi/jcabi-xml/0.17.2/jcabi-xml-0.17.2.jar:/Users/jonathansmit/.m2/repository/com/jcabi/jcabi-log/0.17/jcabi-log-0.17.jar:/Users/jonathansmit/.m2/repository/com/jcabi/jcabi-aspects/0.22/jcabi-aspects-0.22.jar:/Users/jonathansmit/.m2/repository/org/aspectj/aspectjrt/1.8.4/aspectjrt-1.8.4.jar:/Users/jonathansmit/.m2/repository/javax/validation/validation-api/1.1.0.Final/validation-api-1.1.0.Final.jar:/Users/jonathansmit/.m2/repository/com/jcabi/jcabi-immutable/1.4/jcabi-immutable-1.4.jar:/Users/jonathansmit/.m2/repository/com/weaverplatform/sdk-java/1.0/sdk-java-1.0.jar:/Users/jonathansmit/.m2/repository/org/apache/httpcomponents/httpclient/4.4.1/httpclient-4.4.1.jar:/Users/jonathansmit/.m2/repository/org/apache/httpcomponents/httpcore/4.4.1/httpcore-4.4.1.jar:/Users/jonathansmit/.m2/repository/commons-logging/commons-logging/1.2/commons-logging-1.2.jar:/Users/jonathansmit/.m2/repository/commons-codec/commons-codec/1.10/commons-codec-1.10.jar:/Users/jonathansmit/.m2/repository/com/google/code/gson/gson/2.6.2/gson-2.6.2.jar:/Users/jonathansmit/.m2/repository/org/mockito/mockito-core/1.10.19/mockito-core-1.10.19.jar:/Users/jonathansmit/.m2/repository/org/objenesis/objenesis/2.1/objenesis-2.1.jar:/Users/jonathansmit/.m2/repository/org/codehaus/groovy/groovy-all/2.4.5/groovy-all-2.4.5.jar" com.intellij.rt.execution.application.AppMain com.intellij.rt.execution.junit.JUnitStarter -ideVersion5 com.sysunite.weaver.nifi.CreateValuePropertyTest,testOnTrigger contact! RootNode: FunctionalPhysicalObject RootNode (xpath): /FunctionalPhysicalObject RootNode-Attribute: id RootNode-Attribute (xpath): /FunctionalPhysicalObject/@id RootNode-Attribute (value): 816ee370-4274-e211-a3a8-b8ac6f902f00 ChildNode: BeginOfLife ChildNode (xpath): /FunctionalPhysicalObject/BeginOfLife ChildNode-Attribute: value Child-Attribute (xpath): /FunctionalPhysicalObject/BeginOfLife/@value Child-Attribute (value): 2013-12-21 Error, bad response ..linkEntity (local): done! ..linkEntity (remote): done! Error, bad response ..linkEntity (local): done! Error, bad response ..linkEntity (remote): done! aantal gevonden: 1 * * Aan de kant van weaver worden speciale acties niet uitgevoerd voor * EntityType.VALUE_PROPERTY, OBJECT_PROPERTY, COLLECTION, OBJECT; * * * * */ try { String file = "slagboom.xml"; byte[] contents = FileUtils .readFileToByteArray(new File(getClass().getClassLoader().getResource(file).getFile())); InputStream in = new ByteArrayInputStream(contents); InputStream cont = new ByteArrayInputStream(IOUtils.toByteArray(in)); // Generate a test runner to mock a processor in a flow TestRunner runner = TestRunners.newTestRunner(new CreateValueProperty()); // Add properites runner.setProperty(CreateValueProperty.PROP_NODE, "FunctionalPhysicalObject"); runner.setProperty(CreateValueProperty.PROP_NODE_ATTRIBUTE, "id"); runner.setProperty(CreateValueProperty.PROP_CHILDNODE, "BeginOfLife"); runner.setProperty(CreateValueProperty.PROP_CHILDNODE_ATTRIBUTE, "value"); // Add the content to the runner runner.enqueue(cont); // Run the enqueued content, it also takes an int = number of contents queued runner.run(); // All results were processed with out failure //runner.assertQueueEmpty(); // If you need to read or do aditional tests on results you can access the content List<MockFlowFile> results = runner.getFlowFilesForRelationship(CreateValueProperty.MY_RELATIONSHIP); //assertTrue("1 match", results.size() == 1); System.out.println("aantal gevonden: " + results.size()); MockFlowFile result = results.get(0); String resultValue = new String(runner.getContentAsByteArray(result)); //check weaver String checkValue = weaver.get("816ee370-4274-e211-a3a8-b8ac6f902f00").toString(); assertEquals(checkValue, resultValue); //System.out.println("Match: " + IOUtils.toString(runner.getContentAsByteArray(result))); } catch (IOException e) { System.out.println("FOUT!!"); System.out.println(e.getStackTrace()); } catch (NullPointerException e) { System.out.println("weaver connection error (weaver-get)"); } }
From source file:com.palantir.atlasdb.schema.stream.StreamTest.java
private void verifyLoadStreamAsFile(long id, byte[] bytesToStore, GenericStreamStore<Long> store) throws IOException { File file = txManager.runTaskThrowOnConflict(t -> store.loadStreamAsFile(t, id)); Assert.assertArrayEquals(bytesToStore, FileUtils.readFileToByteArray(file)); }
From source file:net.firejack.platform.web.security.x509.KeyUtils.java
public static Properties getProperties(File properties, File keystore) { Properties props = new Properties(); if (!properties.exists()) return props; InputStream stream = null;//from ww w . ja v a 2 s .c om try { byte[] bytes = FileUtils.readFileToByteArray(properties); stream = new ByteArrayInputStream(bytes); if (keystore.exists()) { KeyPair keyPair = load(keystore); try { byte[] decrypt = decrypt(keyPair.getPrivate(), bytes); stream = new ByteArrayInputStream(decrypt); } catch (Exception e) { logger.trace(e); } } props.load(stream); } catch (Exception e) { logger.error(e.getMessage(), e); } finally { IOUtils.closeQuietly(stream); } return props; }