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.sixt.service.framework.jetty.RpcReadException.java

public String toJson(HttpServletRequest req) {
    JsonObject obj = new JsonObject();

    Enumeration<String> h = req.getHeaderNames();
    while (h.hasMoreElements()) {
        String hKey = h.nextElement();
        String hValue = req.getHeader(hKey);
        obj.addProperty("request_header_" + hKey, hValue);
    }//from   w w w .j  a v  a 2s  . co  m

    obj.addProperty("exception_message", this.getMessage());
    obj.addProperty("request_query_string", req.getQueryString());
    obj.addProperty("request_url", req.getRequestURL().toString());
    obj.addProperty("request_remote_addr", req.getRemoteAddr());
    obj.addProperty("request_remote_port", req.getRemotePort());
    obj.addProperty("request_remote_host", req.getRemoteHost());
    obj.addProperty("request_remote_user", req.getRemoteUser());

    String readBody = "success";
    // read the whole remaining body and put the joined base64 encoded message into the json object
    try {
        byte[] ba = IOUtils.toByteArray(this.in);
        byte[] combined;
        if ((ba != null) && (this.incomplete != null)) {
            combined = new byte[ba.length + this.incomplete.length];
            System.arraycopy(incomplete, 0, combined, 0, this.incomplete.length);
            System.arraycopy(ba, 0, combined, this.incomplete.length, ba.length);
            obj.addProperty("request_body", Base64.getEncoder().encodeToString(combined));
        } else if (ba != null) {
            combined = ba;
        } else if (this.incomplete != null) {
            combined = this.incomplete;
        } else {
            readBody = "body is empty";
        }
    } catch (Exception ex) {
        readBody = String.format("failed because: %s", ex.getCause());
    }
    obj.addProperty("read_body", readBody);

    return obj.toString();
}

From source file:com.systematic.healthcare.fhir.generator.UrlStructureDefinitionProvider.java

private String urlToContentString(URL url) throws IOException {
    try (InputStream in = url.openStream()) {
        return new String(IOUtils.toByteArray(in), "UTF-8");
    }//from  w  w  w  .  j  a  v a2 s.  c o  m
}

From source file:flexus.web.servlet.StartMenusServlet.java

/**
 * @param request/* w  w  w  .j  a v  a  2s .c  o  m*/
 * @param response
 */
private void doProcess(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    request.setCharacterEncoding(charsetName);
    response.setCharacterEncoding(charsetName);

    InputStream stream = Thread.currentThread().getContextClassLoader().getResourceAsStream("startMenus.xml");
    byte[] bytes = null;
    if (stream != null && stream.available() > 0) {
        bytes = IOUtils.toByteArray(stream);
    }

    response.setContentType("text/xml");

    if (bytes != null) {
        response.getOutputStream().write(bytes);
        response.getOutputStream().flush();
    }
}

From source file:com.spartasystems.holdmail.domain.MessageContentPart.java

public void setContent(InputStream in) throws IOException {
    this.content = IOUtils.toByteArray(in);
}

From source file:com.yoncabt.ebr.logger.db.BaseDBReportLogger.java

@Override
public void logReport(ReportRequest request, ReportOutputFormat outputFormat, InputStream reportData)
        throws IOException {
    String table = EBRConf.INSTANCE.getValue(EBRParams.REPORT_LOGGER_DBLOGGER_TABLENAME, "log_reports");
    String sql = String.format("update %s set report_data = ? where id = ?", table);
    byte[] buff = IOUtils.toByteArray(reportData);

    try (EBRConnection con = dataSourceManager.get("dblogger", request.getUser(), "EBR",
            getClass().getSimpleName());) {
        con.setAutoCommit(false);/*  w w w.  j  a  va2  s .c om*/
        try (PreparedStatement ps = con.prepareStatement(sql)) {
            ps.setBinaryStream(1, new ByteArrayInputStream(buff));
            ps.setString(2, request.getUuid());
            if (ps.executeUpdate() == 1) {// daha nce loglanm bir rapor ise sadece gncelle
                con.commit();
                return;
            }
            con.commit();
        }

        sql = String.format("insert into %s (" + "id, report_name, time_stamp, "
                + "request_params, report_data, file_extension," + "data_source_name, email, report_locale,"
                + "report_user) " + "values(" + "?, ?, ?," + "?, ?, ?," + "?, ?, ?," + "?)", table);
        try (PreparedStatement ps = con.prepareStatement(sql)) {
            ps.setString(1, request.getUuid());
            ps.setString(2, request.getReport());
            ps.setTimestamp(3, new Timestamp(System.currentTimeMillis()));

            JSONObject jo = new JSONObject(request.getReportParams());
            ps.setString(4, jo.toString(4));
            ps.setBinaryStream(5, new ByteArrayInputStream(buff));
            ps.setString(6, request.getExtension());

            ps.setString(7, request.getDatasourceName());
            ps.setString(8, request.getEmail());
            ps.setString(9, request.getLocale());

            ps.setString(10, request.getUser());

            ps.executeUpdate();
            con.commit();
        }
    } catch (SQLException ex) {
        Logger.getLogger(BaseDBReportLogger.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:edu.hawaii.soest.hioos.storx.StorXParserTest.java

@Before
public void setUp() {

    // read the sample data from a binary StorX file
    try {//from  ww  w.  j av  a 2 s. co  m

        // Set up a simple logger that logs to the console
        BasicConfigurator.configure();

        // create a byte buffer from the binary file data
        storXData = this.getClass().getResourceAsStream("/edu/hawaii/soest/kilonalu/ctd/16364020.RAW");
        dataAsByteArray = IOUtils.toByteArray(storXData);
        buffer = ByteBuffer.wrap(dataAsByteArray);

        // create a parser instance and test that it succeeds
        this.parser = new StorXParser();

    } catch (IOException ioe) {
        fail("There was a problem reading the" + " data file.  The error was: " + ioe.getMessage());

    } catch (NullPointerException npe) {
        fail("There was a problem reading the" + " data file.  The error was: " + npe.getMessage());

    }

}

From source file:com.tbodt.jswerve.servlet.JSwerveServlet.java

@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    if (req.getMethod().equals("OPTIONS")) {
        serviceOptions(req, resp);/*w w  w.ja  va 2  s  .  c om*/
        return;
    }

    HttpMethod method = HttpMethod.valueOf(req.getMethod());
    URI uri = extractUri(req);
    Headers headers = translateHeaders(req);
    Content content = new Content(IOUtils.toByteArray(req.getInputStream()), req.getContentType());
    Request request = new Request(method, uri, headers, content);
    try {
        Response response = website.service(request);
        resp.setStatus(response.getStatus().getCode());
        for (Map.Entry<String, String> header : response.getHeaders())
            resp.setHeader(header.getKey(), header.getValue());
        resp.getOutputStream().write(response.getBody().getData());
    } catch (StatusCodeException ex) {
        resp.setStatus(ex.getStatusCode().getCode());
        ex.printStackTrace(resp.getWriter());
    }
}

From source file:com.talis.storage.memory.MemoryStoreTest.java

/**
 * At the moment, on MemoryStore can guarantee the entity of the 
 * StoredItem returned by write will match that of the 
 * SubmittedItem because there's no chunking involved. See
 * TODO item in S3Store.write() re: making an entity stream
 * using reconstructChunks() or similar when writing
 *///from   w  ww .  j a  va 2 s  .co m
@Test
public void storedItemHasExpectedEntity() throws Exception {
    SubmittedItem submitted = new SubmittedItem(MediaType.TEXT_PLAIN_TYPE, new ByteArrayInputStream(data));
    StoredItem stored = store.write(itemURI, submitted);
    assertTrue(Arrays.equals(data, IOUtils.toByteArray(stored.getEntity())));
}

From source file:jenkins.plugins.publish_over.helper.InputStreamMatcher.java

public boolean matches(final Object argument) {
    if (!(argument instanceof InputStream))
        return false;

    try {//www .jav a  2 s. c o  m
        final byte[] actual = IOUtils.toByteArray((InputStream) argument);
        if (LOG.isDebugEnabled()) {
            LOG.debug("Expected (md5) = " + DigestUtils.md5Hex(expectedContents));
            LOG.debug("Actual   (md5) = " + DigestUtils.md5Hex(actual));
        }
        return Arrays.equals(expectedContents, actual);
    } catch (IOException ioe) {
        throw new RuntimeException("Failed to read contents of InputStream", ioe);
    }
}

From source file:com.eviware.soapui.impl.wsdl.support.CompressionSupport.java

public static byte[] decompress(String alg, byte[] content) throws Exception {
    // Use the excellent content encoding handling that exists in HTTP Client
    HttpResponse response = new BasicHttpResponse(new BasicStatusLine(new HttpVersion(1, 0), 0, null));
    ByteArrayEntity entity = new ByteArrayEntity(content);
    entity.setContentEncoding(alg);//w w  w.  j  a  v  a 2 s .c  o  m
    response.setEntity(entity);
    new ResponseContentEncoding().process(response, null);
    return IOUtils.toByteArray(response.getEntity().getContent());
}