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:hws.core.JobClient.java

private void uploadFile(FileSystem fs, File file, ApplicationId appId) throws IOException {
    Path filePath = new Path("hdfs:///hws/apps/" + appId.toString() + "/" + file.getName());
    if (fs.exists(filePath)) {
        fs.delete(filePath, true);/*from w w w .  ja v a  2 s . c o m*/
    }
    FSDataOutputStream ostream = fs.create(filePath);
    byte[] data = FileUtils.readFileToByteArray(file);
    ostream.write(data);
    ostream.close();
}

From source file:com.logsniffer.reader.log4j.Log4jTextReaderTest.java

/**
 * Tests matching bug caused by new line character caused by
 * {@link LineInputStream}./*from   w w  w.  j  a va 2  s.co  m*/
 */
@Test
public void testInvalidPatternFromFile() throws UnsupportedEncodingException, IOException, FormatException {
    final Log4jTextReader reader = new Log4jTextReader("%d %-5p [%c] (%t) %m%n", "UTF-8");
    final File f = new File("src/test/resources/logs/nl-triming.txt");
    final LogEntry[] entries = readEntries(reader, new ByteArrayLog(FileUtils.readFileToByteArray(f)), null,
            2000);

    Assert.assertEquals(46, entries.length);
}

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

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

    // 1.???
    String url = "https://ais.cn-north-1.myhuaweicloud.com/v1.0/ocr/handwriting";
    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);

        // 
        // 1.a ????????
        // detect_direction?:true, false
        //
        json.put("detect_direction", true);

        // 
        // 1.b ???????? ???
        // text_type?:"digit", "upper_letter" ??
        //
        ArrayList<String> textType = new ArrayList<String>();
        textType.add("digit");
        textType.add("upper_letter");
        json.put("text_type", textType);

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

@Test
public void createLongIndex_indexValueIsBigLong_documentShouldBeIndexed()
        throws IndexExistsException, SQLException, IOException {
    indexManager.ensureIndexed("class", "class", IndexType.INTEGER);
    Index index = indexManager.getIndex("class");
    byte[] data = FileUtils.readFileToByteArray(new File("fixture/index_really_big_long.json"));
    DocumentRevision obj1 = datastore.createDocument(DocumentBodyFactory.create(data));
    indexManager.updateAllIndexes();/*  w w  w . ja va 2s.c  o m*/
    IndexTestUtils.assertDBObjectInIndex(database, index, "class", obj1);
}

From source file:net.firejack.platform.web.security.x509.KeyUtils.java

public static InputStream readCrypt(File file, File keystore) {
    if (!file.exists())
        return null;

    InputStream stream = null;//from  w  ww. j a va  2 s .  c  o  m
    try {
        if (keystore.exists()) {
            KeyPair keyPair = load(keystore);
            byte[] decrypt = decrypt(keyPair.getPrivate(), FileUtils.readFileToByteArray(file));
            stream = new ByteArrayInputStream(decrypt);
        }
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    }

    return stream;
}

From source file:ddf.content.plugin.video.VideoThumbnailPlugin.java

private byte[] createGifFromThumbnailFiles() throws IOException, InterruptedException {
    final DefaultExecuteResultHandler resultHandler = executeFFmpeg(getFFmpegCreateAnimatedGifCommand(), 3,
            null);/*from w  ww.  ja  v  a 2s .  c o  m*/

    resultHandler.waitFor();

    if (resultHandler.getException() == null) {
        return FileUtils.readFileToByteArray(new File(getGifFilePath()));
    } else {
        throw resultHandler.getException();
    }
}

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

@Test
public void createLongIndex_indexValueIsFloat_documentShouldBeIndexed()
        throws IndexExistsException, SQLException, IOException {
    indexManager.ensureIndexed("class", "class", IndexType.INTEGER);
    Index index = indexManager.getIndex("class");
    byte[] data = FileUtils.readFileToByteArray(new File("fixture/index_float.json"));
    DocumentRevision obj1 = datastore.createDocument(DocumentBodyFactory.create(data));
    indexManager.updateAllIndexes();/*from  w  ww. j  a  v  a  2s  . c o m*/
    IndexTestUtils.assertDBObjectInIndex(database, index, "class", obj1);
}

From source file:de.blizzy.documentr.page.PageStore.java

private Map<String, Object> getPageData(String projectName, String branchName, String path, String rootDir,
        String commit, boolean loadData) throws IOException, GitAPIException {

    ILockedRepository repo = null;// w  ww.  j a  v a2  s  . co m
    try {
        repo = globalRepositoryManager.getProjectBranchRepository(projectName, branchName);

        File workingDir = RepositoryUtil.getWorkingDir(repo.r());
        File pagesDir = new File(workingDir, rootDir);
        File workingFile = Util.toFile(pagesDir, path + DocumentrConstants.META_SUFFIX);
        if (!workingFile.isFile()) {
            throw new PageNotFoundException(projectName, branchName, path);
        }

        String json;
        if (commit != null) {
            json = BlobUtils.getContent(repo.r(), commit,
                    DocumentrConstants.PAGES_DIR_NAME + "/" + path + DocumentrConstants.META_SUFFIX); //$NON-NLS-1$
        } else {
            json = FileUtils.readFileToString(workingFile, Charsets.UTF_8);
        }
        Gson gson = new GsonBuilder().enableComplexMapKeySerialization().create();
        Map<String, Object> pageMap = gson.fromJson(json, new TypeToken<Map<String, Object>>() {
        }.getType());

        if (loadData) {
            workingFile = Util.toFile(pagesDir, path + DocumentrConstants.PAGE_SUFFIX);
            byte[] data;
            if (commit != null) {
                data = BlobUtils.getRawContent(repo.r(), commit,
                        DocumentrConstants.PAGES_DIR_NAME + "/" + path + DocumentrConstants.PAGE_SUFFIX); //$NON-NLS-1$
            } else {
                data = FileUtils.readFileToByteArray(workingFile);
            }
            String contentType = (String) pageMap.get(CONTENT_TYPE);
            PageData pageData;
            if (contentType.equals(PageTextData.CONTENT_TYPE)) {
                pageData = PageTextData.fromBytes(data);
            } else {
                pageData = new PageData(data, contentType);
            }
            pageMap.put(PAGE_DATA, pageData);
        }

        String parentPagePath = getParentPagePath(path, repo.r());
        if (parentPagePath != null) {
            pageMap.put(PARENT_PAGE_PATH, parentPagePath);
        }

        return pageMap;
    } finally {
        Closeables.closeQuietly(repo);
    }
}

From source file:com.falkonry.TestAddDataStream.java

/**
 * Should add datastream with microseconds precision
 * @throws Exception//from   ww w  .  j a v  a 2 s  .c  om
 */
@Test
public void addDataWithMicrosecondsPrecision() throws Exception {

    Datastream ds = new Datastream();
    ds.setName("Test-DS1-" + Math.random());
    ds.setTimePrecision("micro");

    TimeObject time = new TimeObject();
    time.setIdentifier("time");
    time.setFormat("iso_8601");
    time.setZone("GMT");

    Signal signal = new Signal();
    signal.setTagIdentifier("tag");
    signal.setValueIdentifier("value");
    signal.setDelimiter("_");
    signal.setIsSignalPrefix(false);

    Datasource dataSource = new Datasource();
    dataSource.setType("STANDALONE");

    Field field = new Field();
    field.setSiganl(signal);
    field.setTime(time);

    ds.setDatasource(dataSource);
    ds.setField(field);

    Datastream datastream = falkonry.createDatastream(ds);
    datastreams.add(datastream);

    Map<String, String> options = new HashMap<String, String>();

    File file = new File("res/data.json");
    ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(FileUtils.readFileToByteArray(file));
    InputStatus inputStatus = falkonry.addInputStream(datastream.getId(), byteArrayInputStream, options);
    Assert.assertEquals(inputStatus.getAction(), "ADD_DATA_DATASTREAM");
    Assert.assertEquals(inputStatus.getStatus(), "PENDING");
    Datastream createdDatastream = falkonry.getDatastream(datastream.getId());
    Assert.assertEquals(createdDatastream.getId(), datastream.getId());
    Assert.assertEquals(createdDatastream.getName(), datastream.getName());
    Assert.assertEquals(createdDatastream.getTimePrecision(), datastream.getTimePrecision());
    Field field1 = createdDatastream.getField();
    Signal signal1 = field1.getSignal();
    Assert.assertEquals(signal1.getDelimiter(), signal.getDelimiter());
    Assert.assertEquals(signal1.getTagIdentifier(), signal.getTagIdentifier());
    Assert.assertEquals(signal1.getValueIdentifier(), signal.getValueIdentifier());
    Assert.assertEquals(signal1.getIsSignalPrefix(), signal.getIsSignalPrefix());
}

From source file:com.emergya.persistenceGeo.service.impl.LayerAdminServiceImpl.java

protected AbstractLayerEntity dtoToEntity(LayerDto dto) {
    AbstractLayerEntity entity = null;//  ww w . j a va  2  s . c o m
    if (dto != null) {
        Date now = new Date();
        if (dto.getId() != null && dto.getId() > 0) {
            entity = (AbstractLayerEntity) layerDao.findById(dto.getId(), false);
            //Grupos
            //            authDao.clearUser(dto.getId());
        } else {
            entity = instancer.createLayer();
            entity.setCreateDate(now);
        }

        // Properties
        if (dto.getProperties() != null && dto.getProperties().size() > 0) {
            List<AbstractLayerPropertyEntity> propertiesList = new LinkedList<AbstractLayerPropertyEntity>();
            for (String name : dto.getProperties().keySet()) {
                AbstractLayerPropertyEntity property = instancer.createLayerProperty();
                property.setName(name);
                property.setValue(dto.getProperties().get(name));
                propertiesList.add(property);
            }
            entity.setProperties(propertiesList);
        }

        // Add own parameters
        //entity.setId(dto.getId());
        entity.setName(dto.getName());
        entity.setOrder(dto.getOrder());
        entity.setServer_resource(dto.getServer_resource());
        entity.setPublicized(dto.getPublicized());
        entity.setEnabled(dto.getEnabled());
        entity.setIsChannel(dto.getPertenece_a_canal());
        entity.setUpdateDate(now);

        //Layer type
        if (dto.getType() != null) {
            entity.setType(layerTypeDao.getLayerType(dto.getType()));
        }

        //Layer data
        if (dto.getData() != null) {
            try {
                entity.setData(FileUtils.readFileToByteArray(dto.getData()));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        // Add relational parameters
        // Add users
        String usersDto = dto.getUser();
        if (usersDto != null) {
            AbstractUserEntity user = userDao.getUser(usersDto);
            if (user != null) {
                entity.setUser(user);
            }
        }
        // Add authorities
        Long authId = dto.getAuthId();
        if (authId != null) {
            entity.setAuth(authDao.findById(authId, false));
        }
        // Add style
        List<AbstractEntity> styleList = new LinkedList<AbstractEntity>();
        if (dto.getStyles() != null) {
            for (StyleDto styleDto : dto.getStyles().keySet()) {
                styleList = addToList(styleList, dtoStyleToEntity(styleDto, entity));
            }
        }
        entity.setStyleList(styleList);
        // Add folder
        if (dto.getFolderId() != null) {
            entity.setFolder(folderDao.findById(dto.getFolderId(), false));
        }
    }
    return entity;
}