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.opensymphony.webwork.util.classloader.listeners.ReloadingListener.java

public void onStop(final File pRepository) {
    boolean reload = false;

    log.debug("created:" + created.size() + " changed:" + changed.size() + " deleted:" + deleted.size());

    if (deleted.size() > 0) {
        for (Iterator it = deleted.iterator(); it.hasNext();) {
            final File file = (File) it.next();
            store.remove(com.opensymphony.webwork.util.classloader.ReloadingClassLoader.clazzName(pRepository,
                    file));// w  w w.j  av a  2 s .  c om
        }
        reload = true;
    }

    if (created.size() > 0) {
        for (Iterator it = created.iterator(); it.hasNext();) {
            final File file = (File) it.next();
            try {
                final byte[] bytes = IOUtils.toByteArray(new FileReader(file));
                store.write(com.opensymphony.webwork.util.classloader.ReloadingClassLoader
                        .clazzName(pRepository, file), bytes);
            } catch (final Exception e) {
                log.error("could not load " + file, e);
            }
        }
    }

    if (changed.size() > 0) {
        for (Iterator it = changed.iterator(); it.hasNext();) {
            final File file = (File) it.next();
            try {
                final byte[] bytes = IOUtils.toByteArray(new FileReader(file));
                store.write(com.opensymphony.webwork.util.classloader.ReloadingClassLoader
                        .clazzName(pRepository, file), bytes);
            } catch (final Exception e) {
                log.error("could not load " + file, e);
            }
        }
        reload = true;
    }

    notifyOfCheck(reload);
}

From source file:com.markuspage.jbinrepoproxy.standalone.transport.sun.URLConnectionTransportClientImpl.java

@Override
public TransportFetch httpGetTheFile() {
    TransportFetch result;//  w ww.j a  va 2 s  . co  m
    try {
        final URL url = new URL(serverURL + theFileURI);

        final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setAllowUserInteraction(false);
        final int responseCode = conn.getResponseCode();
        final String responseMessage = conn.getResponseMessage();
        InputStream responseIn = conn.getErrorStream();
        if (responseIn == null) {
            responseIn = conn.getInputStream();
        }

        // Read the body to the output if OK otherwise to the error message
        final byte[] body = IOUtils.toByteArray(responseIn);

        this.targetResponse = new TargetResponse(responseCode, conn.getHeaderFields(), body);

        result = new TransportFetch(responseCode, responseMessage, body);
    } catch (MalformedURLException ex) {
        LOG.error("Malformed URL", ex);
        result = new TransportFetch(500, ex.getLocalizedMessage(), null);
    } catch (IOException ex) {
        LOG.error("IO error", ex);
        result = new TransportFetch(500, ex.getLocalizedMessage(), null);
    }

    return result;
}

From source file:com.test.movierecordsjsf.controller.MovieRecordsController.java

public void uploadXML() {
    if (file != null) {

        try {// w  w w  . j a va  2 s.  co m
            InputStream is = file.getInputstream();

            byte[] contents = IOUtils.toByteArray(is);
            is.close();
            Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder()
                    .parse(new ByteArrayInputStream(contents));

            NodeList nlist = doc.getElementsByTagName("Movie");

            for (int i = 0; i < nlist.getLength(); i++) {
                Node nod = nlist.item(i);
                MovieRecords movieRecord = new MovieRecords();
                NodeList dataMovie = nod.getChildNodes();
                for (int j = 0; j < dataMovie.getLength(); j++) {

                    Node data = dataMovie.item(j);
                    if (data.getNodeType() == Node.ELEMENT_NODE) {
                        if (null != data.getNodeName()) //Show data type
                        {
                            switch (data.getNodeName()) {
                            case "title": {
                                //The value is contained in a child node Element
                                Node dataContect = data.getFirstChild();
                                //Show the value in the node to be of type Text
                                if (dataContect != null && dataContect.getNodeType() == Node.TEXT_NODE) {
                                    movieRecord.setTitle(dataContect.getNodeValue());

                                }
                                break;
                            }
                            case "description": {
                                //The value is contained in a child node Element
                                Node dataContect = data.getFirstChild();
                                //Show the value in the node to be of type Text
                                if (dataContect != null && dataContect.getNodeType() == Node.TEXT_NODE) {
                                    movieRecord.setDescription(dataContect.getNodeValue());
                                }
                                break;
                            }
                            case "size": {
                                System.out.print(data.getNodeName() + ": ");
                                //The value is contained in a child node Element
                                Node dataContect = data.getFirstChild();
                                //Show the value in the node to be of type Text
                                if (dataContect != null && dataContect.getNodeType() == Node.TEXT_NODE) {
                                    movieRecord.setSize(Integer.parseInt(dataContect.getNodeValue()));
                                }
                                break;
                            }
                            case "rating": {

                                //The value is contained in a child node Element
                                Node dataContect = data.getFirstChild();
                                //Show the value in the node to be of type Text
                                if (dataContect != null && dataContect.getNodeType() == Node.TEXT_NODE) {
                                    movieRecord.setRating(Integer.parseInt(dataContect.getNodeValue()));

                                }
                                break;
                            }
                            case "checksum": {

                                //The value is contained in a child node Element
                                Node dataContect = data.getFirstChild();
                                //Show the value in the node to be of type Text
                                if (dataContect != null && dataContect.getNodeType() == Node.TEXT_NODE) {
                                    movieRecord.setChecksum(dataContect.getNodeValue());

                                }
                                break;
                            }
                            case "staring": {

                                //The value is contained in a child node Element
                                Node dataContect = data.getFirstChild();
                                //Show the value in the node to be of type Text
                                if (dataContect != null && dataContect.getNodeType() == Node.TEXT_NODE) {
                                    movieRecord.setStaring(dataContect.getNodeValue());

                                }
                                break;
                            }
                            default:
                                break;
                            }
                        }
                    }

                }
                movieRecordFacade.create(movieRecord);

            }
            listMovie();

        } catch (Exception ex) {
            Logger.getLogger(MovieRecordsController.class.getName()).log(Level.SEVERE, null, ex);

        }

        JsfUtil.msgInfo(file.getFileName() + " successfully uploaded.");

    }
}

From source file:cpcc.core.utils.GeoJsonStreamResponseTest.java

@Test
public void shouldIgnoreCallsToPrepareResponse() throws IOException {
    FeatureCollection featureCollection = new FeatureCollection();
    byte[] expected = new ObjectMapper().disable(SerializationFeature.INDENT_OUTPUT)
            .writeValueAsBytes(featureCollection);

    GeoJsonStreamResponse sut = new GeoJsonStreamResponse(featureCollection);

    Response response = mock(Response.class);
    sut.prepareResponse(response);//w w w . ja v  a  2 s. c o m

    verifyZeroInteractions(response);

    byte[] actual = IOUtils.toByteArray(sut.getStream());

    assertThat(sut.getContentType()).isEqualTo("application/json");
    assertThat(actual).isEqualTo(expected);
}

From source file:it.staiger.jmeter.services.FileContentServer.java

/**
 * Retrieves the content f a file as a byte array
 *
 * @param file File of which the content is to be returned
 *///from   ww  w .jav  a  2s . co m
private byte[] getFile(File file) {
    try {
        return IOUtils.toByteArray(new FileInputStream(file));
    } catch (IOException e1) {
        log.error("Could not read file " + file.getPath());
        e1.printStackTrace();
        return null;
    }
}

From source file:com.hierynomus.smbj.server.StubSmbServer.java

private void runServer() {
    try (Socket accept = socket.accept()) {
        InputStream inputStream = accept.getInputStream();
        OutputStream outputStream = accept.getOutputStream();
        while (!stop.get()) {
            int packetLength = readTcpHeader(inputStream);
            // Read the SMB packet
            IOUtils.read(inputStream, new byte[packetLength]);
            if (stubbedResponses.size() > 0) {
                Response response = stubbedResponses.remove(0);
                byte[] b = IOUtils.toByteArray(response.getBytes());
                outputStream/* ww  w . j  a  va2  s .c  o  m*/
                        .write(new Buffer.PlainBuffer(Endian.BE).putByte((byte) 0).putUInt24(b.length).array());
                outputStream.write(b);
                outputStream.flush();
            } else {
                throw new NoSuchElementException("The response list is empty!");
            }
        }

    } catch (IOException | Buffer.BufferException e) {
        serverException.set(new RuntimeException(e));
        throw serverException.get();
    }
}

From source file:br.com.topsys.cd.util.AssinaturaDigital.java

private byte[] assinar(CertificadoDigital certificadoDigital, byte[] hash) throws CertificadoDigitalException {
    byte[] retorno = null;
    try {//from www .  j  a  v a2s . com

        PDDE carimbo = PDDEFactory.getPDDE("pdde-teste.bry.com.br");
        carimbo.setPorta(318);
        carimbo.setCertReq(false);

        Assinador assinador = new Assinador(certificadoDigital.getRepositorio());
        assinador.setCarimbadora(carimbo);

        assinador.setCarregaCadeiaRepositorio(true);
        assinador.setObterLCROnline(true); // adiciona a lista de certificados revogados na assinatura
        assinador.setFormatoDadosMemoria(0);
        List<InputStream> docs = new ArrayList<InputStream>();

        docs.add(new ByteArrayInputStream(hash));

        ContextoAssinaturaCMS contexto = new ContextoAssinaturaCMS(certificadoDigital.getX509Certificado(),
                docs);

        contexto.setIncluirCarimbo(true);
        contexto.setAlgoritmoHash(AlgoritmoHash.SHA256);
        contexto.setTipoAssinatura(TipoAssinatura.CONTEUDO);

        retorno = IOUtils.toByteArray(assinador.assinar(contexto).get(0));

    } catch (ExcecaoCMS ex) {
        throw new CertificadoDigitalException("Erro assinando o documento!", ex);
    } catch (IOException ex) {
        Logger.getLogger(AssinaturaDigital.class.getName()).log(Level.SEVERE, null, ex);
    }
    return retorno;
}

From source file:eionet.gdem.dto.ConvertedFileDto.java

/**
 * Get file content as byte array/* ww w  .  j av  a2 s. com*/
 * @return File contents
 * @throws GDEMException If an error occurs.
 */
public byte[] getFileContentAsByteArray() throws GDEMException {
    FileInputStream fis = null;
    File convFile = new File(getFilePath());
    byte[] result;
    try {
        fis = new FileInputStream(convFile);
        result = IOUtils.toByteArray(fis);
    } catch (IOException e) {
        LOGGER.error("Converted file not found: " + getFilePath());
        throw new GDEMException("Converted file not found: " + getFileName());
    } finally {
        IOUtils.closeQuietly(fis);
    }
    Utils.deleteFile(convFile);
    return result;
}

From source file:io.github.jass2125.pesoa.jpa.core.servlets.RegisterImageServlet.java

public byte[] getImage(HttpServletRequest req) throws IOException, ServletException {
    List<Part> parts = (List<Part>) req.getParts();
    for (Part it : parts) {
        if (it.getName().equals("img")) {
            InputStream stream = it.getInputStream();
            return IOUtils.toByteArray(stream);
        }/*from  w  ww  . j a  v a 2  s .c o  m*/
    }
    return null;
}

From source file:com.gargoylesoftware.htmlunit.html.HtmlImage2Test.java

private void loadImage(final String src) throws Exception {
    final InputStream is = getClass().getClassLoader().getResourceAsStream("testfiles/tiny-jpg.img");
    final byte[] directBytes = IOUtils.toByteArray(is);
    is.close();//  w ww .j a  v  a 2  s .  c  o m

    final URL urlImage = new URL(URL_FIRST, "img.jpg");
    final List<NameValuePair> emptyList = Collections.emptyList();
    getMockWebConnection().setResponse(urlImage, directBytes, 200, "ok", "image/jpg", emptyList);

    final String html = "<html><head>\n" + "<script>\n" + "  function test() {\n"
            + "    var img = document.getElementById('myImage');\n" + "    img.width;\n" // this forces image loading in htmlunit
            + "  }\n" + "</script>\n" + "</head><body onload='test()'>\n" + "  <img id='myImage' " + src
            + " >\n" + "</body></html>";

    loadPage2(html);
    assertEquals(Integer.parseInt(getExpectedAlerts()[0]), getMockWebConnection().getRequestCount());
}