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:com.github.nukesparrow.htmlunit.Util.java

public static String toDataUrl(WebResponse response) throws IOException {
    StringBuilder b = new StringBuilder("data:").append(response.getContentType());
    if (response.getContentCharsetOrNull() != null && !response.getContentType().contains("charset=")) {
        b.append(";charset=").append(response.getContentCharset());
    }//ww  w.  j  a  va  2s.co  m
    b.append(";base64,");
    try (InputStream in = response.getContentAsStream()) {
        b.append(Base64.encodeBase64String(IOUtils.toByteArray(in)));
    }
    return b.toString();
}

From source file:edu.northwestern.bioinformatics.studycalendar.utility.osgimosis.FileClassLoader.java

@Override
protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
    log.trace("Looking for " + name);
    Class<?> found = findLoadedClass(name);
    if (found != null) {
        log.trace("Already loaded");
        return found;
    }//from w  w  w  . j a  va  2  s.c  om

    File f = new File(root, name.replaceAll("\\.", "/") + ".class");
    if (!f.exists()) {
        log.trace(f + " does not exist; going to system classloader");
        return super.loadClass(name, resolve);
    }

    byte[] contents;
    try {
        contents = IOUtils.toByteArray(new FileInputStream(f));
    } catch (IOException e) {
        throw new ClassNotFoundException("Could not read " + f, e);
    }
    log.trace("Defining from " + f);
    return defineClass(name, contents, 0, contents.length);
}

From source file:myDarkDiary.service.model.Image.java

public Image(User userId, String fileName, String filePath) throws IOException {
    this.userId = userId;
    this.fileName = fileName;
    ClassLoader classLoader = getClass().getClassLoader();
    File file = new File(classLoader.getResource(filePath).getFile());
    InputStream targetStream = new FileInputStream(file);
    this.data = IOUtils.toByteArray(targetStream);
}

From source file:com.tc.simple.apn.factories.FeedbackFactory.java

public List<Feedback> createFeedback(InputStream in) {
    List<Feedback> list = new ArrayList<Feedback>();
    try {/*from   w w w .  j  ava 2 s .  co  m*/

        byte[] byteMe = IOUtils.toByteArray(in);

        int startRange = 0;

        int endRange = 38; //38 byte chunks per feedback item.

        while (startRange < byteMe.length) {

            //init the value object to hold the feedback data.
            Feedback feedback = new Feedback();

            //build the item based on range
            byte[] item = Arrays.copyOfRange(byteMe, startRange, endRange);//38 byte chunks.

            byte[] date = Arrays.copyOfRange(item, 0, 4);

            byte[] size = Arrays.copyOfRange(item, 4, 6);

            byte[] token = Arrays.copyOfRange(item, 6, item.length);

            ByteBuffer dateWrap = ByteBuffer.wrap(date);

            ByteBuffer javaSize = ByteBuffer.wrap(size);

            //set the date (returns number of seconds from unix epoch date)
            feedback.setDate(new Date(dateWrap.getInt() * 1000L));

            //get the size of the token (should always be 32)
            feedback.setSize(javaSize.getShort());

            //drop in our encoded token (will be used as our key for marking the user's token doc as failed)
            feedback.setToken(String.valueOf(Hex.encodeHex(token)));

            //add it to our collection
            list.add(feedback);

            //increment the start range
            startRange = startRange + 38;

            //increment the end range.
            endRange = endRange + 38;

        }

    } catch (Exception e) {
        logger.log(Level.SEVERE, null, e);

    }

    return list;

}

From source file:HexTest.java

@Override
public void start(Stage primaryStage) throws InterruptedException, IOException {
    HexArea hexArea = new HexArea();

    Scene scene = new Scene(hexArea, 800, 600);
    hexArea.prefWidthProperty().bind(scene.widthProperty());
    hexArea.prefHeightProperty().bind(scene.heightProperty());

    primaryStage.setScene(scene);/* ww w  . j  a v a2 s  .  c o m*/
    primaryStage.setTitle("HexTest");
    primaryStage.show();

    hexArea.setContent(IOUtils.toByteArray(new FileInputStream("a.class")));
}

From source file:com.jayway.restassured.itest.java.FileDownloadITest.java

@Test
public void canDownloadLargeFiles() throws Exception {
    int expectedSize = IOUtils
            .toByteArray(getClass().getResourceAsStream("/powermock-easymock-junit-1.4.12.zip")).length;
    final InputStream inputStream = expect().log().headers().when()
            .get("http://powermock.googlecode.com/files/powermock-easymock-junit-1.4.12.zip").asInputStream();

    final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    IOUtils.copy(inputStream, byteArrayOutputStream);
    IOUtils.closeQuietly(byteArrayOutputStream);
    IOUtils.closeQuietly(inputStream);/*w w w.j a v a2s  .  co m*/

    assertThat(byteArrayOutputStream.size(), equalTo(expectedSize));
}

From source file:AIR.Common.Web.Session.ContentLoggingHttpServletRequest.java

public ContentLoggingHttpServletRequest(HttpServletRequest request) throws IOException {
    super(request);
    InputStream is = super.getInputStream();
    content = IOUtils.toByteArray(is);
    // TODO: Need to implement parsing of body parameters
}

From source file:com.imag.nespros.network.devices.SacomutDevice.java

public SacomutDevice(String name, double cpuSpeed, int totalMemory) {
    super(name, cpuSpeed, totalMemory, DeviceType.SACOMUT);
    try {/* w  w  w . j  av  a  2 s. co  m*/
        byte[] imageInByte;
        imageInByte = IOUtils.toByteArray(getClass().getClassLoader().getResourceAsStream("image/sacomut.jpg"));
        icon = new MyLayeredIcon(new ImageIcon(imageInByte).getImage());
    } catch (IOException ex) {
        Logger.getLogger(AMIDevice.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.mengge.service.local.Scripts.java

public File getScriptFile() {
    InputStream inputStream = getClass().getResourceAsStream(RESOURCE_FOLDER + this.script);
    byte[] bytes;
    try {/*from  w ww.  j a  v a2  s .  c  o m*/
        bytes = IOUtils.toByteArray(inputStream);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    String[] splittedName = this.script.split("\\.");
    File scriptFile;
    try {
        scriptFile = File.createTempFile(splittedName[0], "." + splittedName[1]);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    if (!scriptFile.exists()) {
        try {
            scriptFile.createNewFile();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    FileOutputStream output;
    try {
        output = new FileOutputStream(scriptFile, true);
    } catch (FileNotFoundException e) {
        throw new RuntimeException(e);
    }

    try {
        output.write(bytes);
        output.flush();
        output.close();
        return scriptFile;
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

}

From source file:com.oculusinfo.tile.util.AvroJSONConverter.java

/**
 * Convert an Avro input stream into a JSON object
 * //from w w w .  j a  v a2  s .  c  o m
 * @param stream The input data
 * @return A JSON representation of the input data
 * @throws IOException
 * @throws JSONException
 */
public static JSONObject convert(InputStream stream) throws IOException, JSONException {
    SeekableInput input = new SeekableByteArrayInput(IOUtils.toByteArray(stream));
    ByteArrayOutputStream output = new ByteArrayOutputStream();

    // Conversion code taken from org.apache.avro.tool.DataFileReadTool
    GenericDatumReader<Object> reader = new GenericDatumReader<Object>();
    FileReader<Object> fileReader = DataFileReader.openReader(input, reader);
    try {
        Schema schema = fileReader.getSchema();
        DatumWriter<Object> writer = new GenericDatumWriter<Object>(schema);
        JsonEncoder encoder = EncoderFactory.get().jsonEncoder(schema, output);
        for (Object datum : fileReader) {
            encoder.configure(output);
            writer.write(datum, encoder);
            encoder.flush();
            // For some reason, we only contain one record, but the 
            // decoding thinks we contain more and fails; so just break 
            // after our first one.
            break;
        }
        output.flush();
    } finally {
        fileReader.close();
    }
    String jsonString = output.toString("UTF-8");
    return new JSONObject(jsonString);
}