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:jodtemplate.io.ZipWriter.java

public void zipResources(final Resources resources, final OutputStream output) throws IOException {
    try (final ZipOutputStream zos = new ZipOutputStream(output);
            final BufferedOutputStream bos = new BufferedOutputStream(zos)) {
        for (Resource resource : resources.getResources()) {
            zos.putNextEntry(new ZipEntry(resource.getName()));
            try (final InputStream is = resource.getInputStream()) {
                zos.write(IOUtils.toByteArray(is));
            }/*from   w  w w  .ja  v a 2  s.co  m*/
            zos.closeEntry();
        }
    }
}

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

public HTACoordDevice(String name, double cpuSpeed, int totalMemory) {
    super(name, cpuSpeed, totalMemory, DeviceType.HTA_COORD);
    try {//w  ww  .  j  a v a2s  . co m
        byte[] imageInByte;
        imageInByte = IOUtils
                .toByteArray(getClass().getClassLoader().getResourceAsStream("image/htaCoord.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.cedarsoft.serialization.test.utils.AbstractJsonVersionTest2.java

@Nonnull
protected static VersionEntry create(@Nonnull Version version, @Nonnull URL expected) {
    try {// www  .j  a va  2s  .  com
        return new JsonVersionEntry(version, IOUtils.toByteArray(expected.openStream()));
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.moz.fiji.mapreduce.kvstore.lib.TestAvroRecordKeyValueStore.java

public static byte[] readResourceBytes(String resourcePath) throws IOException {
    final InputStream istream = TestAvroRecordKeyValueStore.class.getClassLoader()
            .getResourceAsStream(resourcePath);
    try {/*from  w  w w  .  j a  v  a 2 s  .  co m*/
        return IOUtils.toByteArray(istream);
    } finally {
        ResourceUtils.closeOrLog(istream);
    }
}

From source file:es.uma.inftel.blog.bean.RegistroBean.java

public String registrarUsuario() {
    if (usuarioFacade.findByName(username) != null) {
        setErrorRegistro(true);/*from  w  w  w . j a  va 2s.  c o  m*/
        return "registro";
    }
    Usuario usuario = new Usuario();
    usuario.setUsername(username);
    usuario.setPassword(password);
    usuario.setEmail(email);
    usuario.setTipo(Usuario.TIPO_NORMAL);
    try {
        usuario.setAvatar(IOUtils.toByteArray(avatar.getInputStream()));
    } catch (IOException ex) {
        Logger.getLogger(RegistroBean.class.getName()).log(Level.SEVERE, null, ex);
    }
    usuarioFacade.create(usuario);

    usuarioBean.setUsuario(usuario);

    return "index?faces-redirect=true";
}

From source file:edu.harvard.med.screensaver.io.workbook2.Workbook2UtilsTest.java

/** Requires manual inspection to verify success */
public void testImageExport() throws Exception {
    try {/*from   w  w w .j a va 2 s .co  m*/
        File file = File.createTempFile("testImageExport", ".xls");
        OutputStream out = new FileOutputStream(file);
        WritableWorkbook workbook = Workbook.createWorkbook(out);
        WritableSheet sheet = workbook.createSheet("sheet1", 0);
        InputStream imageIn = Workbook2UtilsTest.class.getResourceAsStream("arrow-first.png");
        byte[] imageData = IOUtils.toByteArray(imageIn);
        Workbook2Utils.writeCell(sheet, 1, 0, "image:");
        Workbook2Utils.writeImage(sheet, 1, 1, imageData);
        workbook.write();
        workbook.close();
        log.warn("must manually verify that image was exported to workbook " + file);
    } catch (Exception e) {
        // prefer not to maintain this type of test, so allow the error to go to console -sde4
        e.printStackTrace();
    }
}

From source file:com.iorga.iraj.security.MultiReadHttpServletRequest.java

public MultiReadHttpServletRequest(final HttpServletRequest httpServletRequest) throws IOException {
    super(httpServletRequest);
    // Read the request body and save it as a byte array
    body = IOUtils.toByteArray(super.getInputStream());
}

From source file:com.vigglet.oei.technician.UploadProfilePhoto.java

@Override
protected void preProcessRequest(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    try {/*from   w  ww  .  j  ava  2 s .co  m*/
        User user = getUser(req);

        for (Part part : req.getParts()) {
            byte[] b = IOUtils.toByteArray(part.getInputStream());
            String fileName = extractFileName(part);

            File file = new File(Content.FILE_LOCATION + "/" + fileName);
            FileOutputStream fos = new FileOutputStream(file);
            ByteArrayInputStream bais = new ByteArrayInputStream(b);
            IOUtils.copy(bais, fos);

            fos.flush();
            fos.close();
            bais.close();

            Content content = new Content();
            content.setCompany(user.getCompany());
            content.setUser(user.getId());
            content.setName(file.getName());
            content.setFilesize((int) file.length());
            content.setLocation(file.getAbsolutePath());

            ContentUtil.getInstance().insertOrUpdate(content);
        }
    } catch (ServletException ex) {
        logger.log(Level.SEVERE, null, ex);
    }
}

From source file:com.ctriposs.r2.filter.compression.DeflateCompressor.java

@Override
public byte[] inflate(InputStream data) throws CompressionException {
    byte[] input;
    try {/*from w  ww  .j a v  a2 s .  c o  m*/
        input = IOUtils.toByteArray(data);
    } catch (IOException e) {
        throw new CompressionException(CompressionConstants.DECODING_ERROR + CompressionConstants.BAD_STREAM,
                e);
    }

    Inflater zlib = new Inflater();
    zlib.setInput(input);

    ByteArrayOutputStream output = new ByteArrayOutputStream();
    byte[] temp = new byte[CompressionConstants.BUFFER_SIZE];

    int bytesRead;
    while (!zlib.finished()) {
        try {
            bytesRead = zlib.inflate(temp);
        } catch (DataFormatException e) {
            throw new CompressionException(CompressionConstants.DECODING_ERROR + getContentEncodingName(), e);
        }
        if (bytesRead == 0) {
            if (!zlib.needsInput()) {
                throw new CompressionException(CompressionConstants.DECODING_ERROR + getContentEncodingName());
            } else {
                break;
            }
        }

        if (bytesRead > 0) {
            output.write(temp, 0, bytesRead);
        }
    }

    zlib.end();
    return output.toByteArray();
}

From source file:de.jetwick.snacktory.AbstractPageReader.java

protected String readContent(InputStream response, String forceEncoding) throws IOException {
    byte[] bytes = IOUtils.toByteArray(response);
    charset = null;//from   w w w.j a  v a  2s .c o m
    String hint = null;
    if (forceEncoding != null) {
        serverReturnedEncoding = true;
        try {
            charset = Charset.forName(forceEncoding);
            hint = charset.name();
        } catch (Exception e) {
            //
        }
    }
    if (charsetDetector != null && (!respectServerEncoding || charset == null)) {
        String charsetName = charsetDetector.detect(bytes, hint);
        if (charsetName != null) {
            try {
                charset = Charset.forName(charsetName);
                detectedEncoding = charset.name();
            } catch (Exception e) {
                LOG.warn("Detected character set " + charsetName + " not supported");
            }
        }
    }
    if (charset == null) {
        LOG.warn("Defaulting to utf-8");
        charset = UTF8;
    }
    return new String(bytes, charset);
}