List of usage examples for org.apache.commons.io FileUtils writeByteArrayToFile
public static void writeByteArrayToFile(File file, byte[] data) throws IOException
From source file:org.cloudifysource.quality.iTests.test.cli.cloudify.util.NewRestTestUtils.java
public static File getMachineDumpFile(final String restUrl, final String ip, final String processors, final long fileZiseLimit, final String errMessageContain) throws IOException, RestClientException, FailedToCreateDumpException, WrongMessageException { // connect to the REST RestClient restClient = createAndConnect(restUrl); // get dump data using REST API GetMachineDumpFileResponse response = null; try {//from w ww .j a v a 2 s .c o m response = restClient.getMachineDumpFile(ip, fileZiseLimit, processors); if (errMessageContain != null) { LogUtils.log("RestClientException expected [" + errMessageContain + "]"); } // write the result data to a temporary file. File file = File.createTempFile("dump", ".zip"); FileUtils.writeByteArrayToFile(file, response.getDumpBytes()); return file; } catch (RestClientException e) { String message = e.getMessageFormattedText(); if (errMessageContain == null) { throw new FailedToCreateDumpException(message); } else { if (!message.contains(errMessageContain)) { throw new WrongMessageException(message, errMessageContain); } return null; } } }
From source file:org.cloudifysource.quality.iTests.test.cli.cloudify.util.NewRestTestUtils.java
public static Map<String, File> getMachinesDumpFile(final String restUrl, final String username, final String password, final String processors, final long fileZiseLimit, final String errMessageContain) throws IOException, RestClientException, WrongMessageException, FailedToCreateDumpException { // connect to the REST RestClient restClient = createAndConnect(restUrl, username, password); // get dump data using REST API GetMachinesDumpFileResponse response; try {// w w w.j a va2 s .com response = restClient.getMachinesDumpFile(processors, fileZiseLimit); if (errMessageContain != null) { Assert.fail("RestClientException expected [" + errMessageContain + "]"); } // write the result data to a temporary file. Map<String, byte[]> dumpBytesPerIP = response.getDumpBytesPerIP(); Map<String, File> dumpFilesPerIP = new HashMap<String, File>(dumpBytesPerIP.size()); for (Entry<String, byte[]> entry : dumpBytesPerIP.entrySet()) { File file = File.createTempFile("dump", ".zip"); file.deleteOnExit(); FileUtils.writeByteArrayToFile(file, entry.getValue()); dumpFilesPerIP.put(entry.getKey(), file); } return dumpFilesPerIP; } catch (RestClientException e) { String message = e.getMessageFormattedText(); if (errMessageContain == null) { throw new FailedToCreateDumpException(message); } else { if (!message.contains(errMessageContain)) { throw new WrongMessageException(message, errMessageContain); } return null; } } }
From source file:org.codice.ddf.commands.catalog.ExportCommand.java
private void signJar(File outputFile) { SecurityLogger.audit("Signing exported data. file: [{}]", outputFile.getName()); console.println("Signing zip file..."); Instant start = Instant.now(); try (InputStream inputStream = new FileInputStream(outputFile)) { String alias = AccessController .doPrivileged((PrivilegedAction<String>) () -> System.getProperty(SystemBaseUrl.EXTERNAL_HOST)); String password = AccessController.doPrivileged( (PrivilegedAction<String>) () -> System.getProperty("javax.net.ssl.keyStorePassword")); byte[] signature = signer.createDigitalSignature(inputStream, alias, password); if (signature != null) { String signatureFilepath = Paths.get(System.getProperty("ddf.home"), FILE_NAMER.apply("sig")) .toString();/*from w w w . j a v a 2 s . c om*/ FileUtils.writeByteArrayToFile(new File(signatureFilepath), signature); console.println("zip file signed in: " + getFormattedDuration(start)); } else { console.println("An error occurred while signing export"); } } catch (CatalogCommandRuntimeException | IOException e) { String message = "Unable to sign export of data"; LOGGER.debug(message, e); console.println(message); } }
From source file:org.commonjava.maven.galley.io.checksum.ChecksummingTransferDecoratorTest.java
@Test public void forceChecksumOnReadWhenChecksumsAreDisabledForReads() throws Exception { fixture.setDecorator(new ChecksummingTransferDecorator(Collections.<TransferOperation>emptySet(), new SpecialPathManagerImpl(), false, false, metadataConsumer, new Md5GeneratorFactory())); fixture.initMissingComponents();/*from www . j a v a 2 s .c om*/ fixture.getCache().startReporting(); String path = "my-path.txt"; final Transfer txfr = fixture.getCache() .getTransfer(new ConcreteResource(new SimpleLocation("test:uri"), path)); File f = new File(temp.getRoot(), "cache/test:uri"); f = new File(f, path); byte[] data = "This is a test with a bunch of data and some other stuff, in a big box sealed with chewing gum" .getBytes(); FileUtils.writeByteArrayToFile(f, data); logger.info("Opening transfer input stream"); EventMetadata forceEventMetadata = new EventMetadata().set(FORCE_CHECKSUM, TRUE); try (InputStream stream = txfr.openInputStream(false, forceEventMetadata)) { logger.info("Reading stream"); byte[] resultData = IOUtils.toByteArray(stream); logger.debug("Result is {} bytes", resultData.length); assertThat(Arrays.equals(resultData, data), equalTo(true)); } final MessageDigest md = MessageDigest.getInstance("MD5"); md.update(data); final byte[] digest = md.digest(); final String digestHex = Hex.encodeHexString(digest); logger.debug("Verifying MD5 in metadata consumer"); TransferMetadata metadata = metadataConsumer.getMetadata(txfr); assertThat(metadata, notNullValue()); Map<ContentDigest, String> digests = metadata.getDigests(); assertThat(digests, CoreMatchers.<Map<ContentDigest, String>>notNullValue()); assertThat(digests.get(MD5), equalTo(digestHex)); }
From source file:org.commonjava.maven.galley.io.checksum.ChecksummingTransferDecoratorTest.java
@Test public void noChecksumOnReadWhenChecksumsAreDisabledForReads() throws Exception { fixture.setDecorator(new ChecksummingTransferDecorator(Collections.<TransferOperation>emptySet(), new SpecialPathManagerImpl(), false, false, metadataConsumer, new Md5GeneratorFactory())); fixture.initMissingComponents();//ww w. ja v a2 s.c o m fixture.getCache().startReporting(); String path = "my-path.txt"; final Transfer txfr = fixture.getCache() .getTransfer(new ConcreteResource(new SimpleLocation("test:uri"), path)); File f = new File(temp.getRoot(), "cache/test:uri"); f = new File(f, path); byte[] data = "This is a test with a bunch of data and some other stuff, in a big box sealed with chewing gum" .getBytes(); FileUtils.writeByteArrayToFile(f, data); logger.info("Opening transfer input stream"); EventMetadata forceEventMetadata = new EventMetadata(); try (InputStream stream = txfr.openInputStream(false, forceEventMetadata)) { logger.info("Reading stream"); byte[] resultData = IOUtils.toByteArray(stream); logger.debug("Result is {} bytes", resultData.length); assertThat(Arrays.equals(resultData, data), equalTo(true)); } logger.debug("Verifying .md5 file is missing"); final Transfer md5Txfr = txfr.getSiblingMeta(".md5"); assertThat(md5Txfr.exists(), equalTo(false)); logger.debug("Verifying MD5 in metadata consumer is missing"); TransferMetadata metadata = metadataConsumer.getMetadata(txfr); assertThat(metadata, nullValue()); }
From source file:org.commonjava.maven.galley.io.checksum.ChecksummingTransferDecoratorTest.java
@Test public void customChecksumReaderFilter() throws Exception { String path = "my-path.txt"; fixture.setDecorator(new ChecksummingTransferDecorator(new TestDecoratorAdvisor(), new DisabledChecksummingDecoratorAdvisor(), new SpecialPathManagerImpl(), metadataConsumer, new Md5GeneratorFactory())); fixture.initMissingComponents();//from w w w .ja va 2 s . c om fixture.getCache().startReporting(); final Transfer txfr = fixture.getCache() .getTransfer(new ConcreteResource(new SimpleLocation("test:uri"), path)); File f = new File(temp.getRoot(), "cache/test:uri"); f = new File(f, path); byte[] data = "This is a test with a bunch of data and some other stuff, in a big box sealed with chewing gum" .getBytes(); FileUtils.writeByteArrayToFile(f, data); EventMetadata em = new EventMetadata(); logger.debug("Reading stream with EventMetadata advice: {}", em.get(DO_CHECKSUMS)); assertRead(txfr, data, em, false, false); em = new EventMetadata().set(DO_CHECKSUMS, ChecksummingDecoratorAdvisor.ChecksumAdvice.CALCULATE_NO_WRITE); logger.debug("Reading stream with EventMetadata advice: {}", em.get(DO_CHECKSUMS)); assertRead(txfr, data, em, false, true); logger.debug("Removing checksum metadata from consumer"); metadataConsumer.removeMetadata(txfr); em = new EventMetadata().set(DO_CHECKSUMS, ChecksummingDecoratorAdvisor.ChecksumAdvice.CALCULATE_AND_WRITE); logger.debug("Reading stream with EventMetadata advice: {}", em.get(DO_CHECKSUMS)); assertRead(txfr, data, em, true, true); }
From source file:org.commonjava.util.partyline.ConcurrentFirstReaderTest.java
/** * GIVEN:/*from w w w .j a v a 2 s . com*/ * <ol> * <li>File exists on disk</li> * <li>File is not opened for reading or writing</li> * <li>The underlying filesystem is slow to respond to lock requests on FileChannel</li> * </ol> * <br/> * WHEN: * <ol> * <li>Two reader threads attempt to open the file at the same time</li> * </ol> * <br/> * THEN: * <ol> * <li>One reader thread should "win" and be the first to open the file</li> * <li>The other reader thread should "join" that first thread's open file</li> * <li>No OverlappingFileLockException should be thrown</li> * </ol> * @throws Exception */ /*@formatter:off*/ @BMRules(rules = { // setup a rendezvous to control thread execution @BMRule(name = "init rendezvous", targetClass = "FileTree", targetMethod = "<init>", targetLocation = "ENTRY", action = "createRendezvous(\"begin\", 2);" + "debug(\"<<<init rendezvous for begin.\")"), // sync up to reduce chances of missing the race condition for the opLock.lock() control. @BMRule(name = "sync FileTree.setOrJoin", targetClass = "FileTree", targetMethod = "setOrJoinFile", targetLocation = "ENTRY", action = "debug(\"Rendezvous read operations.\"); " + "rendezvous(\"begin\"); " + "debug(\"Continue read operations.\");"), // When we try to init a new JoinableFile for INPUT, simulate an IOException from somewhere deeper in the stack. @BMRule(name = "new JoinableFile lock delay", targetClass = "JoinableFile", targetMethod = "<init>", targetLocation = "ENTRY", action = "debug(\"Delaying JoinableFile.init. Lock is: \" + $5); " + "Thread.sleep(500);" + "debug( \"Resuming lock operation.\" );") }) /*@formatter:on*/ @BMUnitConfig(debug = true) @Test public void run() throws Exception { byte[] bytes = new byte[1024 * 1024 * 2]; // let's get some serious data going. Random rand = new Random(); rand.nextBytes(bytes); final ExecutorService execs = Executors.newFixedThreadPool(2); final File f = temp.newFile("child.bin"); FileUtils.writeByteArrayToFile(f, bytes); final CountDownLatch latch = new CountDownLatch(2); final JoinableFileManager manager = new JoinableFileManager(); manager.startReporting(5000, 5000); for (int i = 0; i < 2; i++) { final int k = i; execs.execute(reader(k, manager, f, latch, true)); } latch.await(); }
From source file:org.craftercms.studio.impl.v1.repository.disk.DiskContentRepository.java
@Override public boolean writeContent(String path, InputStream content) { boolean success = true; try {/*from w w w . java2s.com*/ File file = constructRepoPath(path).toFile(); File folder = file.getParentFile(); if (folder != null && !folder.exists()) { folder.mkdirs(); } FileUtils.writeByteArrayToFile(file, IOUtils.toByteArray(content)); } catch (Exception err) { logger.error("error writing file: " + path, err); success = false; } return success; }
From source file:org.craftercms.studio.impl.v1.repository.git.GitContentRepository.java
@Override public boolean writeContent(String site, String path, InputStream content) { boolean success = true; try {// w ww . j a va 2 s . c o m Repository repo; if (StringUtils.isEmpty(site)) { repo = getGlobalConfigurationRepositoryInstance(); } else { repo = getSiteRepositoryInstance(site); } String gitPath = getGitPath(path); RevTree tree = getTree(repo); TreeWalk tw = TreeWalk.forPath(repo, gitPath, tree); FS fs = FS.detect(); File repoRoot = repo.getWorkTree(); Path filePath = null; if (tw == null) { filePath = Paths.get(fs.normalize(repoRoot.getPath()), gitPath); } else { filePath = Paths.get(fs.normalize(repoRoot.getPath()), tw.getPathString()); } if (!Files.exists(filePath)) { filePath = Files.createFile(filePath); Git git = new Git(repo); git.add().addFilepattern(gitPath).call(); } File file = filePath.toFile(); File folder = file.getParentFile(); if (folder != null && !folder.exists()) { folder.mkdirs(); } FileUtils.writeByteArrayToFile(file, IOUtils.toByteArray(content)); } catch (IOException | GitAPIException err) { logger.error("error writing file: site: " + site + " path: " + path, err); success = false; } return success; }
From source file:org.darkstar.batch.utils.DarkstarUtils.java
/** * Method to Load the Batch Configuration Properties, Creating a Config From the Embedded Default If Necessary * @return Configuration Properties/*w ww .j a v a 2 s .c om*/ */ public static Properties loadBatchConfiguration() { Properties config = new Properties(); try { final File configFile = new File("config.properties"); if (!configFile.exists()) { final InputStream configStream = DarkstarUtils.class .getResourceAsStream("/defaultconfig.properties"); final byte[] configBytes = new byte[configStream.available()]; IOUtils.readFully(configStream, configBytes); IOUtils.closeQuietly(configStream); FileUtils.writeByteArrayToFile(configFile, configBytes); } final FileInputStream configStream = new FileInputStream(configFile); config.load(configStream); IOUtils.closeQuietly(configStream); } catch (final Exception e) { throw new RuntimeException("Error Reading Config File!", e); } return config; }