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.wipro.ats.bdre.filemon.FileScan.java

public static void scanAndAddToQueue() {
    try {// w w w . j  av  a 2 s . c o m
        String scanDir = FileMonRunnableMain.getMonitoredDirName();
        LOGGER.debug("Scanning directory: " + scanDir);
        File dir = new File(scanDir);
        if (!dir.exists()) {
            LOGGER.info("Created monitoring dir " + dir + " success=" + dir.mkdirs());
        }
        File arcDir = new File(scanDir + "/" + FileMonRunnableMain.ARCHIVE);
        if (!arcDir.exists()) {
            LOGGER.info("Created monitoring dir " + arcDir + " success=" + arcDir.mkdirs());
        }
        // Getting list of files recursively from directory except '_archive' directory
        Collection<File> listOfFiles = FileUtils.listFiles(dir,
                new RegexFileFilter(FileMonRunnableMain.getFilePattern()),
                new RegexFileFilter("^(?:(?!" + FileMonRunnableMain.ARCHIVE + ").)*$"));
        String fileName = "";
        FileCopyInfo fileCopyInfo = null;
        for (File file : listOfFiles) {
            fileName = file.getName();
            LOGGER.debug("Matched File Pattern by " + fileName);
            fileCopyInfo = new FileCopyInfo();
            fileCopyInfo.setFileName(fileName);
            fileCopyInfo.setSubProcessId(FileMonRunnableMain.getSubProcessId());
            fileCopyInfo.setServerId(Integer.toString(123461));
            fileCopyInfo.setSrcLocation(file.getAbsolutePath());
            fileCopyInfo.setDstLocation(file.getParent().replace(FileMonRunnableMain.getMonitoredDirName(),
                    FileMonRunnableMain.getHdfsUploadDir()));
            fileCopyInfo.setFileHash(DigestUtils.md5Hex(FileUtils.readFileToByteArray(file)));
            fileCopyInfo.setFileSize(file.length());
            fileCopyInfo.setTimeStamp(file.lastModified());
            FileMonitor.addToQueue(fileName, fileCopyInfo);
        }
    } catch (Exception err) {
        LOGGER.error("Error in scan directory ", err);
        throw new BDREException(err);
    }
}

From source file:com.vexsoftware.votifier.crypto.RSAIO.java

/**
 * Loads an RSA key pair from a directory. The directory must have the files
 * "public.key" and "private.key"./*from  w  w w .j  av a  2  s.c  o  m*/
 * 
 * @param directory
 *            The directory to load from
 * @return The key pair
 * @throws Exception
 *             If an error occurs
 */
public static KeyPair load(File directory) throws Exception {
    // Read the public key file.
    File publicKeyFile = new File(directory + "/public.key");
    byte[] encodedPublicKey = FileUtils.readFileToByteArray(publicKeyFile);
    encodedPublicKey = DatatypeConverter.parseBase64Binary(new String(encodedPublicKey));

    // Read the private key file.
    File privateKeyFile = new File(directory + "/private.key");
    byte[] encodedPrivateKey = FileUtils.readFileToByteArray(privateKeyFile);
    encodedPrivateKey = DatatypeConverter.parseBase64Binary(new String(encodedPrivateKey));

    // Instantiate and return the key pair.
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(encodedPublicKey);
    PublicKey publicKey = keyFactory.generatePublic(publicKeySpec);
    PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(encodedPrivateKey);
    PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec);
    return new KeyPair(publicKey, privateKey);
}

From source file:backtype.storm.utils.LocalState.java

public synchronized Map<Object, Object> snapshot() throws IOException {
    int attempts = 0;
    while (true) {
        String latestPath = _vs.mostRecentVersionPath();
        if (latestPath == null)
            return new HashMap<Object, Object>();
        try {/*from   w w w  .  j a  va  2 s.  c  o  m*/
            return (Map<Object, Object>) Utils
                    .javaDeserialize(FileUtils.readFileToByteArray(new File(latestPath)));
        } catch (IOException e) {
            attempts++;
            if (attempts >= 10) {
                throw e;
            }
        }
    }
}

From source file:info.joseluismartin.gtc.Tile.java

public void load(String path) {
    try {//www  .  jav  a2s.  c o m
        image = FileUtils.readFileToByteArray(new File(path));
    } catch (IOException e) {
        log.error(e);
    }
}

From source file:net.rptools.lib.image.ImageUtil.java

/**
 * Load the image. Does not create a graphics configuration compatible version.
 *//* w  ww .j a va2  s  .c o m*/
public static Image getImage(File file) throws IOException {
    return bytesToImage(FileUtils.readFileToByteArray(file));
}

From source file:com.github.kubakaszycki.jkhttpd.api.FileURLHandler.java

@Override
public void handle(String res, HttpRequest req, HttpResponse resp)
        throws IOException, IllegalArgumentException {
    File relativeFile = new File(baseDir, res);
    if (!relativeFile.exists()) {
        resp.setCode(404);/* w  w w  .j a va 2  s  . c o  m*/
        resp.setCodeString();
        return;
    }
    if (relativeFile.isDirectory()) {
        resp.setContents(CharBuffer.wrap(DirectoryListing.doDirectoryListing(relativeFile, res)));
    } else {
        resp.setContents(
                Charset.defaultCharset().decode(ByteBuffer.wrap(FileUtils.readFileToByteArray(relativeFile))));
    }
    resp.setCode(200);
    resp.setCodeString();
}

From source file:com.sysunite.weaver.nifi.CreateObjectPropertyTest.java

@Test
public void testOnTrigger() {
    try {/*from ww  w  . j a  va  2s  . com*/
        String file = "slagboom.xml";

        byte[] contents = FileUtils
                .readFileToByteArray(new File(getClass().getClassLoader().getResource(file).getFile()));

        InputStream in = new ByteArrayInputStream(contents);

        InputStream cont = new ByteArrayInputStream(IOUtils.toByteArray(in));

        // Generate a test runner to mock a processor in a flow
        TestRunner runner = TestRunners.newTestRunner(new CreateObjectProperty());

        // Add properites
        runner.setProperty(CreateObjectProperty.PROP_NODE, "FunctionalPhysicalObject");
        runner.setProperty(CreateObjectProperty.PROP_NODE_ATTRIBUTE, "id");

        runner.setProperty(CreateObjectProperty.PROP_CHILDNODE, "HasAsSubject");
        runner.setProperty(CreateObjectProperty.PROP_CHILDNODE_ATTRIBUTE, "noattr");
        //optional
        runner.setProperty(CreateObjectProperty.PROP_CHILDNODE_SUB, "Geometry");
        runner.setProperty(CreateObjectProperty.PROP_CHILDNODE_SUB_ATTRIBUTE, "id");

        // Add the content to the runner
        runner.enqueue(cont);

        // Run the enqueued content, it also takes an int = number of contents queued
        runner.run();

        // All results were processed with out failure
        //runner.assertQueueEmpty();

        //            // If you need to read or do aditional tests on results you can access the content
        //            List<MockFlowFile> results = runner.getFlowFilesForRelationship(CreateObjectProperty.MY_RELATIONSHIP);
        //            //assertTrue("1 match", results.size() == 1);
        //
        //            System.out.println("aantal gevonden: " + results.size());
        //
        //            MockFlowFile result = results.get(0);
        //            String resultValue = new String(runner.getContentAsByteArray(result));
        //
        //
        //            //check weaver
        //            String checkValue = weaver.get("816ee370-4274-e211-a3a8-b8ac6f902f00").toString();
        //
        //            assertEquals(checkValue, resultValue);

        //System.out.println("Match: " + IOUtils.toString(runner.getContentAsByteArray(result)));
    } catch (IOException e) {
        System.out.println("FOUT!!");
        System.out.println(e.getStackTrace());
    }
}

From source file:com.btmatthews.leabharlann.service.impl.FileImportSource.java

/**
 * If the content root is a file then the file is processed. Otherwise, if the content
 * root is a directory a depth first traversal of the directory tree is preformed
 * processing each file discovered.// ww  w  .  j  a  v  a 2 s  . c  o m
 *
 * @param callback The callback used to process the files.
 * @throws Exception If there was an error.
 */
@Override
public void process(final ImportCallback callback) throws Exception {
    if (file.isDirectory()) {
        processDirectory(file, callback);
    } else {
        final byte[] data = FileUtils.readFileToByteArray(file);
        callback.file(File.separator + file.getName(), file.lastModified(), data);
    }
}

From source file:com.eviware.soapui.support.xml.actions.InsertBase64FileTextAreaAction.java

public void actionPerformed(ActionEvent e) {
    File file = UISupport.getFileDialogs().open(this, dialogTitle, null, null, null);
    if (file == null)
        return;//w ww .ja  v a  2  s. c  o  m

    try {
        // read file
        byte[] ba = FileUtils.readFileToByteArray(file);

        // convert to base 64
        Base64 b64 = new Base64();
        String hex = new String(b64.encode(ba));
        // insert into text at cursor position
        int pos = textArea.getCaretPosition();
        StringBuffer text = new StringBuffer(textArea.getText());
        text.insert(pos, hex);
        textArea.setText(text.toString());

    } catch (IOException e1) {
        UISupport.showErrorMessage("Error reading from file: " + e1.getMessage());
    }
}

From source file:com.sysunite.nifi.StringSplitTest.java

@Test
public void testOnTrigger() {
    try {//from w w w  . j a  v  a2s . c o  m
        String file = "line.txt";

        byte[] contents = FileUtils
                .readFileToByteArray(new File(getClass().getClassLoader().getResource(file).getFile()));

        InputStream in = new ByteArrayInputStream(contents);

        InputStream cont = new ByteArrayInputStream(IOUtils.toByteArray(in));

        // Add properites
        testRunner.setProperty(StringSplit.SPLIT, ";");
        testRunner.setProperty("RouteA", "0");
        testRunner.setProperty("RouteB", "1");
        testRunner.setProperty("AnotherThing", "3");

        // Add the content to the runner
        testRunner.enqueue(cont);

        // Run the enqueued content, it also takes an int = number of contents queued
        testRunner.run();

        //get contents for a specific dynamic relationship
        List<MockFlowFile> results = testRunner.getFlowFilesForRelationship("RouteB");
        assertTrue("1 match", results.size() == 1);
        MockFlowFile result = results.get(0);
        result.assertAttributeEquals("RouteB", "(ABCT1-N-02A/02B)CT1-W2hoofdrijbaan");

        //get original flowfile contents
        results = testRunner.getFlowFilesForRelationship("original");
        result = results.get(0);
        String resultValue = new String(testRunner.getContentAsByteArray(result));
        System.out.println(resultValue);

    } catch (IOException e) {
        System.out.println("FOUT!!");
        System.out.println(e.getStackTrace());
    }
}