Example usage for java.io ByteArrayOutputStream flush

List of usage examples for java.io ByteArrayOutputStream flush

Introduction

In this page you can find the example usage for java.io ByteArrayOutputStream flush.

Prototype

public void flush() throws IOException 

Source Link

Document

Flushes this output stream and forces any buffered output bytes to be written out.

Usage

From source file:com.kurento.kmf.content.internal.ControlProtocolManager.java

/**
 * Receiver method for JSON throw a request.
 * /*from w w w .j a  v a  2 s  . c  om*/
 * @param asyncCtx
 *            Asynchronous context
 * @return Received JSON encapsulated as a Java class
 */
public JsonRpcRequest receiveJsonRequest(AsyncContext asyncCtx) {
    HttpServletRequest request = (HttpServletRequest) asyncCtx.getRequest();

    // Received character encoding should be UTF-8. In order to check this,
    // the method detectJsonEncoding will be used. Before that, the
    // InputStream read from request.getInputStream() should be cloned
    // (using a ByteArrayOutputStream) to be used on detectJsonEncoding and
    // then for reading the JSON message

    try {
        InputStream inputStream = request.getInputStream();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buffer = new byte[BUFF];
        int len;
        while ((len = inputStream.read(buffer)) > -1) {
            baos.write(buffer, 0, len);
        }
        baos.flush();

        String encoding = detectJsonEncoding(new ByteArrayInputStream(baos.toByteArray()));
        log.debug("Detected JSON encoding: " + encoding);
        if (encoding == null) {
            throw new KurentoMediaFrameworkException(
                    "Invalid or unsupported charset encondig in received JSON request", 10018);
        }

        InputStreamReader isr = new InputStreamReader(new ByteArrayInputStream(baos.toByteArray()), encoding);

        JsonRpcRequest jsonRequest = gson.fromJson(isr, JsonRpcRequest.class);
        Assert.notNull(jsonRequest.getMethod());
        log.info("Received JsonRpc request ...\n " + jsonRequest.toString());
        return jsonRequest;
    } catch (IOException e) {
        // TODO: trace this exception and double check appropriate JsonRpc
        // answer is sent
        throw new KurentoMediaFrameworkException(
                "IOException reading JsonRPC request. Cause: " + e.getMessage(), e, 20016);
    }
}

From source file:codes.thischwa.c5c.impl.LocalConnector.java

@Override
public StreamContent resize(InputStream imageIn, String imageExt, Dimension dim) throws IOException {
    BufferedImage img = null;/*from w  w  w.jav  a2  s  . c o m*/
    BufferedImage newImg = null;
    try {
        img = ImageIO.read(imageIn);
        newImg = Scalr.resize(img, Scalr.Method.BALANCED, Scalr.Mode.AUTOMATIC, dim.width, dim.height);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(newImg, imageExt, baos);
        baos.flush();
        return buildStreamContent(new ByteArrayInputStream(baos.toByteArray()), baos.size());
    } catch (IllegalArgumentException | ImagingOpException e) {
        throw new IOException(e);
    } finally {
        if (img != null)
            img.flush();
        if (newImg != null)
            newImg.flush();
    }
}

From source file:com.icesoft.faces.component.outputchart.AbstractChart.java

public void encode(FacesContext context, OutputChart outputChart) throws Throwable {
    //if type is dynamic here we should update it
    String type = outputChart.getType();
    Chart currentChart = getChart();//from  w  w w. jav a 2s  .  c  o  m
    if (chart == currentChart) {
        buildChart(outputChart);
    }
    if (getChart() != null) {
        if (outputChart.isClientSideImageMap()) {
            generateMap(getChart());
        }
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        JPEGEncoder.encode(getChart(), 1.0f, bos);
        byte[] data = bos.toByteArray();
        bos.flush();
        bos.close();
        bos = null;
        outputChart.setChartResource(new ChartResource(data));
        outputChart.setChartURI(
                ResourceRegistryLocator.locate(context).registerResource(outputChart.getChartResource()));
    } else {
        log.equals("The jchart is not defined for the "
                + outputChart.getClientId(FacesContext.getCurrentInstance())
                + ", please check if the proper [type] has been defined");
    }
}

From source file:com.streamsets.pipeline.lib.parser.protobuf.TestProtobufDataParser.java

@Test
public void testMissingRequiredField() throws Exception {
    ByteArrayOutputStream bOut = new ByteArrayOutputStream();
    PersonProto.Person john = PersonProto.Person.newBuilder().setId(1).setName("John Doe")
            .addEmail("jdoe" + "@example.com")
            .addPhone(PersonProto.Person.PhoneNumber.newBuilder().setNumber("7568345")).build();
    john.writeDelimitedTo(bOut);// ww w.  ja  v  a  2 s  . c  om
    bOut.flush();

    DataParserFactory factory = getDataParserFactory("test1.desc", "util.Person");
    DataParser parser = factory.getParser("Person", new ByteArrayInputStream(bOut.toByteArray()), "0");

    try {
        parser.parse();
        Assert.fail("DataParserException expected as a required field is missing");
    } catch (DataParserException e) {
        assertEquals(Errors.DATA_PARSER_02, e.getErrorCode());
    }
}

From source file:fr.aliasource.webmail.server.proxy.client.http.MoveMessageMethod.java

public String streamString(InputStream in, boolean closeIn) throws IOException {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    final byte[] buffer = new byte[100000];
    try {/*from  ww w  .  j a  v a2 s .c  o  m*/
        while (true) {
            int amountRead = in.read(buffer);
            if (amountRead == -1) {
                break;
            }
            out.write(buffer, 0, amountRead);
        }
    } finally {
        if (closeIn) {
            in.close();
        }
        out.flush();
        out.close();
    }
    return new String(out.toByteArray());
}

From source file:eu.databata.SupplementPropagation.java

private String getHash(InputStream in) {
    MessageDigest md5;//from  w  w w .java 2  s . c o  m
    try {
        md5 = MessageDigest.getInstance("MD5");
    } catch (NoSuchAlgorithmException e) {
        throw new IllegalArgumentException("No MD5 algorithm found!", e);
    }
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    byte[] buffer = new byte[1024];
    int read;
    try {
        while ((read = in.read(buffer)) != -1) {
            os.write(buffer, 0, read);
        }
        os.flush();
        md5.update(os.toByteArray());
    } catch (IOException e) {
        throw new IllegalStateException("Error reading file.", e);
    } finally {
        try {
            in.close();
            os.close();
        } catch (IOException e) {
            throw new IllegalStateException("Error closing stream ", e);
        }
    }
    return convertToHex(md5.digest());
}

From source file:org.apache.nutch.searcher.response.xml.XMLResponseWriter.java

public void writeResponse(SearchResults results, HttpServletRequest request, HttpServletResponse response)
        throws IOException {

    try {//www  .  j a  v  a  2s  .  com

        // create the xml document and add the results and search nodes
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        Document xmldoc = factory.newDocumentBuilder().newDocument();
        Element resEl = addNode(xmldoc, xmldoc, "results");
        Element searchEl = addNode(xmldoc, resEl, "search");

        // add common nodes
        String query = results.getQuery();
        addNode(xmldoc, searchEl, "query", query);
        addNode(xmldoc, searchEl, "totalhits", String.valueOf(results.getTotalHits()));
        String lang = results.getLang();
        if (lang != null) {
            addNode(xmldoc, searchEl, "lang", lang);
        }
        String sort = results.getSort();
        if (sort != null) {
            addNode(xmldoc, searchEl, "sort", sort);
        }
        addNode(xmldoc, searchEl, "reverse", results.isReverse() ? "true" : "false");
        addNode(xmldoc, searchEl, "start", String.valueOf(results.getStart()));
        addNode(xmldoc, searchEl, "end", String.valueOf(results.getEnd()));
        addNode(xmldoc, searchEl, "rows", String.valueOf(results.getRows()));
        addNode(xmldoc, searchEl, "totalhits", String.valueOf(results.getTotalHits()));
        addNode(xmldoc, searchEl, "withSummary", String.valueOf(results.isWithSummary()));

        String[] searchFields = results.getFields();
        Set<String> fieldSet = new HashSet<String>();
        if (searchFields != null && searchFields.length > 0) {
            addNode(xmldoc, searchEl, "fields", StringUtils.join(searchFields, ","));
            for (int i = 0; i < searchFields.length; i++) {
                fieldSet.add(searchFields[i]);
            }
        }

        // add documents
        Element documents = addNode(xmldoc, resEl, "documents");
        HitDetails[] details = results.getDetails();
        Hit[] hits = results.getHits();
        Summary[] summaries = results.getSummaries();
        for (int i = 0; i < details.length; i++) {

            // every document has an indexno and an indexdocno
            Element document = addNode(xmldoc, documents, "document");
            addAttribute(xmldoc, document, "indexno", String.valueOf(hits[i].getIndexNo()));
            addAttribute(xmldoc, document, "indexkey", String.valueOf(hits[i].getUniqueKey()));

            // don't add summaries not including summaries
            if (summaries != null && results.isWithSummary()) {
                String encSumm = Entities.encode(summaries[i].toString());
                addNode(xmldoc, document, "summary", encSumm);
            }

            // add the fields from hit details
            Element fields = addNode(xmldoc, document, "fields");
            HitDetails detail = details[i];
            for (int j = 0; j < detail.getLength(); j++) {
                String fieldName = detail.getField(j);
                String[] fieldValues = detail.getValues(fieldName);

                // if we specified fields to return, only return those fields
                if (fieldSet.size() == 0 || fieldSet.contains(fieldName)) {
                    Element field = addNode(xmldoc, fields, "field");
                    addAttribute(xmldoc, field, "name", fieldName);
                    for (int k = 0; k < fieldValues.length; k++) {
                        String encFieldVal = Entities.encode(fieldValues[k]);
                        addNode(xmldoc, field, "value", encFieldVal);
                    }
                }
            }
        }

        // get the xml source and a transformer to print it out
        DOMSource source = new DOMSource(xmldoc);
        TransformerFactory transFactory = TransformerFactory.newInstance();
        Transformer transformer = transFactory.newTransformer();

        // pretty printing can be set through configuration
        if (prettyPrint) {
            transformer.setOutputProperty("indent", "yes");
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
        }

        // write out the content to a byte array
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        StreamResult result = new StreamResult(baos);
        transformer.transform(source, result);
        baos.flush();
        baos.close();

        // cache control headers
        SimpleDateFormat sdf = new SimpleDateFormat("E, d MMM yyyy HH:mm:ss 'GMT'");
        long relExpiresInMillis = System.currentTimeMillis() + (1000 * maxAgeInSeconds);
        response.setContentType(contentType);
        response.setHeader("Cache-Control", "max-age=" + maxAgeInSeconds);
        response.setHeader("Expires", sdf.format(relExpiresInMillis));

        // write out the content to the response
        response.getOutputStream().write(baos.toByteArray());
        response.flushBuffer();
    } catch (Exception e) {
        throw new IOException(e);
    }

}

From source file:org.opentestsystem.authoring.testauth.rest.ScoringRuleController.java

@RequestMapping(value = "/scoringRule/conversionTableFile/{fileGridId}", method = RequestMethod.GET)
@Secured({ "ROLE_Scoring Rule Read" })
// NOTE: there is intentionally no @PreAuthorize annotation...ability to read scoring rule is all that is needed since scoring rule conversion table files are non-tenanted
public ResponseEntity<byte[]> getConversionTableFile(@PathVariable final String fileGridId,
        final HttpServletResponse response) {
    final ByteArrayOutputStream ret = new ByteArrayOutputStream();
    String filename = null;/*w  w w .ja v  a2 s  . co  m*/
    try {
        final GridFSDBFile grid = this.scoringRuleService.getConversionTableFile(fileGridId);
        grid.writeTo(ret);
        filename = grid.getFilename();
        ret.flush();
    } catch (final IOException e) {
        throw new LocalizedException("scoringRule.conversionTableFile.notfound", new String[] { fileGridId },
                e);
    }
    final byte[] bytes = ret.toByteArray();
    final HttpHeaders responseHeaders = buildResponseHeaders(bytes.length, filename);
    return new ResponseEntity<byte[]>(bytes, responseHeaders, HttpStatus.OK);
}

From source file:com.github.rwitzel.streamflyer.support.ProcessEndOfStreamTest.java

/**
 * @param flush/*from   w w w.j  a  v a2  s.co m*/
 * @return Returns true if the actual output is equals to the expected
 *         output.
 * @throws Exception
 */
private boolean rewriteContent(boolean flush, String domainPrefix) throws Exception {
    String contentPart = StringUtils.repeat("text", 2);
    String oldUrl = domainPrefix + "something";
    String expectedNewUrl = domainPrefix + "anything";
    String oldHtml = "<html><body>" + contentPart + oldUrl + contentPart + "</body></html>";
    String expectedNewHtml = "<html><body>" + contentPart + expectedNewUrl + contentPart + "</body></html>";
    String encoding = "UTF-8";

    ByteArrayOutputStream os = new ByteArrayOutputStream();
    long written = rewriteContent(new ReaderInputStream(new StringReader(oldHtml)), os, encoding, flush);
    System.out.println("written: " + written);
    System.out.println("oldHtml.length(): " + oldHtml.length());
    System.out.println("expectedNewHtml.length(): " + expectedNewHtml.length());
    System.out.println("expectedNewHtml: \n" + expectedNewHtml);
    os.flush();
    String newHtml = new String(os.toByteArray(), encoding);
    System.out.println(newHtml);
    return expectedNewHtml.equals(newHtml);
}

From source file:jcuda.utils.KernelLauncher.java

/**
 * Reads the data from the given inputStream and returns it as
 * a 0-terminated byte array./* www.j  a  v a2  s.c  o m*/
 *
 * @param inputStream The inputStream to read
 * @return The data from the inputStream
 */
private static byte[] loadData(InputStream inputStream) {
    ByteArrayOutputStream baos = null;
    try {
        baos = new ByteArrayOutputStream();
        byte buffer[] = new byte[8192];
        while (true) {
            int read = inputStream.read(buffer);
            if (read == -1) {
                break;
            }
            baos.write(buffer, 0, read);
        }
        baos.write('\0');
        baos.flush();
        return baos.toByteArray();
    } catch (IOException e) {
        throw new CudaException("Could not load data", e);
    } finally {
        if (baos != null) {
            try {
                baos.close();
            } catch (IOException e) {
                throw new CudaException("Could not close output", e);
            }
        }
    }

}