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.cloudant.sync.indexing.IndexManagerIndexTest.java

@Test
public void createLongIndex_indexValueConversionNotSupported_documentShouldNotBeIndexed()
        throws IndexExistsException, SQLException, IOException {
    indexManager.ensureIndexed("class", "class", IndexType.INTEGER);
    Index index = indexManager.getIndex("class");
    byte[] data = FileUtils.readFileToByteArray(new File("fixture/index_string.json"));
    DocumentRevision obj1 = datastore.createDocument(DocumentBodyFactory.create(data));
    IndexTestUtils.assertDBObjectNotInIndex(database, index, obj1);
}

From source file:com.baidu.cc.ConfigLoader.java

/**
 * Read property from local resource file
 * //from   w ww  .  j a  v  a  2  s.  com
 * @param props to merge from local
 * @param localFile local resource file
 * @throws IOException throw all file operation exception
 */
public void readLocal(Properties props, File localFile) throws IOException {
    Assert.notNull(localFile, "Property 'localFile' is null.");
    if (!localFile.exists()) {
        throw new IOException("File not exist. " + localFile.getPath());
    }

    byte[] byteArray = FileUtils.readFileToByteArray(localFile);
    Hex encoder = new Hex();
    try {
        byteArray = encoder.decode(byteArray);
    } catch (DecoderException e) {
        throw new IOException(e.getMessage());
    }

    String json = new String(byteArray, FILE_ENCODE);

    Map<String, String> map = gson.fromJson(json, new TypeToken<Map<String, String>>() {
    }.getType());

    setVersionTag(map);
    props.putAll(map);
}

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

@Test
public final void testPutWithJPGFile() throws IOException {
    final String name = UUID.randomUUID().toString();
    final String path = testPathPrefix + name;
    File temp = File.createTempFile("upload", ".jpg");
    FileUtils.forceDeleteOnExit(temp);//  w  w  w  .  j  a  va 2  s.  c  om
    final ClassLoader classLoader = Thread.currentThread().getContextClassLoader();

    try (InputStream testDataInputStream = classLoader.getResourceAsStream(TEST_FILENAME);
            OutputStream out = new FileOutputStream(temp)) {
        IOUtils.copy(testDataInputStream, out);
        MantaObject response = mantaClient.put(path, temp);
        String contentType = response.getContentType();
        Assert.assertEquals(contentType, "image/jpeg", "Content type wasn't detected correctly");

        try (InputStream in = mantaClient.getAsInputStream(path)) {
            byte[] actual = IOUtils.toByteArray(in);
            byte[] expected = FileUtils.readFileToByteArray(temp);

            Assert.assertTrue(Arrays.equals(actual, expected), "Uploaded file isn't the same as actual file");
        }
    }
}

From source file:com.cloudant.sync.indexing.IndexManagerIndexTest.java

@Test
public void indexString_documentWithValidField_indexRowShouldBeAdded()
        throws IndexExistsException, SQLException, IOException {
    Index index = createAndGetIndex("StringIndex", "stringIndex", IndexType.STRING);
    byte[] data = FileUtils.readFileToByteArray(new File("fixture/string_index_valid_field.json"));
    DocumentRevision obj = datastore.createDocument(DocumentBodyFactory.create(data));
    indexManager.updateAllIndexes();/*from  ww w  .  j a v a 2s .c o m*/
    IndexTestUtils.assertDBObjectInIndex(database, index, "stringIndex", obj);
}

From source file:edu.ku.brc.specify.tools.ireportspecify.MainFrameSpecify.java

/**
 * @param jasperFile// w w  w . java 2 s.  c  o  m
 * @param confirmOverwrite
 * @param newResName this name override the name of the report (which is usually the file name sans the extension)
 * @return true if the report is successfully imported, otherwise return false.
 */
public static boolean importJasperReport(final File jasperFile, final boolean confirmOverwrite,
        final String newResName) {
    ByteArrayOutputStream xml = null;
    try {
        xml = new ByteArrayOutputStream();
        xml.write(FileUtils.readFileToByteArray(jasperFile));
    } catch (IOException e) {
        edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
        edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(MainFrameSpecify.class, e);
        UIRegistry.getStatusBar().setErrorMessage(e.getLocalizedMessage(), e);
        return false;
    }

    String resName = newResName != null ? newResName : FilenameUtils.getBaseName(jasperFile.getName());
    AppResAndProps resApp = getAppRes(resName, null, confirmOverwrite);
    if (resApp != null) {
        String metaData = resApp.getAppRes().getMetaData();
        String newMetaData = "isimport=1";
        try {
            Element element = XMLHelper.readFileToDOM4J(jasperFile);
            List<?> parameters = element.selectNodes("/jasperReport/parameter");
            boolean isDropSite = false;
            for (Object p : parameters) {
                Element param = (Element) p;
                if (param.attributeValue("name").equals(ReportsBaseTask.RECORDSET_PARAM)) {
                    isDropSite = true;
                    break;
                }
            }
            if (isDropSite) {
                newMetaData += ";hasrsdropparam=1";
            } else {
                newMetaData += ";hasrsdropparam=0";
            }
        } catch (Exception e) {
            edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
            edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(MainFrameSpecify.class, e);
            UIRegistry.getStatusBar().setErrorMessage(e.getLocalizedMessage(), e);
            return false;
        }
        if (StringUtils.isEmpty(metaData)) {
            metaData = newMetaData;
        } else {
            metaData += ";" + newMetaData;
        }
        resApp.getAppRes().setMetaData(metaData);
        return saveXML(xml, resApp, null, false);
    }
    return false;
}

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

/**
 * ?Base64???Token???// w  w w.j  a v  a  2s .  com
 * @param token token?
 * @param formFile 
 * @throws IOException
 */
public static void requestOcrMvsInvoiceBase64(String token, String formFile) {

    // 1.????
    String url = "https://ais.cn-north-1.myhuaweicloud.com/v1.0/ocr/mvs-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.xpn.xwiki.plugin.graphviz.GraphVizPlugin.java

/**
 * Executes GraphViz, writes the resulting image (in the requested format) in a temporary file on disk, and returns
 * the generated content from that file.
 * // w  ww  .  j ava2  s.  c  o m
 * @param hashCode the hascode of the content, to be used as the temporary file name
 * @param content the dot source code
 * @param extension the output file extension
 * @param dot which engine to execute: {@code dot} if {@code true}, {@code neato} if {@code false}
 * @return the content of the generated file
 * @throws IOException if writing the input or output files to the disk fails, or if writing the response body fails
 */
private byte[] getDotImage(int hashCode, String content, String extension, boolean dot) throws IOException {
    File dfile = getTempFile(hashCode, "input.dot", dot);
    if (!dfile.exists()) {
        FileUtils.write(dfile, content, XWiki.DEFAULT_ENCODING);
    }

    File ofile = getTempFile(hashCode, extension, dot);
    if (!ofile.exists()) {
        Runtime rt = Runtime.getRuntime();
        String[] command = new String[5];
        command[0] = dot ? this.dotPath : this.neatoPath;
        command[1] = "-T" + extension;
        command[2] = dfile.getAbsolutePath();
        command[3] = "-o";
        command[4] = ofile.getAbsolutePath();
        Process p = rt.exec(command);
        int exitValue = -1;
        final Thread thisThread = Thread.currentThread();
        Thread t = new Thread(new Hangcheck(thisThread), "dot-hangcheck");
        t.run();
        try {
            exitValue = p.waitFor();
            t.interrupt();
        } catch (InterruptedException ex) {
            p.destroy();
            LOGGER.error("Timeout while generating image from dot", ex);
        }

        if (exitValue != 0) {
            LOGGER.error("Error while generating image from dot: "
                    + IOUtils.toString(p.getErrorStream(), XWiki.DEFAULT_ENCODING));
        }
    }
    return FileUtils.readFileToByteArray(ofile);
}

From source file:com.highcharts.export.controller.ExportController.java

private ByteArrayOutputStream writeFileToStream(String filename) throws SVGConverterException {
    ByteArrayOutputStream stream = new ByteArrayOutputStream();

    try {/*from   w w w. j  a va  2s . co  m*/
        stream.write(FileUtils.readFileToByteArray(new File(filename)));
    } catch (IOException ioex) {
        logger.error("Tried to read file from filesystem: " + ioex.getMessage());
        throw new SVGConverterException("IOException: cannot find your file to download...");
    }

    return stream;
}

From source file:cpcc.ros.sim.osm.CameraTest.java

@Test(dataProvider = "imageDataProvider")
public void shouldGetImageForGivenPositionAndHeight(PolarCoordinate position, int width, int height,
        String imageFormat, String imageName) throws IOException {
    byte[] buffer = camera.getImage(position);
    BufferedImage image = ImageIO.read(new ByteArrayInputStream(buffer));
    assertThat(image.getHeight()).isEqualTo(height);
    assertThat(image.getWidth()).isEqualTo(width);

    byte[] reference = FileUtils.readFileToByteArray(new File(imageName));
    assertThat(buffer).isEqualTo(reference);
}

From source file:ch.silviowangler.dox.DocumentServiceImpl.java

@Override
@Transactional(propagation = SUPPORTS, readOnly = true)
@PreAuthorize("hasRole('ROLE_USER')")
public PhysicalDocument findPhysicalDocument(Long id)
        throws DocumentNotFoundException, DocumentNotInStoreException {

    DocumentReference doc = findDocumentReference(id);
    PhysicalDocument document = new PhysicalDocument();

    try {/* w w w. j a  va 2  s  . c  om*/
        BeanUtils.copyProperties(document, doc);
    } catch (IllegalAccessException | InvocationTargetException e) {
        logger.error("Unable to copy properties", e);
    }

    File file = new File(this.archiveDirectory, doc.getHash());

    if (!file.exists()) {
        logger.error("Unable to find file for document hash '{}' on path '{}'", doc.getHash(),
                file.getAbsolutePath());
        throw new DocumentNotInStoreException(doc.getHash(), doc.getId());
    }

    try {
        document.setContent(FileUtils.readFileToByteArray(file));
    } catch (IOException e) {
        logger.error("Unable to read content of file '{}'", file.getAbsolutePath(), e);
    }
    return document;
}