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:org.apache.cocoon.reading.ImageReader.java

protected byte[] readFully(InputStream in) throws IOException {
    byte tmpbuffer[] = new byte[4096];
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    int i;//  w ww. j  a  va2  s  .  com
    while (-1 != (i = in.read(tmpbuffer))) {
        baos.write(tmpbuffer, 0, i);
    }
    baos.flush();
    return baos.toByteArray();
}

From source file:com.adaptris.util.TestMultipartInput.java

public void testMultiPartInputSelectBodyPartByPosition() throws Exception {
    MultiPartOutput output = new MultiPartOutput(guid.getUUID());
    String contentId = guid.getUUID();
    byte[] payload = buildPayload();
    output.addPart(payload, ENCODING_BASE64, contentId);
    String contentId2 = guid.getUUID();
    output.addPart(PAYLOAD_1, ENCODING_8BIT, contentId2);

    MultiPartInput input = new MultiPartInput(output.getBytes(), false);
    assertEquals(NUMBER_OF_PARTS, input.size(), 2);

    MimeBodyPart bodyPart = input.getBodyPart(0);
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    StreamUtil.copyStream(bodyPart.getInputStream(), out);
    verifyProperties(new ByteArrayInputStream(out.toByteArray()));

    bodyPart = input.getBodyPart(1);/*  w ww .ja va 2  s  .c  o m*/
    out = new ByteArrayOutputStream();
    StreamUtil.copyStream(bodyPart.getInputStream(), out);
    out.flush();
    assertEquals(TXT_COMPARE_PAYLOADS, PAYLOAD_1, out.toString());
    assertTrue(input.getBodyPart(10) == null);
}

From source file:com.fa.mastodon.activity.ComposeActivity.java

@Nullable
private static byte[] inputStreamGetBytes(InputStream stream) {
    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    int read;//  w  w w.  j  av  a 2 s  .  co  m
    byte[] data = new byte[16384];
    try {
        while ((read = stream.read(data, 0, data.length)) != -1) {
            buffer.write(data, 0, read);
        }
        buffer.flush();
    } catch (IOException e) {
        return null;
    }
    return buffer.toByteArray();
}

From source file:org.apache.hama.bsp.ResourceManager.java

private byte[] getConfigurationOverride(Long groomRPCPort, Long groomPeerPort, Integer maxTasks,
        Long slotJVMHeap) {/*from   w w  w .j av a 2  s. c o  m*/
    // Create a configuration from the current configuration and
    // override properties as appropriate for the Groom server.
    Configuration overrides = new Configuration(conf);

    overrides.set("bsp.groom.rpc.port", groomRPCPort.toString());
    overrides.set("bsp.peer.port", groomPeerPort.toString());
    overrides.set("bsp.tasks.maximum", maxTasks.toString());

    overrides.set("bsp.child.java.opts", conf.get("bsp.child.java.opts") + slotJVMHeap + "m");

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {
        overrides.write(new DataOutputStream(baos));
        baos.flush();
    } catch (IOException e) {
        log.warn("Failed to serialize configuration.", e);
        System.exit(1);
    }

    return baos.toByteArray();
}

From source file:com.adaptris.util.TestMultipartInput.java

public void testMultiPartInputSelectBodyPartByContentID() throws Exception {
    MultiPartOutput output = new MultiPartOutput(guid.getUUID());
    String contentId = guid.getUUID();
    byte[] payload = buildPayload();
    output.addPart(payload, ENCODING_BASE64, contentId);
    String contentId2 = guid.getUUID();
    output.addPart(PAYLOAD_1, ENCODING_8BIT, contentId2);

    MultiPartInput input = new MultiPartInput(output.getBytes(), false);
    assertEquals(NUMBER_OF_PARTS, input.size(), 2);

    MimeBodyPart bodyPart = input.getBodyPart(contentId);
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    StreamUtil.copyStream(bodyPart.getInputStream(), out);
    verifyProperties(new ByteArrayInputStream(out.toByteArray()));

    bodyPart = input.getBodyPart(contentId2);
    out = new ByteArrayOutputStream();
    StreamUtil.copyStream(bodyPart.getInputStream(), out);
    out.flush();
    assertEquals(TXT_COMPARE_PAYLOADS, PAYLOAD_1, out.toString());
}

From source file:com.kysoft.cpsi.audit.controller.SelfCheckAjaxUploadController.java

/**
 * @param request/*ww  w  .  j  a v a 2 s  . c  o m*/
 * @param files
 * @return
 */
@RequestMapping(value = "selfCheckUpload", method = RequestMethod.POST)
@ResponseBody
public Map<String, Object> ajaxUpload(HttpServletRequest request, HttpServletResponse response, String owner,
        String col, String ownerKey, String hcrwId, String hcclName, String hcsxmc, Integer nd) {

    Map<String, Object> result = new HashedMap();

    InputStream is = null;

    String filename = request.getHeader("X-File-Name");
    try {
        is = request.getInputStream();
        String mongoId = null;

        Map<String, Object> params = new HashedMap();
        params.put("dxnType", 2);
        Map<String, Object> dxnHccl2 = selfCheckService.getDXNHccl(params);
        params.put("dxnType", 1);
        Map<String, Object> dxnHccl1 = selfCheckService.getDXNHccl(params);
        if (hcclName.equals(dxnHccl2.get("NAME").toString())
                && hcsxmc.equals(dxnHccl2.get("HCSXMC").toString())) {
            //?
            ByteArrayOutputStream baos = new ByteArrayOutputStream();

            byte[] buffer = new byte[1024];
            int len;
            while ((len = is.read(buffer)) > -1) {
                baos.write(buffer, 0, len);
            }
            baos.flush();
            // ?
            InputStream is1 = new ByteArrayInputStream(baos.toByteArray());
            InputStream is2 = new ByteArrayInputStream(baos.toByteArray());
            //?
            selfCheckService.uploadSelfCheckData(is2, hcrwId, filename, nd);

            //?MONGODB
            mongoId = FileUploadUtils.mongoUpload(is1, filename, owner, ownerKey);
        } else if (hcclName.equals(dxnHccl1.get("NAME").toString())
                && hcsxmc.equals(dxnHccl1.get("HCSXMC").toString())) {
            //???
            ByteArrayOutputStream baos = new ByteArrayOutputStream();

            byte[] buffer = new byte[1024];
            int len;
            while ((len = is.read(buffer)) > -1) {
                baos.write(buffer, 0, len);
            }
            baos.flush();

            // ?
            InputStream is1 = new ByteArrayInputStream(baos.toByteArray());
            InputStream is2 = new ByteArrayInputStream(baos.toByteArray());

            //?
            if (filename.endsWith("xls") || filename.endsWith("xlsx")) {
                selfCheckService.judgeRepeatExcle(is2, 5, 2, filename);
            }

            //?MONGODB
            mongoId = FileUploadUtils.mongoUpload(is1, filename, owner, ownerKey);
        } else {
            mongoId = FileUploadUtils.mongoUpload(is, filename, owner, ownerKey);
        }

        FileUploadUtils.updateOwner(owner, col, ownerKey, mongoId);

        response.setStatus(HttpServletResponse.SC_OK);
        result.put("status", 1);
        result.put("mongoId", mongoId);
        result.put("message", "??");

    } catch (Exception ex) {
        response.setStatus(HttpServletResponse.SC_OK);
        ex.printStackTrace();
        result.put("status", -1);
        result.put("mongoId", "");
        result.put("message", "??" + ex.getMessage());
        MongoLogger.warn("??", ExceptionUtils.getStackTrace(ex), hcrwId);
    } finally {
        try {
            is.close();
        } catch (IOException ignored) {
        }
    }
    return result;
}

From source file:at.molindo.webtools.crawler.CrawlerTask.java

private Object consumeContent(final InputStream content, String contentType, final long contentLength,
        final String encoding) throws IOException {
    if (contentType == null) {
        contentType = "";
    }//w ww  .j  av a 2  s. c o  m

    try {
        if (contentType.startsWith("text/")) {
            final BufferedReader r = new BufferedReader(
                    new InputStreamReader(content, encoding == null ? "utf-8" : encoding));

            String line;
            final StringBuilder buf = new StringBuilder();

            while ((line = r.readLine()) != null) {
                buf.append(line).append("\n");
            }
            if (buf.length() > 0) {
                buf.setLength(buf.length() - 1);
            }
            return buf.toString();
        } else {
            final ByteArrayOutputStream out = new ByteArrayOutputStream(
                    contentLength > 0 && contentLength <= Integer.MAX_VALUE ? (int) contentLength : 4096);
            StreamUtils.copy(content, out, 4096);
            final byte[] bytes = out.toByteArray();
            out.flush();
            out.close();
            return bytes;
        }
    } finally {
        try {
            content.close();
        } catch (final IOException e) {
            // ignore
        }
    }
}

From source file:com.ar.dev.tierra.api.controller.UsuariosController.java

@PreAuthorize("hasAuthority('ROLE_ADMIN')")
@RequestMapping(value = "/addUsuario", method = RequestMethod.POST)
public ResponseEntity<?> addNewUsuario(@RequestBody Usuarios usuarios) throws IOException {
    String ptoEnc = usuarios.getPassword();
    String bCrypt = passwordEncoder.encode(ptoEnc);
    usuarios.setPassword(bCrypt);//from  ww  w.  j ava2s  .c  o m
    usuarios.setEstado(false);
    usuarios.setFechaCreacion(new Date());
    Usuarios replyUsername;
    Usuarios replyDNI;
    replyUsername = facadeService.getUsuariosDAO().findUsuarioByUsername(usuarios.getUsername());
    replyDNI = facadeService.getUsuariosDAO().findUsuarioByDNI(usuarios.getDni());
    ResponseEntity responseEntity;
    if (replyDNI == null && replyUsername == null) {
        ClassLoader classloader = Thread.currentThread().getContextClassLoader();
        InputStream is = classloader.getResourceAsStream("dd.png");
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        int nRead;
        byte[] bytes = new byte[16384];
        while ((nRead = is.read(bytes, 0, bytes.length)) != -1) {
            buffer.write(bytes, 0, nRead);
        }
        buffer.flush();
        usuarios.setImagen(buffer.toByteArray());
        facadeService.getUsuariosDAO().addUsuario(usuarios);
        responseEntity = new ResponseEntity(HttpStatus.OK);
    } else {
        JsonResponse msj;
        if (replyDNI != null && replyUsername == null) {
            msj = new JsonResponse("Error", "D.N.I. ya existe.");
        } else if (replyUsername != null && replyDNI == null) {
            msj = new JsonResponse("Error", "Nombre de usuario ya existe.");
        } else {
            msj = new JsonResponse("Error", "Nombre de usuario y D.N.I. ya existen.");
        }
        responseEntity = new ResponseEntity(msj, HttpStatus.BAD_REQUEST);
    }
    return responseEntity;
}

From source file:com.netsteadfast.greenstep.bsc.command.KpiReportPdfCommand.java

private void putCharts(PdfPTable table, Context context) throws Exception {
    String pieBase64Content = SimpleUtils.getPNGBase64Content((String) context.get("pieCanvasToData"));
    String barBase64Content = SimpleUtils.getPNGBase64Content((String) context.get("barCanvasToData"));
    BufferedImage pieImage = SimpleUtils.decodeToImage(pieBase64Content);
    BufferedImage barImage = SimpleUtils.decodeToImage(barBase64Content);
    ByteArrayOutputStream pieBos = new ByteArrayOutputStream();
    ImageIO.write(pieImage, "png", pieBos);
    pieBos.flush();
    ByteArrayOutputStream barBos = new ByteArrayOutputStream();
    ImageIO.write(barImage, "png", barBos);
    barBos.flush();// w  w w .  j a  v a 2  s  .c o m

    PdfPCell cell = null;

    Image pieImgObj = Image.getInstance(pieBos.toByteArray());
    pieImgObj.setWidthPercentage(100f);
    cell = new PdfPCell();
    cell.setBorder(Rectangle.NO_BORDER);
    cell.addElement(pieImgObj);
    table.addCell(cell);

    Image barImgObj = Image.getInstance(barBos.toByteArray());
    barImgObj.setWidthPercentage(100f);
    cell = new PdfPCell();
    cell.setBorder(Rectangle.NO_BORDER);
    cell.addElement(barImgObj);
    table.addCell(cell);

}

From source file:com.mirth.connect.connectors.jms.JmsMessageUtils.java

/**
 * @param message//from  w  w  w  .  j  av a2  s.  c  o  m
 *            the message to receive the bytes from. Note this only works
 *            for TextMessge, ObjectMessage, StreamMessage and BytesMessage.
 * @return a byte array corresponding with the message payload
 * @throws JMSException
 *             if the message can't be read or if the message passed is a
 *             MapMessage
 * @throws java.io.IOException
 *             if a failiare occurs while stream and converting the message
 *             data
 */
public static byte[] getBytesFromMessage(Message message) throws JMSException, IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    byte[] buffer = new byte[1024 * 2];
    int len;

    if (message instanceof BytesMessage) {
        BytesMessage bMsg = (BytesMessage) message;
        // put message in read-only mode
        bMsg.reset();
        while ((len = bMsg.readBytes(buffer)) != -1) {
            baos.write(buffer, 0, len);
        }
    } else if (message instanceof StreamMessage) {
        StreamMessage sMsg = (StreamMessage) message;
        sMsg.reset();
        while ((len = sMsg.readBytes(buffer)) != -1) {
            baos.write(buffer, 0, len);
        }
    } else if (message instanceof ObjectMessage) {
        ObjectMessage oMsg = (ObjectMessage) message;
        ByteArrayOutputStream bs = new ByteArrayOutputStream();
        ObjectOutputStream os = new ObjectOutputStream(bs);
        os.writeObject(oMsg.getObject());
        os.flush();
        baos.write(bs.toByteArray());
        os.close();
        bs.close();
    } else if (message instanceof TextMessage) {
        TextMessage tMsg = (TextMessage) message;
        baos.write(tMsg.getText().getBytes());
    } else {
        throw new JMSException("Cannot get bytes from Map Message");
    }

    baos.flush();
    byte[] bytes = baos.toByteArray();
    baos.close();
    return bytes;
}