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.redhat.red.offliner.ftest.SinglePlaintextDownloadOfTarballFTest.java

@Test
public void testGenericTarballDownload() 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();//from  w  w w .  j ava2  s . c  om

    String url = server.formatUrl(path);

    // 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", url, (req, resp) -> {
        //            Content-Length: 47175
        //            Content-Type: application/x-gzip
        resp.setHeader("Content-Encoding", "x-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);
    });

    final PoolingHttpClientConnectionManager ccm = new PoolingHttpClientConnectionManager();
    ccm.setMaxTotal(1);

    final HttpClientBuilder builder = HttpClients.custom().setConnectionManager(ccm);
    CloseableHttpClient client = builder.build();

    HttpGet get = new HttpGet(url);
    //        get.setHeader( "Accept-Encoding", "gzip,deflate" );

    Boolean result = client.execute(get, (response) -> {
        Arrays.stream(response.getAllHeaders()).forEach((h) -> System.out.println("Header:: " + h));

        Header contentEncoding = response.getEntity().getContentEncoding();
        if (contentEncoding == null) {
            contentEncoding = response.getFirstHeader("Content-Encoding");
        }

        System.out.printf("Got content encoding: %s\n",
                contentEncoding == null ? "None" : contentEncoding.getValue());

        byte[] content = IOUtils.toByteArray(response.getEntity().getContent());

        try (TarArchiveInputStream tarIn = new TarArchiveInputStream(
                new GzipCompressorInputStream(new ByteArrayInputStream(content)))) {
            TarArchiveEntry entry = null;
            while ((entry = tarIn.getNextTarEntry()) != null) {
                System.out.printf("Got tar entry: %s\n", entry.getName());
                byte[] entryData = new byte[(int) entry.getSize()];
                int read = tarIn.read(entryData, 0, entryData.length);
            }
        }

        return false;
    });
}

From source file:com.silverpeas.kmelia.export.KmeliaPublicationExporter.java

/**
 * Only the first publication is taken in charge by this exporter.
 * @param descriptor the descriptor providing enough information about the export to perform
 * (document name, user for which the export is, the language in which the export has to be done,
 * ...)// w  ww  .  j av  a2  s  .co  m
 * @param publication the publication to export. If several publications are passed as parameter,
 * only the first one is taken.
 * @throws ExportException if an error occurs while exporting the publication.
 */
@Override
public void export(ExportDescriptor descriptor, KmeliaPublication publication) throws ExportException {
    OutputStream output = descriptor.getOutputStream();
    UserDetail user = descriptor.getParameter(EXPORT_FOR_USER);
    String language = descriptor.getParameter(EXPORT_LANGUAGE);
    String folderId = descriptor.getParameter(EXPORT_TOPIC);
    DocumentFormat targetFormat = DocumentFormat.inFormat(descriptor.getFormat());
    String documentPath = getTemporaryExportFilePathFor(publication);
    File odtDocument = null, exportFile = null;
    try {
        ODTDocumentBuilder builder = anODTDocumentBuilder().forUser(user).inLanguage(language)
                .inTopic(folderId);
        odtDocument = builder.buildFrom(publication, anODTAt(documentPath));
        if (targetFormat != odt) {
            ODTConverter converter = DocumentFormatConverterFactory.getFactory().getODTConverter();
            exportFile = converter.convert(odtDocument, inFormat(targetFormat));
        } else {
            exportFile = odtDocument;
        }
        output.write(FileUtils.readFileToByteArray(exportFile));
        output.flush();
        output.close();
    } catch (IOException ex) {
        throw new ExportException(ex.getMessage(), ex);
    } finally {
        if (odtDocument != null && odtDocument.exists()) {
            odtDocument.delete();
        }
        if (exportFile != null && exportFile.exists()) {
            exportFile.delete();
        }
    }
}

From source file:edu.unc.lib.dl.update.MODSUIPFilterTest.java

@Test
public void addMODSToObjectWithMODS() 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();/* w w w .ja  va2s .co m*/

    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.ADD, 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 originalChildrenCount = uip.getOriginalData()
            .get(ContentModelHelper.Datastream.MD_DESCRIPTIVE.getName()).getChildren().size();
    int incomingChildrenCount = uip.getIncomingData()
            .get(ContentModelHelper.Datastream.MD_DESCRIPTIVE.getName()).getChildren().size();

    filter.doFilter(uip);

    assertEquals(originalChildrenCount, uip.getOriginalData()
            .get(ContentModelHelper.Datastream.MD_DESCRIPTIVE.getName()).getChildren().size());
    assertEquals(incomingChildrenCount, uip.getIncomingData()
            .get(ContentModelHelper.Datastream.MD_DESCRIPTIVE.getName()).getChildren().size());
    assertEquals(incomingChildrenCount + originalChildrenCount, uip.getModifiedData()
            .get(ContentModelHelper.Datastream.MD_DESCRIPTIVE.getName()).getChildren().size());
}

From source file:hu.bme.mit.sette.common.tasks.JaCoCoClassLoader.java

/**
 * Gets the bytes of the corresponding binary file for the specified class.
 *
 * @param className//from   ww  w .  j a  va2s.  c  om
 *            the name of the class
 * @return the bytes in the corresponding binary file or null if the file
 *         was not found
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
public byte[] readBytes(String className) throws IOException {
    Validate.notBlank(className, "The class name must not be blank");

    File file = findBinaryFile(className);

    if (file != null) {
        return FileUtils.readFileToByteArray(file);
    } else {
        return null;
    }
}

From source file:my.jabbr.app.ftpclient.controller.ConfigManager.java

public void copyABEKeys(String defaultScheme, String sourcePKFile, String sourceASKFile, char[] password)
        throws IOException, EncryptionAlgorithmMismatchException, InvalidABEFileFormatException {
    AppConfiguration appConfig = client.getAppConfig();
    try {/*from   w ww . j a  v a  2s.co m*/
        ABEPublicKey pk = JabbrKeyStoreUtils.readPublicKeyFromFile(defaultScheme, sourcePKFile);
        JabbrKeyStoreUtils.writeToFile(pk, appConfig.getPublicEncryptionKeyFile(), defaultScheme);
        byte[] plaintextSecretKeyBytes = FileUtils.readFileToByteArray(new File(sourceASKFile));
        JabbrKeyStoreUtils.pbeEncryptBytes(plaintextSecretKeyBytes, password,
                appConfig.getUserSecretEncryptionKeyFile());

        //ABEUserAttributeSet userAttributes = ABEObjectFactory.createUserAttributeSetObj();
        //ABESecretKey userKey = JabbrKeyStoreUtils.readUserKeyFromFile(defaultScheme, userAttributes, pk, sourceASKFile);
        //JabbrKeyStoreUtils.writeToFile(userKey, appConfig.getUserSecretEncryptionKeyFile(),  defaultScheme, userAttributes);                  
    } catch (NumberFormatException e) {
        e.printStackTrace();
    }

}

From source file:de.undercouch.gradle.tasks.download.ProxyTest.java

/**
 * Tests if a single file can be downloaded through a proxy server
 * @param authenticating true if the proxy should require authentication
 * @param newNonProxyHosts new value of the "http.nonProxyHosts" system property
 * @param expectedProxyCounter number of times the request is expected to hit the proxy
 * @throws Exception if anything goes wrong
 *//*from w ww .  j  ava2s  . c  o  m*/
private void testProxy(boolean authenticating, String newNonProxyHosts, int expectedProxyCounter)
        throws Exception {
    String proxyHost = System.getProperty("http.proxyHost");
    String proxyPort = System.getProperty("http.proxyPort");
    String nonProxyHosts = System.getProperty("http.nonProxyHosts");
    String proxyUser = System.getProperty("http.proxyUser");
    String proxyPassword = System.getProperty("http.proxyPassword");

    startProxy(authenticating);
    try {
        System.setProperty("http.proxyHost", "127.0.0.1");
        System.setProperty("http.proxyPort", String.valueOf(this.proxyPort));
        System.setProperty("http.nonProxyHosts", newNonProxyHosts);

        if (authenticating) {
            System.setProperty("http.proxyUser", PROXY_USERNAME);
            System.setProperty("http.proxyPassword", PROXY_PASSWORD);
        }

        Download t = makeProjectAndTask();
        t.src(makeSrc(TEST_FILE_NAME));
        File dst = folder.newFile();
        t.dest(dst);
        t.execute();

        byte[] dstContents = FileUtils.readFileToByteArray(dst);
        assertArrayEquals(contents, dstContents);
        assertEquals(expectedProxyCounter, proxyCounter);
    } finally {
        stopProxy();
        if (proxyHost == null) {
            System.getProperties().remove("http.proxyHost");
        } else {
            System.setProperty("http.proxyHost", proxyHost);
        }
        if (proxyPort == null) {
            System.getProperties().remove("http.proxyPort");
        } else {
            System.setProperty("http.proxyPort", proxyPort);
        }
        if (nonProxyHosts == null) {
            System.getProperties().remove("http.nonProxyHosts");
        } else {
            System.setProperty("http.nonProxyHosts", nonProxyHosts);
        }
        if (proxyUser == null) {
            System.getProperties().remove("http.proxyUser");
        } else {
            System.setProperty("http.proxyUser", proxyUser);
        }
        if (proxyPassword == null) {
            System.getProperties().remove("http.proxyPassword");
        } else {
            System.setProperty("http.proxyPassword", proxyPassword);
        }
    }
}

From source file:com.adaptris.core.ftp.SftpKeyAuthConnection.java

@Override
protected FileTransferClient create(String remoteHost, int port, UserInfo ui)
        throws IOException, FileTransferException {
    log.debug("Connecting to " + remoteHost + ":" + port + " as user " + ui.getUser());
    SftpClient sftp = new SftpClient(remoteHost, port, socketTimeout(), getSftpConnectionBehaviour());
    sftp.setAdditionalDebug(additionalDebug());
    sftp.setKeepAliveTimeout(keepAlive);
    try {//  w ww. j  a va  2 s. c  o  m
        byte[] privateKey = FileUtils.readFileToByteArray(new File(getPrivateKeyFilename()));
        sftp.connect(ui.getUser(), privateKey, Password.decode(getPrivateKeyPassword()).getBytes());
    } catch (PasswordException e) {
        throw new SftpException(e);
    }
    return sftp;
}

From source file:algorithm.PDFFileAttacher.java

private File copyCarrier(File carrier) throws IOException, FileNotFoundException {
    File outputFile = new File(getOutputFileName(carrier));
    byte[] carrierBytes = FileUtils.readFileToByteArray(carrier);
    FileOutputStream outputStream = new FileOutputStream(outputFile);
    outputStream.write(carrierBytes);//from  ww  w .  j  a va 2  s .  co m
    outputStream.close();
    return outputFile;
}

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

/**
 * ?Base64???Token???//w  w  w.  j a  v  a2  s  . c  o m
 * @param token token?
 * @param formFile 
 * @throws IOException
 */
public static void requestOcrVatInvoiceBase64(String token, String formFile) {

    // 1.????
    String url = "https://ais.cn-north-1.myhuaweicloud.com/v1.0/ocr/vat-invoice";
    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);
        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:com.fengduo.bee.web.controller.product.ProductController.java

/**
 * pdf?/* w w w. j av  a  2s.  co  m*/
 * 
 * @param id
 * @return
 * @throws IOException
 */
@RequestMapping("/item/{id}/download")
public ResponseEntity<byte[]> download(@PathVariable("id") Long id) throws IOException {
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
    headers.setContentDispositionFormData("attachment", ".pdf");
    String name = "";
    name = new String(name.getBytes(), "ISO8859-1");
    headers.set("content-disposition", "attachment;filename=" + name + ".pdf");

    if (Argument.isNotPositive(id)) {
        return new ResponseEntity<byte[]>(null, headers, HttpStatus.CREATED);
    }
    ItemFinance itemFinance = itemService.getItemFinanceByItemId(id);
    if (itemFinance == null) {
        return new ResponseEntity<byte[]>(null, headers, HttpStatus.CREATED);
    }
    String url = itemFinance.getPdfUrl();
    File file = fileService.getFile(url);
    if (file == null) {
        return new ResponseEntity<byte[]>(null, headers, HttpStatus.CREATED);
    }

    return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED);
}