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

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

Introduction

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

Prototype

public static byte[] readFileToByteArray(File file) throws IOException 

Source Link

Document

Reads the contents of a file into a byte array.

Usage

From source file:com.aboutdata.service.bean.ImageGraphicsServiceImpl.java

@Override
public byte[] scale(byte[] input, int height, int width) {
    File inputFile = null;/*w ww .j a v  a 2  s. c o m*/
    File outputFile = null;
    try {
        inputFile = File.createTempFile("input", ".tmp");
        outputFile = File.createTempFile("output", ".tmp");

        FileUtils.writeByteArrayToFile(inputFile, input);

        IMOperation op = new IMOperation();
        op.addImage(inputFile.getAbsolutePath());
        //op.size(width, height); ?? ?
        op.resize(width, height);
        op.quality(95d);
        op.addImage(outputFile.getAbsolutePath());
        logger.debug("Command will be {}", op);
        cmd.run(op);
        return FileUtils.readFileToByteArray(outputFile);
    } catch (IOException | InterruptedException | IM4JavaException ex) {
        ex.printStackTrace();
    } finally {
        inputFile.delete();
        outputFile.delete();
    }
    return null;
}

From source file:com.zacwolf.commons.crypto.Crypter_AES.java

/**
 * @param keyfile// w  w  w  . j  av a 2s.  c  o  m
 * @param cipher
 * @param salter
 * @throws IOException
 */
public Crypter_AES(final File keyfile, final String cipher, final SecureRandom salter) throws IOException {
    this(FileUtils.readFileToByteArray(keyfile), cipher, salter);
}

From source file:com.huawei.ais.demo.TokenDemo.java

/**
 * ?Base64???Token???/*from  w w w  .j av  a2 s .  co  m*/
 * @param token token?
 * @param formFile 
 * @throws IOException
 */
public static void requestOcrIDCardBase64(String token, String formFile) {

    // 1.????
    String url = "https://ais.cn-north-1.myhuaweicloud.com/v1.0/ocr/id-card";
    Header[] headers = new Header[] { new BasicHeader("X-Auth-Token", token),
            new BasicHeader("Content-Type", ContentType.APPLICATION_JSON.toString()) };
    try {
        byte[] fileData = FileUtils.readFileToByteArray(new File(formFile));
        String fileBase64Str = Base64.encodeBase64String(fileData);
        JSONObject json = new JSONObject();
        json.put("image", fileBase64Str);

        //
        // ?????????
        // "side"?"front", "back"""?""??
        //
        json.put("side", "front");

        StringEntity stringEntity = new StringEntity(json.toJSONString(), "utf-8");

        // 2.???, POST??
        HttpResponse response = HttpClientUtils.post(url, headers, stringEntity);
        System.out.println(response);
        String content = IOUtils.toString(response.getEntity().getContent());
        System.out.println(content);
    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:io.jenkins.blueocean.blueocean_git_pipeline.GitCloneReadSaveRequest.java

@Override
void save() throws IOException {
    try {/*  w w w.  j  a  v a 2s .  co m*/
        GitClient git = cloneRepo();
        try {
            git.checkoutBranch(sourceBranch, "origin/" + sourceBranch);
        } catch (Exception e) {
            throw new RuntimeException("Branch not found: " + sourceBranch);
        }
        if (!sourceBranch.equals(branch)) {
            //git.branch(branch);
            git.checkoutBranch(branch, "origin/" + sourceBranch);
        }
        File f = new File(repositoryPath, filePath);
        // commit will fail if the contents hasn't changed
        if (!f.exists() || !Arrays.equals(FileUtils.readFileToByteArray(f), contents)) {
            FileUtils.writeByteArrayToFile(f, contents);
            git.add(filePath);
            git.commit(commitMessage);
        }
        git.push().ref(branch).to(new URIish(gitSource.getRemote())).execute();
    } catch (InterruptedException | GitException | URISyntaxException ex) {
        throw new ServiceException.UnexpectedErrorException("Unable to save " + filePath, ex);
    } finally {
        cleanupRepo();
    }
}

From source file:com.ibm.liberty.starter.ProjectConstructor.java

private void addDynamicPackages() throws IOException {
    log.log(Level.FINE, "Entering method ProjectConstructor.addDynamicPackages()");
    if (inputData.workspaceDirectory == null || inputData.workspaceDirectory.isEmpty()
            || !(new File(inputData.workspaceDirectory).exists())) {
        log.log(Level.FINE,/* ww w.  j  ava  2  s.c  o m*/
                "No dynamic packages to add since workspace doesn't exist : " + inputData.workspaceDirectory);
        return;
    }

    for (Service service : inputData.services.getServices()) {
        String serviceId = service.getId();
        String packageLocation = inputData.workspaceDirectory + "/" + serviceId + "/" + StarterUtil.PACKAGE_DIR;
        File packageDir = new File(packageLocation);

        if (packageDir.exists() && packageDir.isDirectory()) {
            log.log(Level.FINE,
                    "Package directory for " + serviceId + " technology exists : " + packageLocation);
            List<File> filesListInDir = new ArrayList<File>();
            StarterUtil.populateFilesList(packageDir, filesListInDir);

            for (File aFile : filesListInDir) {
                String path = aFile.getAbsolutePath().replace('\\', '/').replace(packageLocation, "");

                if (path.startsWith("/")) {
                    path = path.substring(1);
                }
                putFileInMap(path, FileUtils.readFileToByteArray(aFile));
                log.log(Level.FINE, "Packaged file " + aFile.getAbsolutePath() + " to " + path);
            }
        }
    }
    log.log(Level.FINE, "Exiting method ProjectConstructor.addDynamicPackages()");
}

From source file:io.hakbot.providers.nessus.NessusProvider.java

@Override
public void getResult(Job job) {
    // Retrieve the remote instance defined during initialization
    final RemoteInstance remoteInstance = getRemoteInstance(job);
    try {/*from   w  w  w  .jav  a 2  s.c  om*/
        final ScanClientV6 scan = (ScanClientV6) ClientFactory.createScanClient(remoteInstance.getUrl(), 6,
                !remoteInstance.isValidateCertificates());
        scan.login(remoteInstance.getUsername(), remoteInstance.getPassword());
        final String scanId = getJobProperty(job, NessusConstants.PROP_SCAN_ID);
        final File report = scan.download(Integer.parseInt(scanId), ExportFormat.NESSUS,
                Paths.get(System.getProperty("java.io.tmpdir")));
        if (report.exists()) {
            // Convert result to byte array and save it
            final byte[] result = FileUtils.readFileToByteArray(report);
            addArtifact(job, JobArtifact.Type.PROVIDER_RESULT, JobArtifact.MimeType.XML.value(), result,
                    job.getUuid() + ".nessus");
            // Cleanup and logout
            report.delete();
            scan.logout();
        } else {
            updateState(job, State.FAILED, "Unable to download or save Nessus report");
        }
    } catch (LoginException e) {
        updateState(job, State.FAILED, "Unable to login to Nessus");
    } catch (IOException e) {
        updateState(job, State.FAILED, "IOException - Possibly due to downloading report");
    }
}

From source file:cn.mypandora.controller.BaseUserController.java

/**
 * /*from www . j  a  v  a 2 s  . c  o m*/
 */
@ApiOperation(value = "")
@RequestMapping(value = "/down/{currentPage}", method = RequestMethod.GET)
public ResponseEntity<byte[]> down(@PathVariable int currentPage, HttpServletRequest request)
        throws IOException {
    // ???Excel?
    PageInfo<BaseUser> page = new PageInfo<>();
    page.setPageNum(currentPage);
    page = baseUserService.findPageUserByCondition("pageUsers", null, page);
    // ???
    String rootpath = request.getSession().getServletContext().getRealPath("/");
    String fileName = MyDateUtils.getCurrentDate() + XLSX;
    MyExcelUtil.writeExcel(rootpath + "download" + fileName, "sheet1", "ID,??,,,",
            page.getList(), BaseUser.class, "id,username,sex,birthday,credits");
    // 
    File file = new File(rootpath + "download" + fileName);
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
    headers.setContentDispositionFormData("attachment", fileName);
    return new ResponseEntity<>(FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED);
}

From source file:fm.last.moji.integration.MojiFileIT.java

@Test
public void copyToFile() throws IOException {
    MojiFile copyFile = getFile(newKey("mogileFileCopyToFile"));

    File file = testFolder.newFile(newKey() + ".dat");
    copyFile.copyToFile(file);//from  ww  w  .  j  a v a  2 s. c om

    byte[] actualData = FileUtils.readFileToByteArray(file);

    File original = new File("src/test/data/mogileFileCopyToFile.dat");
    byte[] expectedData = FileUtils.readFileToByteArray(original);
    assertArrayEquals(expectedData, actualData);
}

From source file:com.goodformobile.build.mobile.PreverifyMojoTest.java

private void assertFilesArePreverified(File inputClass, File outputClass) throws IOException {

    assertNotNull("Unable to find original input class: " + inputClass.getAbsolutePath(), inputClass.exists());
    assertNotNull("Unable to find preverified output class: " + outputClass.getAbsolutePath(),
            outputClass.exists());//from w  w  w.  j  a  va  2s . c om

    assertNotSame("Input and output class should not have the same last modified time.",
            inputClass.lastModified(), outputClass.lastModified());

    byte[] inputClassContents = FileUtils.readFileToByteArray(inputClass);
    byte[] outputClassContents = FileUtils.readFileToByteArray(outputClass);
    if (inputClassContents.length == outputClassContents.length) {
        boolean bytesDiffer = false;
        for (int i = 0; i < inputClassContents.length; i++) {
            if (inputClassContents[i] != outputClassContents[i]) {
                bytesDiffer = true;
                break;
            }
        }
        assertFalse("The input class and output class are identical.  This was likely not preverified.",
                bytesDiffer);
    }
}

From source file:com.jhash.oimadmin.Utils.java

public static void createJarFileFromDirectory(String directory, String jarFileName) {
    File jarDirectory = new File(directory);
    try (JarOutputStream jarFileOutputStream = new JarOutputStream(new FileOutputStream(jarFileName))) {
        for (Iterator<File> fileIterator = FileUtils.iterateFiles(jarDirectory, null, true); fileIterator
                .hasNext();) {/*www  .  ja va  2s.com*/
            File inputFile = fileIterator.next();
            String inputFileName = inputFile.getAbsolutePath();
            String directoryFileName = jarDirectory.getAbsolutePath();
            String relativeInputFileName = inputFileName.substring(directoryFileName.length() + 1);
            JarEntry newFileEntry = new JarEntry(relativeInputFileName);
            newFileEntry.setTime(System.currentTimeMillis());
            jarFileOutputStream.putNextEntry(newFileEntry);
            jarFileOutputStream.write(FileUtils.readFileToByteArray(inputFile));
        }
    } catch (Exception exception) {
        throw new OIMAdminException(
                "Failed to create the jar file " + jarFileName + " from directory " + directory, exception);
    }
}