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.iyonger.apm.web.model.Home.java

/**
 * Get the {@link Properties} from the the given configuration file.
 *
 * @param confFileName configuration file name
 * @return loaded {@link Properties}/*from w  w  w . ja v a 2  s  . c o m*/
 */
public Properties getProperties(String confFileName) {
    try {
        File configFile = getSubFile(confFileName);
        if (configFile.exists()) {
            byte[] propByte = FileUtils.readFileToByteArray(configFile);
            String propString = EncodingUtils.getAutoDecodedString(propByte, "UTF-8");
            Properties prop = new Properties();
            prop.load(new StringReader(propString));
            return prop;
        } else {
            // default empty properties.
            return new Properties();
        }

    } catch (IOException e) {
        throw processException("Fail to load property file " + confFileName, e);
    }
}

From source file:eionet.webq.converter.MultipartFileToUserFileConverterTest.java

@Test
public void whenConvertingMultipartFile_ifAttachmentTypeIsZipFileAndFilesAreCorrupt_setDummyXmlSchema()
        throws Exception {
    Collection<UserFile> files = fileConverter.convert(createMultipartFile(ZIP_ATTACHMENT_MEDIA_TYPE,
            FileUtils.readFileToByteArray(new File(BROKEN_TEST_XML_FILE_ZIP))));

    assertThat(files.size(), equalTo(1));
    Iterator<UserFile> it = files.iterator();
    assertThat(it.next().getXmlSchema(), equalTo(UserFileInfo.DUMMY_XML_SCHEMA));
}

From source file:de.hybris.platform.media.storage.impl.LocalFileMediaStorageStrategyTest.java

@Test
public void shouldStoreFileInAllReplicationDirs() throws IOException {
    final String tempDir = System.getProperty("java.io.tmpdir");

    final File dataDir = new File(tempDir, "_test_datadir");
    dataDir.mkdirs();//from  w w  w . j  a  va 2  s . co m
    final File replicationDir1 = new File(tempDir, "_test_replicationdir1");
    replicationDir1.mkdirs();
    final File replicationDir2 = new File(tempDir, "_test_replicationdir2");
    replicationDir2.mkdirs();

    final LocalFileMediaStorageStrategy lfStrategy = new LocalFileMediaStorageStrategy();
    lfStrategy.setMainDataDir(dataDir);
    // !!! despite the name 'setReplicationDirs()' must include the main data dir as well !!!
    lfStrategy.setReplicationDirs(Arrays.asList(dataDir, replicationDir1, replicationDir2));
    lfStrategy.setMimeService(mimeService);
    lfStrategy.setLocationHashService(mediaLocationHashService);

    // given
    final byte[] rawData = "AllReplicationDirsShouldGetTheSameDataTest!!!".getBytes();
    final Map<String, Object> metaData = buildMediaMetaData(MIME, REAL_FILENAME, FOLDER_PATH);

    final File expectedDataFile = new File(dataDir, PROPER_LOCATION + MEDIA_ID + ".jpg");
    final File expectedRepFile1 = new File(replicationDir1, PROPER_LOCATION + MEDIA_ID + ".jpg");
    final File expectedRepFile2 = new File(replicationDir2, PROPER_LOCATION + MEDIA_ID + ".jpg");
    try {

        // when
        final StoredMediaData storedMedia = lfStrategy.store(folderConfig, MEDIA_ID, metaData,
                new ByteArrayInputStream(rawData));

        // then
        assertThat(storedMedia).isNotNull();
        assertThat(storedMedia.getLocation()).isNotNull();
        assertThat(storedMedia.getLocation()).isEqualTo(PROPER_LOCATION + MEDIA_ID + ".jpg");

        assertThat(expectedDataFile.exists()).isTrue();
        assertThat(FileUtils.readFileToByteArray(expectedDataFile)).isEqualTo(rawData);

        assertThat(expectedRepFile1.exists()).isTrue();
        assertThat(FileUtils.readFileToByteArray(expectedRepFile1)).isEqualTo(rawData);

        assertThat(expectedRepFile2.exists()).isTrue();
        assertThat(FileUtils.readFileToByteArray(expectedRepFile2)).isEqualTo(rawData);
    } finally {
        FileUtils.deleteQuietly(expectedDataFile);
        FileUtils.deleteQuietly(expectedRepFile1);
        FileUtils.deleteQuietly(expectedRepFile2);
    }
}

From source file:edu.monash.merc.util.file.DMFileUtils.java

public static byte[] readFileToByteArray(String fileName) {
    try {/* ww  w  .  j ava2s .c o  m*/
        return FileUtils.readFileToByteArray(new File(fileName));
    } catch (Exception e) {
        throw new DMFileException(e);
    }
}

From source file:edu.odu.cs.cs350.yellow1.jar.ExecuteJar.java

/**
 * /*from w  w w.ja va2s.c  o  m*/
 * {@inheritDoc}
 * <br>Run all tests in the test suit on the mutant 
 * capturing the output created and if the execution of the mutant with a test exits successfully compare the standard output generated by<br>
 * the mutant if different stop running tests and return {@link ExecutionResults}
 * <br> Treats exiting the jvm with error as was not killed continue to run more tests 
 * @return {@link ExecutionResults}
 */
@Override
public ExecutionResults call() throws Exception {
    //create new Executor for monitoring mutation running
    executor = new DefaultExecutor();
    //get a MessageDigest Instance for use in comparing outputs
    MessageDigest mDigest = MessageDigest.getInstance("MD5");
    //get file object for gold file
    File f = new File(pathToGold);
    //get the hash value for the gold file
    goldHash = mDigest.digest(FileUtils.readFileToByteArray(f));
    //reset the MessageDigest
    mDigest.reset();
    int testCount = 0;
    //Create a new ExecuteWatchdog with timeout at 10 seconds
    wDog = new ExecuteWatchdog(10000);
    executor.setWatchdog(wDog);
    //loop through the tests till empty
    while (!tests.isEmpty()) {
        //get the next test
        File test = tests.poll();//poll removes the test from the queue
        //prepair captured output files
        String testName = test.getName();
        testName = testName.toUpperCase(Locale.getDefault()).substring(0, testName.indexOf("."));
        String outName = jarName + "_" + testName + "_out.txt";
        String errOutName = jarName + "_" + testName + "_err.txt";
        //create file objects to be written to 
        File standardOut = new File(pathToOutputDir + File.separator + outName);
        File standardErr = new File(pathToOutputDir + File.separator + errOutName);
        //file streams create the files for me
        try {
            log = new FileOutputStream(standardOut);

            err = new FileOutputStream(standardErr);
        } catch (FileNotFoundException e1) {
            logger.error("log or err file not found for jar " + jarName, e1.getMessage());
        }
        //create new stream handler for each execution
        streamHandler = new PumpStreamHandler(/* standard out */log, /* error out */err);
        executor.setStreamHandler(streamHandler);
        //construct the executable command
        CommandLine args = new CommandLine(pathToJVM);
        args.addArgument("-jar");
        args.addArgument(jar.getAbsolutePath());
        args.addArgument(test.getAbsolutePath());
        //new process destroyer per execution
        ShutDownSpawnedJVMProcess killJVM = new ShutDownSpawnedJVMProcess("java -jar " + jarName, 10000);
        killJVM.setWaitOnShutdown(true);
        executor.setProcessDestroyer(killJVM);
        success = false;

        try {
            streamHandler.start();
            int result = executor.execute(args);
            logger.info(jarName + " Sucess with val=[" + result + "] for test[" + testName + "]");
            success = true;
        } catch (ExecuteException ee) {
            logger.error(jarName + " Execute exception " + ee.getMessage() + " with val=[" + ee.getExitValue()
                    + "] for test[" + testName + "]");
        } catch (IOException e) {
            logger.error(jarName + " IOExecption " + e.getMessage());

        } finally {
            //PumpStreamHandler does not guarantee the closing of stream 100% so to release the locks held by the filestreams 
            //on the created output files so close manually 
            //if the streamhandler was able to close then this will through exception which we ignore
            try {
                streamHandler.stop();
                //log.flush();
                log.close();
                //err.flush();
                err.close();
            } catch (IOException e) {
                logger.error(e.getMessage());
                //ignore nothing I can do 
            }

        }

        //if the spawned process exited with success value 
        //check the hash of the output file and delete the empty error file
        //if the hash is different the mutant was killed otherwise test more
        //if the spawned process exited with an error value delete empty standard out file and test more
        if (success) {
            ++numOfSucesses;
            standardErr.delete();
            outFiles.add(standardOut);
            if (!Arrays.equals(goldHash, mDigest.digest(FileUtils.readFileToByteArray(standardOut)))) {
                testMore = false;
                logger.debug("Different hashes for jar [" + jarName + "] for test [" + testName + "]");
            } else {
                logger.debug("Same hashes for jar [" + jarName + "] for test [" + testName + "]");
            }
            mDigest.reset();
        } else {
            ++numOfFailurs;
            standardOut.delete();
            errFiles.add(standardErr);
            this.didNotExecute.add(test);
        }
        ++testCount;
        //the mutant was killed so stop testing 
        if (!testMore) {
            testMore = false;
            killed = true;
            testNumKilledME = testCount;
            break;
        }

    }

    jar.delete();
    return new ExecutionResults(numOfSucesses, numOfFailurs, testNumKilledME, jarName, killed, killedMutant,
            outFiles, errFiles);

}

From source file:be.fedict.eid.dss.admin.portal.control.bean.RPBean.java

@Override
@Begin(join = true)/*from   ww w  .  j a v a  2s . c  o  m*/
public void uploadListener(UploadEvent event) throws IOException {

    UploadItem item = event.getUploadItem();
    this.log.debug(item.getContentType());
    this.log.debug(item.getFileSize());
    this.log.debug(item.getFileName());
    if (null == item.getData()) {
        // meaning createTempFiles is set to true in the SeamFilter
        this.certificateBytes = FileUtils.readFileToByteArray(item.getFile());
    } else {
        this.certificateBytes = item.getData();
    }

    try {
        X509Certificate certificate = getCertificate(this.certificateBytes);
        this.log.debug("certificate: " + certificate);
        this.selectedRP.setCertificate(certificate);
    } catch (CertificateException e) {
        this.facesMessages.addToControl("upload", "Invalid certificate");
    }
}

From source file:app.common.upload.shapeways.oauth.ModelUploadOauthRunner.java

public String uploadModel(String modelFile, Integer modelId, Float scale, String title, String description,
        Integer isPublic, Integer isForSale, Map<Integer, Object> materialsMap) throws Exception {

    String reason = null;// w  w w. ja v a 2 s. c om
    File file = new File(modelFile);

    try {
        byte[] fileBytes = FileUtils.readFileToByteArray(file);
        return uploadModel(fileBytes, file.getName(), modelId, scale, title, description, isPublic, isForSale,
                materialsMap);
    } catch (IOException ioe) {
        reason = "Model not found: " + file.getAbsolutePath();
        System.out.println(reason);
        throw new Exception(reason);
    }
}

From source file:de.xirp.mail.Attachment.java

/**
 * Reads the attachment {@link java.io.File} field to a byte
 * array./* ww  w  .j a  v a2 s  .c om*/
 * 
 * @return The content of the file as byte array.
 * 
 * @throws IOException if the attachment field is null.
 * 
 */
private byte[] readAttachmentFileToByteArray() throws IOException {
    return FileUtils.readFileToByteArray(attachment);
}

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

private void fillContent(SysJreportVO report) throws IOException, Exception {
    String uploadOid = super.getFields().get("uploadOid");
    File file = UploadSupportUtils.getRealFile(uploadOid);
    report.setContent(FileUtils.readFileToByteArray(file));
    file = null;//from  w  w  w .  j  a  v a  2  s .c  o m
}

From source file:beans.FotoBean.java

public void enviarArquivo(FileUploadEvent event) {
    try {/* ww w .  j  av a 2  s . c o m*/
        arquivo = gerarNome();
        ServletContext servletContext = (ServletContext) FacesContext.getCurrentInstance().getExternalContext()
                .getContext();
        String pasta = servletContext.getRealPath("") + File.separator + "resources" + File.separator
                + "arquivossalvos";
        File vpasta = new File(pasta);
        if (!vpasta.exists()) {
            vpasta.setWritable(true);
            vpasta.mkdirs();
        }
        String novoarquivo = pasta + File.separator + event.getFile().getFileName();
        File a = new File(novoarquivo);
        a.createNewFile();
        FileUtils.copyInputStreamToFile(event.getFile().getInputstream(), a);
        byte[] fotobyte = FileUtils.readFileToByteArray(a);
        foto.setNome(event.getFile().getFileName());
        foto.setArquivo(fotobyte);
        foto.setDataHora(Calendar.getInstance().getTime());

        if (new FotoController().salvar(foto)) {
            listarArquivos();
            Util.executarJavascript("PF('dlgfoto').hide()");
            Util.criarMensagem("arquivo salvo");
            Util.atualizarComponente("foto");
            a.delete();
        }

    } catch (Exception e) {
        Util.criarMensagemErro(e.toString());
    }
}