Example usage for org.apache.commons.io FileUtils writeByteArrayToFile

List of usage examples for org.apache.commons.io FileUtils writeByteArrayToFile

Introduction

In this page you can find the example usage for org.apache.commons.io FileUtils writeByteArrayToFile.

Prototype

public static void writeByteArrayToFile(File file, byte[] data) throws IOException 

Source Link

Document

Writes a byte array to a file creating the file if it does not exist.

Usage

From source file:com.hotmart.hot.uploader.rest.UploadRESTTest.java

/**
 * Test of download method, of class UploadREST.
 *//* w  ww. j  ava2 s  . co  m*/
@Test
@InSequence(3)
// @GET @Path("v1/file/download/"+MD5)
public void testDownload(@ArquillianResteasyResource UploadREST uploadREST) throws Exception {

    Response response = uploadREST.download(MD5);
    StreamingOutput fileDownload = (StreamingOutput) response.getEntity();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    fileDownload.write(baos);
    FileUtils.writeByteArrayToFile(new File("./src/test/resources/files/download"), baos.toByteArray());
    assertThat(DigestUtils.md5Hex(baos.toByteArray())).isEqualTo(MD5);
}

From source file:net.netheos.pcsapi.BytesIOTest.java

@Test
public void testFileByteSink() throws Exception {
    String strContent = "This 1 file is the test content of a file byte source... (70 bytes)";
    byte[] byteContent = strContent.getBytes(PcsUtils.UTF8);

    File tmpFile = new File(tmpDir, "byte_sink.txt");
    FileUtils.writeByteArrayToFile(tmpFile, byteContent);

    checkFileByteSinkAllFlags(tmpFile, byteContent);
    checkMemoryByteSink(byteContent);/*from w  ww  .java  2 s.  co  m*/
}

From source file:jp.igapyon.selecrawler.SeleCrawlerWebContentTrimmer.java

public void processFile(final File file) throws IOException {
    String contents = FileUtils.readFileToString(file, "UTF-8");
    contents = SimpleHtmlNormalizerUtil.normalizeHtml(contents);

    final Document document = SimpleMyXmlUtil.string2Document(contents);

    final Element elementRoot = document.getDocumentElement();

    processElement(elementRoot);/*from w w  w . ja  v a 2s . c o  m*/

    try {
        // write xml
        final Transformer transformer = TransformerFactory.newInstance().newTransformer();
        final DOMSource source = new DOMSource(elementRoot);
        final ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        final StreamResult target = new StreamResult(outStream);
        transformer.transform(source, target);

        outStream.flush();

        final File fileNormalTrim = new File(file.getParentFile(),
                file.getName() + SeleCrawlerConstants.EXT_SC_NORMAL_TRIM);
        FileUtils.writeByteArrayToFile(fileNormalTrim,
                SimpleHtmlCleanerNormalizerUtil.normalizeHtml(outStream.toByteArray()));
    } catch (TransformerConfigurationException ex) {
        throw new IOException(ex);
    } catch (TransformerFactoryConfigurationError ex) {
        throw new IOException(ex);
    } catch (TransformerException ex) {
        throw new IOException(ex);
    }
}

From source file:com.netflix.spinnaker.halyard.deploy.spinnaker.v1.service.distributed.google.GoogleProviderUtils.java

static private void ensureSshKeysExist() {
    File sshKeyFile = new File(getSshKeyFile());
    if (!sshKeyFile.exists()) {
        if (!sshKeyFile.getParentFile().exists()) {
            sshKeyFile.getParentFile().mkdirs();
        }/*from   w  w w .  j a  va 2s.  c o m*/

        log.info("Generating a new ssh key file...");
        JobExecutor jobExecutor = DaemonTaskHandler.getJobExecutor();
        List<String> command = new ArrayList<>();
        command.add("ssh-keygen");
        command.add("-N"); // no password
        command.add("");
        command.add("-t"); // rsa key
        command.add("rsa");
        command.add("-f"); // path to keyfile
        command.add(getSshKeyFile());
        command.add("-C"); // username sshing into machine
        command.add("ubuntu");

        JobRequest request = new JobRequest().setTokenizedCommand(command);

        JobStatus status;
        try {
            status = jobExecutor.backoffWait(jobExecutor.startJob(request));
        } catch (InterruptedException e) {
            throw new DaemonTaskInterrupted(e);
        }

        if (status.getResult() == JobStatus.Result.FAILURE) {
            throw new HalException(FATAL, "ssh-keygen failed: " + status.getStdErr());
        }

        try {
            File sshPublicKeyFile = new File(getSshPublicKeyFile());
            String sshKeyContents = IOUtils.toString(new FileInputStream(sshPublicKeyFile));

            if (!sshKeyContents.startsWith("ubuntu:")) {
                sshKeyContents = "ubuntu:" + sshKeyContents;
                FileUtils.writeByteArrayToFile(sshPublicKeyFile, sshKeyContents.getBytes());
            }
        } catch (IOException e) {
            throw new HalException(FATAL,
                    "Cannot reformat ssh key to match google key format expectation: " + e.getMessage(), e);
        }

        command = new ArrayList<>();
        command.add("chmod");
        command.add("400");
        command.add(getSshKeyFile());

        request = new JobRequest().setTokenizedCommand(command);
        try {
            status = jobExecutor.backoffWait(jobExecutor.startJob(request));
        } catch (InterruptedException e) {
            throw new DaemonTaskInterrupted(e);
        }

        if (status.getResult() == JobStatus.Result.FAILURE) {
            throw new HalException(FATAL, "chmod failed: " + status.getStdErr() + status.getStdOut());
        }
    }
}

From source file:controllers.CarOptionValueController.java

@RequestMapping("/updateFromXml")
public String updateFromXml(Map<String, Object> model,
        @RequestParam(value = "oldCcoId", required = false) Long oldCcoId,
        @RequestParam(value = "xlsFile", required = false) MultipartFile file, RedirectAttributes ras)
        throws Exception {
    if (file == null || file.isEmpty()) {
        ras.addFlashAttribute("error", "File not found");
    } else {/*from   w  w w . j  av a2  s.com*/
        File newFile = new File("/usr/local/etc/covs");
        if (newFile.exists()) {
            newFile.delete();
        }
        try {
            FileUtils.writeByteArrayToFile(newFile, file.getBytes());
            carOptionValueService.updateFromXml(newFile);
            ras.addFlashAttribute("error", carOptionValueService.getResult().getErrors());
        } catch (Exception e) {
            List<String> erList = new ArrayList();
            erList.addAll(carOptionValueService.getResult().getErrors());
            erList.add(e.getMessage());
            ras.addFlashAttribute("error",
                    "updateFromXml: " + /*StringAdapter.getStackTraceException(e)*/erList);

        }
        if (newFile.exists()) {
            newFile.delete();
        }
    }
    ras.addAttribute("ccoId", oldCcoId);
    return "redirect:/CarOptionValue/show";
}

From source file:nc.noumea.mairie.appock.services.impl.CatalogueServiceImpl.java

private void creeFichierCoteServeur(PhotoArticleCatalogue photoArticleCatalogue) throws IOException {
    if (photoArticleCatalogue.getContenu() == null) {
        return;//from  w  ww .  j a v a  2 s .  co  m
    }

    FileUtils.writeByteArrayToFile(getFilePieceJointe(photoArticleCatalogue),
            photoArticleCatalogue.getContenu());
}

From source file:com.haulmont.yarg.formatters.impl.inline.HtmlContentInliner.java

private void insertHTML(XText destination, XTextRange textRange, String htmlContent) throws Exception {
    File tempFile = null;/*from ww w. jav a  2 s . com*/
    try {
        tempFile = File.createTempFile(UUID.randomUUID().toString(), ".htm");

        StringBuilder contentBuilder = new StringBuilder();
        contentBuilder.append(ENCODING_HEADER);
        contentBuilder.append(OPEN_HTML_TAGS);
        contentBuilder.append(htmlContent);
        contentBuilder.append(CLOSE_HTML_TAGS);

        FileUtils.writeByteArrayToFile(tempFile, contentBuilder.toString().getBytes());
        String fileUrl = "file:///" + tempFile.getCanonicalPath().replace("\\", "/");

        XTextCursor textCursor = destination.createTextCursorByRange(textRange);
        XDocumentInsertable insertable = as(XDocumentInsertable.class, textCursor);

        insertable.insertDocumentFromURL(fileUrl, new PropertyValue[0]);
    } finally {
        FileUtils.deleteQuietly(tempFile);
    }
}

From source file:com.joyent.manta.client.multipart.TestMultipartManager.java

@Override
public MantaMultipartUploadPart uploadPart(TestMultipartUpload upload, int partNumber, byte[] bytes)
        throws IOException {
    UUID partId = UUID.randomUUID();
    File part = new File(upload.getPartsPath() + File.separator + partNumber);
    File partIdFile = new File(part.getPath() + ".id");
    FileUtils.write(partIdFile, partId.toString(), StandardCharsets.UTF_8);
    FileUtils.writeByteArrayToFile(part, bytes);

    return new MantaMultipartUploadPart(partNumber, upload.getPath(), partId.toString());
}

From source file:controllers.CCOController.java

@RequestMapping("/updateFromXml")
public String updateFromXml(Map<String, Object> model,
        @RequestParam(value = "xlsFile", required = false) MultipartFile file, RedirectAttributes ras) {
    if (file == null || file.isEmpty()) {
        ras.addFlashAttribute("error", "File not found");
    } else {//from  w  w  w  .  jav a  2 s  . c  o m
        File newFile = new File("/usr/local/etc/CCO");
        if (newFile.exists()) {
            newFile.delete();
        }
        try {
            FileUtils.writeByteArrayToFile(newFile, file.getBytes());
            carCompletionOptionService.updateFromXml(newFile);
            ras.addFlashAttribute("error", carCompletionOptionService.getResult().getErrors());
        } catch (Exception e) {
            ras.addFlashAttribute("error", "updateFromXml" + e.getMessage());
        }
        if (newFile.exists()) {
            newFile.delete();
        }
    }
    return "redirect:/CCO/show";
}

From source file:controllers.BaseParamController.java

@RequestMapping("/updateFromXml")
public String updateFromXml(Map<String, Object> model,
        @RequestParam(value = "xlsFile", required = false) MultipartFile file, RedirectAttributes ras) {
    if (file == null || file.isEmpty()) {
        ras.addFlashAttribute("error", "File not found");
    } else {/*from  w  w  w.ja  v  a2 s  .  co  m*/
        File newFile = new File("/usr/local/etc/BaseParamMap");
        if (newFile.exists()) {
            newFile.delete();
        }
        try {
            FileUtils.writeByteArrayToFile(newFile, file.getBytes());
            baseParamService.updateFromXml(newFile);
            ras.addFlashAttribute("error", baseParamService.getResult().getErrors());
        } catch (Exception e) {
            ras.addFlashAttribute("error",
                    "updateFromXml" + StringAdapter.getStackTraceException(e)/*e.getMessage()*/);
        }
        if (newFile.exists()) {
            newFile.delete();
        }
    }
    return "redirect:/BaseParam/show";
}