Example usage for org.apache.commons.io IOUtils toByteArray

List of usage examples for org.apache.commons.io IOUtils toByteArray

Introduction

In this page you can find the example usage for org.apache.commons.io IOUtils toByteArray.

Prototype

public static byte[] toByteArray(String input) throws IOException 

Source Link

Document

Get the contents of a String as a byte[] using the default character encoding of the platform.

Usage

From source file:eu.europa.ejusticeportal.dss.applet.model.action.SavePdfActionTest.java

/**
 * Test the doExec method for SavePdfAction
 *//*from   w  w w . jav a 2s .  co  m*/
@Test
public void testDoExec() {
    FileInputStream fis = null;
    FileInputStream result = null;
    SavePdfAction instance;
    try {
        fis = new FileInputStream("src/test/resources/hello-world.pdf");
        byte[] pdf = (IOUtils.toByteArray(fis));
        instance = new SavePdfAction(pdf, null);
        instance.exec();

        File f = File.createTempFile("test", ".pdf");
        f.deleteOnExit();
        instance = new SavePdfAction(pdf, f);
        instance.exec();
        assertNotNull(f);
        assertTrue(f.exists());
        assertTrue(f.canRead());
        assertTrue(f.canWrite());

        result = new FileInputStream(f);
        byte[] resultPdf = (IOUtils.toByteArray(result));
        assertTrue(resultPdf.length > 0);

    } catch (FileNotFoundException ex) {
        fail("Hello-world.pdf is not available.");
    } catch (IOException ex) {
        fail("IO Issue");
    } finally {
        try {
            fis.close();
            result.close();
        } catch (IOException ex) {
            fail("Unable to close File stream");
        }
    }
}

From source file:fr.chaffottem.bonita.connector.ftp.DownloadFilesToDirectoryConnectorTest.java

private byte[] getFileContent(final FileEntry file) throws IOException {
    final InputStream inputStream = file.createInputStream();
    try {//from www  .  j  ava 2s.c o m
        return IOUtils.toByteArray(inputStream);
    } finally {
        inputStream.close();
    }
}

From source file:de.rnd7.urlcache.URLCacheLoader.java

private CachedElement loadFromURL(final URLCacheKey key) throws IOException {
    final CachedElement element = new CachedElement();
    element.setBytes(IOUtils.toByteArray(key.getUrl()));
    element.setValidUntil(CachedElement.createTimeoutDate());

    return element;
}

From source file:com.truebanana.data.SecureData.java

public SecureData(InputStream inputStream, String password) {
    this.password = password;
    try {/* w ww .jav  a2 s.c o  m*/
        byte[] data = IOUtils.toByteArray(inputStream);
        load(data);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.hurence.logisland.serializer.BytesArraySerializer.java

public Record deserialize(InputStream objectDataInput) {
    try {// w  ww  .  j  a  v  a  2  s  .  c o m
        Record record = new StandardRecord();
        byte[] bytes = IOUtils.toByteArray(objectDataInput);
        record.setField(FieldDictionary.RECORD_VALUE, FieldType.BYTES, bytes);
        return record;
    } catch (Throwable t) {
        throw new RecordSerializationException(t.getMessage(), t.getCause());
    }
}

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

@Test
public void testOnTrigger() {
    try {/*from w  ww  . jav  a 2s.c  om*/
        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:ai.aitia.meme.paramsweep.classloader.AspectJClassPath.java

/** {@inheritDoc} 
 *///from www  .  j  a v a 2  s .  c  om
@Override
public InputStream openClassfile(String classname) throws NotFoundException {
    try {
        URL originalURL = originalClassPath.find(classname);
        if (originalURL == null) {
            return null;
        }

        byte[] classBytes = IOUtils.toByteArray(originalClassPath.openClassfile(classname));

        try {
            if (!classname.startsWith("ai.aitia.meme")) {
                weaver.weaveClass(classname, classBytes);
            }
        } catch (IOException e) {
            Logger.logExceptionCallStack(e);
            throw new RuntimeException(e);
        }

        return new ByteArrayInputStream(classBytes);
    } catch (IOException e) {
        throw new NotFoundException("Could not read the bytes of " + classname + " from " + originalClassPath,
                e);
    }
}

From source file:com.youTransactor.uCube.mdm.task.DownloadBinaryTask.java

@Override
protected void start() {
    HttpURLConnection urlConnection = null;

    try {/*from   ww  w  .  j  a va2s .c o m*/
        String url = GET_BINARY_WS + String.valueOf(binaryUpdate.getCfg().getType()) + '/'
                + deviceInfos.getPartNumber() + '/' + deviceInfos.getSerial();
        urlConnection = MDMManager.getInstance().initRequest(url, MDMManager.POST_METHOD);

        urlConnection.setRequestProperty("Content-Type", "application/octet-stream");

        urlConnection.getOutputStream().write(certificate);

        HTTPResponseCode = urlConnection.getResponseCode();

        if (HTTPResponseCode == 200) {
            byte[] response = IOUtils.toByteArray(urlConnection.getInputStream());

            if (parseResponse(response)) {
                notifyMonitor(TaskEvent.SUCCESS, binaryUpdate);

            } else {
                notifyMonitor(TaskEvent.FAILED);
            }
        } else {
            LogManager.debug(MDMManager.class.getSimpleName(), "config WS error: " + HTTPResponseCode);

            notifyMonitor(TaskEvent.FAILED);
        }

    } catch (Exception e) {
        LogManager.debug(MDMManager.class.getSimpleName(), "config WS error", e);

        notifyMonitor(TaskEvent.FAILED);

    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
    }
}

From source file:com.betel.flowers.web.bean.util.UploadFileRun.java

@Override
public void run() {
    Boolean succesefull = Boolean.FALSE;
    Path path = Paths.get(url);
    //if directory exists?
    if (!Files.exists(path)) {
        try {/*w  w w . j  a  v a2s  .  c o  m*/
            Files.createDirectories(path);
            log.log(Level.INFO, "Directory is created!");
        } catch (IOException e) {
            //fail to create directory
            log.log(Level.SEVERE, "Failed to create directory! " + e.getMessage());
        }
    }

    File fileDelete = new File(url + name + "." + ext);
    if (fileDelete.delete()) {
        log.log(Level.INFO, "Se elimino el archivo: " + url + name + "." + ext);
    } else {
        log.log(Level.INFO, "No se elimino el archivo: " + url + name + "." + ext);
    }

    File file = new File(url + name + "." + ext);
    try {
        byte[] imgbytes = IOUtils.toByteArray(input);
        InputStream in = new ByteArrayInputStream(imgbytes);
        BufferedImage bImageFromConvert = ImageIO.read(in);
        ImageIO.write(bImageFromConvert, ext, file);
        succesefull = Boolean.TRUE;
    } catch (IOException e) {
        log.log(Level.SEVERE, "Error al guardar la imagen en:" + file.getPath(), e);
    }
    if (succesefull) {
        try {
            this.finalize();
            this.exito = true;
        } catch (Throwable ex) {
            log.log(Level.SEVERE, "Error al procesar imagen", ex);
        }
    } else {
        this.interrupt();
        this.exito = false;
    }
}

From source file:be.fedict.eid.applet.service.impl.HttpServletRequestHttpReceiver.java

public byte[] getBody() {
    try {/*from www.ja v a2  s. c  o m*/
        ServletInputStream inputStream = this.httpServletRequest.getInputStream();
        byte[] body = IOUtils.toByteArray(inputStream);
        return body;
    } catch (IOException e) {
        throw new RuntimeException("IO error: " + e.getMessage(), e);
    }
}