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.platform.middlewares.HTTPFileMiddleware.java

private boolean handlePartialRequest(org.eclipse.jetty.server.Request request, HttpServletResponse response,
        File file) {/*from w ww .  j a  v a2 s  .c  o  m*/
    try {
        String rangeHeader = request.getHeader("range");
        String rangeValue = rangeHeader.trim().substring("bytes=".length());
        int fileLength = (int) file.length();
        int start, end;
        if (rangeValue.startsWith("-")) {
            end = fileLength - 1;
            start = fileLength - 1 - Integer.parseInt(rangeValue.substring("-".length()));
        } else {
            String[] range = rangeValue.split("-");
            start = Integer.parseInt(range[0]);
            end = range.length > 1 ? Integer.parseInt(range[1]) : fileLength - 1;
        }
        if (end > fileLength - 1) {
            end = fileLength - 1;
        }
        if (start <= end) {
            int contentLength = end - start + 1;
            response.setHeader("Content-Length", contentLength + "");
            response.setHeader("Content-Range", "bytes " + start + "-" + end + "/" + fileLength);
            byte[] respBody = Arrays.copyOfRange(FileUtils.readFileToByteArray(file), start, contentLength);
            return BRHTTPHelper.handleSuccess(206, respBody, request, response, detectContentType(file));
        }
    } catch (Exception e) {
        e.printStackTrace();
        try {
            request.setHandled(true);
            response.getWriter().write("Invalid Range Header");
            response.sendError(400, "Bad Request");
        } catch (IOException e1) {
            e1.printStackTrace();
        }

        return true;
    }
    return BRHTTPHelper.handleError(500, "unknown error", request, response);
}

From source file:de.mpg.imeji.test.logic.storage.StorageTest.java

/**
 * Do upload - read - delete methods in a row
 * /* w  w w.ja  v a  2  s.c  o  m*/
 * @param filename
 * @throws ImejiException
 */
private synchronized void uploadReadDelete(String filename) {
    StorageController sc = new StorageController("internal");
    InternalStorageManager manager = new InternalStorageManager();
    // UPLOAD
    File file = ImejiTestResources.getTestPng();
    try {
        UploadResult res = sc.upload(filename, file, "1");
        Assert.assertFalse(res.getOrginal() + " url is same as path",
                res.getOrginal().equals(manager.transformUrlToPath(res.getOrginal())));
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        // READ THE URL
        sc.read(res.getOrginal(), baos, true);
        baos.toByteArray();
        byte[] stored = baos.toByteArray();
        try {
            // Test if the uploaded file is the (i.e has the same hashcode) the
            // one which has been stored
            Assert.assertTrue("Uploaded file has been modified",
                    Arrays.hashCode(FileUtils.readFileToByteArray(file)) == Arrays.hashCode(stored));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        // DELETE THE FILE
        long before = manager.getAdministrator().getNumberOfFiles();
        sc.delete(res.getId());
        long after = manager.getAdministrator().getNumberOfFiles();
        // Test that the file has been correctly deleted (i.e, the number of
        // files in the storage is null)
        Assert.assertEquals(before - 1, after);
        // Assert.assertTrue(Arrays.equals(original, stored));
        // Assert.assertTrue(Arrays.hashCode(original) ==
        // Arrays.hashCode(stored));
    } catch (ImejiException e) {
        LOGGER.info("There has been some upload error in the storage test.");
    }
}

From source file:com.redhat.red.offliner.ftest.DownloadWithRedirectFTest.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!
 *//*from   w w  w . j av  a2s. c  o m*/
@Test
public void run() throws Exception {
    // We only need one repo server.
    ExpectationServer server = new ExpectationServer().start();
    //        TestRepositoryServer server = newRepositoryServer();

    // Generate some test content
    String path = contentGenerator.newArtifactPath("jar");
    byte[] content = contentGenerator.newBinaryContent(1024);

    // register the redirects.
    server.expect("GET", "/" + path, (request, response) -> {
        response.setStatus(302);
        response.setHeader("Location", server.formatUrl("/redir/" + path));
    });

    server.expect("GET", "/" + path + Main.SHA_SUFFIX, (request, response) -> {
        response.setStatus(302);
        response.setHeader("Location", server.formatUrl("/redir/" + path + Main.SHA_SUFFIX));
    });

    server.expect("GET", "/" + path + Main.MD5_SUFFIX, (request, response) -> {
        response.setStatus(302);
        response.setHeader("Location", server.formatUrl("/redir/" + path + Main.MD5_SUFFIX));
    });

    server.expect("HEAD", "/" + path, (request, response) -> {
        response.setStatus(302);
        response.setHeader("Location", server.formatUrl("/redir/" + path));
    });

    server.expect("HEAD", "/" + path + Main.SHA_SUFFIX, (request, response) -> {
        response.setStatus(302);
        response.setHeader("Location", server.formatUrl("/redir/" + path + Main.SHA_SUFFIX));
    });

    server.expect("HEAD", "/" + path + Main.MD5_SUFFIX, (request, response) -> {
        response.setStatus(302);
        response.setHeader("Location", server.formatUrl("/redir/" + path + Main.MD5_SUFFIX));
    });

    // 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("/redir/" + path, 200, new ByteArrayInputStream(content));
    server.expect("/redir/" + path + Main.SHA_SUFFIX, 200, sha1Hex(content));
    server.expect("/redir/" + 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()));

    // 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:io.jenkins.blueocean.blueocean_git_pipeline.GitCloneReadSaveRequest.java

@Override
byte[] read() throws IOException {
    try {/*from   w w  w .  j  ava  2 s. co  m*/
        GitClient git = cloneRepo();
        try {
            // thank you test for how to use something...
            // https://github.com/jenkinsci/git-client-plugin/blob/master/src/test/java/org/jenkinsci/plugins/gitclient/GitClientTest.java#L1108
            git.checkoutBranch(branch, "origin/" + branch);
        } catch (Exception e) {
            throw new RuntimeException("Branch not found: " + branch);
        }
        File f = new File(repositoryPath, filePath);
        if (f.canRead()) {
            return FileUtils.readFileToByteArray(f);
        }
        return null;
    } catch (InterruptedException ex) {
        throw new ServiceException.UnexpectedErrorException("Unable to read " + filePath, ex);
    } finally {
        cleanupRepo();
    }
}

From source file:de.digiway.rapidbreeze.server.model.download.DownloadTest.java

@Test
public void testContent() throws IOException {
    // Dummy content:
    byte[] bytes = new byte[100000];
    random.nextBytes(bytes);//from  w w w  . ja  v  a  2 s. c o  m
    InputStream is = new ByteArrayInputStream(bytes);

    // Mocking provider with:
    when(downloadClient.start(dummyUrl, 0)).thenReturn(is);

    // Mock Url Status:
    when(urlStatus.getFileSize()).thenReturn((long) bytes.length);

    // Download content to temp file:
    Download download = new Download(dummyUrl, tempFile, storageProvider);
    download.start();
    handleUntilStatus(download, DownloadStatus.FINISHED_SUCCESSFUL);

    // Compare content:
    byte[] target = FileUtils.readFileToByteArray(tempFile.toFile());
    assertArrayEquals(bytes, target);
}

From source file:com.joyent.manta.client.MantaClientPutIT.java

@Test
public final void testPutWithMarkSupportedStream() throws IOException, URISyntaxException {
    final String name = UUID.randomUUID().toString();
    final String path = testPathPrefix + name;
    final ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    Assert.assertNotNull(classLoader.getResource(TEST_FILENAME));

    try (InputStream testDataInputStream = classLoader.getResourceAsStream(TEST_FILENAME);
            CountingInputStream countingInputStream = new CountingInputStream(testDataInputStream)) {
        Assert.assertTrue(countingInputStream.markSupported());
        mantaClient.put(path, countingInputStream);
        Assert.assertTrue(mantaClient.existsAndIsAccessible(path));

        File localFile = Paths.get(classLoader.getResource(TEST_FILENAME).toURI()).toFile();
        byte[] expectedBytes = FileUtils.readFileToByteArray(localFile);

        try (MantaObjectInputStream in = mantaClient.getAsInputStream(path)) {
            byte[] actualBytes = IOUtils.readFully(in, (int) localFile.length());
            AssertJUnit.assertArrayEquals(expectedBytes, actualBytes);
        }/*from   ww  w  . j a v  a 2 s .  co  m*/
    }
}

From source file:com.netsteadfast.greenstep.action.CommonUploadFileAction.java

private void upload() throws ControllerException, AuthorityException, ServiceException, IOException, Exception {
    if (this.getUpload() == null) {
        throw new ControllerException(SysMessageUtil.get(GreenStepSysMsgConstants.UPLOAD_FILE_NO_SELECT));
    }//  w  w  w  .  ja  v a2s  .c  o  m
    if (StringUtils.isBlank(this.system) || StringUtils.isBlank(this.type) || !UploadTypes.check(this.type)) {
        throw new ControllerException("System and type is required!");
    }
    String fileName = this.copy2UploadDir();
    SysUploadVO uploadObj = new SysUploadVO();
    uploadObj.setSystem(this.system);
    uploadObj.setSubDir(UploadSupportUtils.getSubDir());
    uploadObj.setType(this.type);
    uploadObj.setFileName(fileName);
    uploadObj.setShowName(this.uploadFileName);
    if (uploadObj.getShowName().length() > 255) {
        uploadObj.setShowName(uploadObj.getShowName().substring(0, 255));
    }
    uploadObj.setIsFile(this.isFile);
    if (!YesNo.YES.equals(this.isFile)) {
        uploadObj.setContent(FileUtils.readFileToByteArray(this.getUpload()));
    }
    DefaultResult<SysUploadVO> result = this.sysUploadService.saveObject(uploadObj);
    this.message = result.getSystemMessage().getValue();
    if (result.getValue() == null) {
        return;
    }
    this.message = this.message + "upload file success!";
    this.success = IS_YES;
    this.uploadOid = result.getValue().getOid();
}

From source file:com.cloudant.sync.util.JSONUtilsTest.java

private byte[] readJsonDataFromFile(String filename) throws IOException {
    byte[] data = FileUtils.readFileToByteArray(new File(filename));
    return data;/*from w w  w .  j av  a 2s  .  com*/
}

From source file:com.mirth.connect.client.ui.TemplatePanel.java

public void drop(DropTargetDropEvent dtde) {
    try {/*w ww. ja v  a2  s. co m*/
        Transferable tr = dtde.getTransferable();

        if (tr.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
            dtde.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
            File file = ((List<File>) tr.getTransferData(DataFlavor.javaFileListFlavor)).get(0);

            String dataType = PlatformUI.MIRTH_FRAME.displayNameToDataType.get(getDataType());
            DataTypeClientPlugin dataTypePlugin = LoadedExtensions.getInstance().getDataTypePlugins()
                    .get(dataType);
            if (dataTypePlugin.isBinary()) {
                byte[] content = FileUtils.readFileToByteArray(file);

                // The plugin should decide how to convert the byte array to string
                pasteBox.setText(dataTypePlugin.getTemplateString(content));
            } else {
                pasteBox.setText(FileUtils.readFileToString(file, UIConstants.CHARSET));
            }

            parent.modified = true;
        }
    } catch (Exception e) {
        dtde.rejectDrop();
    }
}

From source file:br.com.fabiopereira.quebrazip.JavaZipSplitter.java

private static void join() {
    try {// w ww . j a v a  2 s .c  om
        // Escrevendo para simular
        File folder = new File(ORIGEM_PATH);
        File[] files = folder.listFiles(new FileFilter() {
            @Override
            public boolean accept(File file) {
                return !file.getName().endsWith(".zip");
            }
        });
        List<File> fileList = new ArrayList<File>();
        for (File file : files) {
            fileList.add(file);
        }
        Collections.sort(fileList, new Comparator<File>() {
            public int compare(File f1, File f2) {
                int i1 = Integer.parseInt(f1.getName().substring(f1.getName().indexOf(".txt") + 4));
                int i2 = Integer.parseInt(f2.getName().substring(f2.getName().indexOf(".txt") + 4));
                if (i1 == i2) {
                    return 0;
                }
                return i1 < i2 ? -1 : 1;
            };
        });
        // Obtendo tamanho total
        int sizeTotal = 0;
        for (File file : fileList) {
            sizeTotal += file.length();
        }
        byte[] tudao = new byte[sizeTotal];
        int posicao = 0;
        for (File file : fileList) {
            byte[] b = FileUtils.readFileToByteArray(file);
            invertArrayBytes(b);
            int i = 0;
            for (i = posicao; i < posicao + b.length; i++) {
                tudao[i] = (b[i - posicao]);
            }
            posicao = i;
        }
        FileUtils.writeByteArrayToFile(new File(ORIGEM_PATH + "/result.zip"), tudao);
    } catch (Exception e) {
        e.printStackTrace();
    }
}