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:cn.afterturn.easypoi.excel.imports.ExcelImportService.java

/**
 * Excel  field  Integer,Long,Double,Date,String,Boolean
 *//*from w  w  w . ja v  a2  s . c o m*/
public ExcelImportResult importExcelByIs(InputStream inputstream, Class<?> pojoClass, ImportParams params,
        boolean needMore) throws Exception {
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Excel import start ,class is {}", pojoClass);
    }
    List<T> result = new ArrayList<T>();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ExcelImportResult importResult;
    try {
        byte[] buffer = new byte[1024];
        int len;
        while ((len = inputstream.read(buffer)) > -1) {
            baos.write(buffer, 0, len);
        }
        baos.flush();

        InputStream userIs = new ByteArrayInputStream(baos.toByteArray());
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Excel clone success");
        }
        Workbook book = WorkbookFactory.create(userIs);

        boolean isXSSFWorkbook = !(book instanceof HSSFWorkbook);
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Workbook create success");
        }
        importResult = new ExcelImportResult();
        createErrorCellStyle(book);
        Map<String, PictureData> pictures;
        for (int i = params.getStartSheetIndex(); i < params.getStartSheetIndex() + params.getSheetNum(); i++) {
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug(" start to read excel by is ,startTime is {}", new Date());
            }
            if (isXSSFWorkbook) {
                pictures = PoiPublicUtil.getSheetPictrues07((XSSFSheet) book.getSheetAt(i),
                        (XSSFWorkbook) book);
            } else {
                pictures = PoiPublicUtil.getSheetPictrues03((HSSFSheet) book.getSheetAt(i),
                        (HSSFWorkbook) book);
            }
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug(" end to read excel by is ,endTime is {}", new Date());
            }
            result.addAll(importExcel(result, book.getSheetAt(i), pojoClass, params, pictures));
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug(" end to read excel list by sheet ,endTime is {}", new Date());
            }
            if (params.isReadSingleCell()) {
                readSingleCell(importResult, book.getSheetAt(i), params);
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug(" read Key-Value ,endTime is {}", System.currentTimeMillis());
                }
            }
        }
        if (params.isNeedSave()) {
            saveThisExcel(params, pojoClass, isXSSFWorkbook, book);
        }
        importResult.setList(result);
        if (needMore) {
            InputStream successIs = new ByteArrayInputStream(baos.toByteArray());
            try {
                Workbook successBook = WorkbookFactory.create(successIs);
                importResult.setWorkbook(removeSuperfluousRows(successBook, failRow, params));
                importResult.setFailWorkbook(removeSuperfluousRows(book, successRow, params));
                importResult.setFailList(failCollection);
                importResult.setVerfiyFail(verifyFail);
            } finally {
                successIs.close();
            }
        }
    } finally {
        IOUtils.closeQuietly(baos);
    }

    return importResult;
}

From source file:com.hexidec.ekit.component.RelativeImageView.java

private Icon makeIcon(final String gifFile) throws IOException {
    /* Copy resource into a byte array. This is
     * necessary because several browsers consider
     * Class.getResource a security risk because it
     * can be used to load additional classes.
     * Class.getResourceAsStream just returns raw
     * bytes, which we can convert to an image.
     *///from  w  w  w.j a  va  2  s .  com
    InputStream resource = RelativeImageView.class.getResourceAsStream(gifFile);

    if (resource == null) {
        return null;
    }
    BufferedInputStream in = new BufferedInputStream(resource);
    ByteArrayOutputStream out = new ByteArrayOutputStream(1024);
    byte[] buffer = new byte[1024];
    int n;
    while ((n = in.read(buffer)) > 0) {
        out.write(buffer, 0, n);
    }
    in.close();
    out.flush();

    buffer = out.toByteArray();
    if (buffer.length == 0) {
        log.warn(gifFile + " is zero-length");
        return null;
    }
    return new ImageIcon(buffer);
}

From source file:com.joliciel.jochre.graphics.GraphicsDaoJdbc.java

@Override
public void saveOriginalImage(JochreImage jochreImage) {
    NamedParameterJdbcTemplate jt = new NamedParameterJdbcTemplate(this.getDataSource());
    MapSqlParameterSource paramSource = new MapSqlParameterSource();
    paramSource.addValue("image_id", jochreImage.getId());

    ByteArrayOutputStream os = new ByteArrayOutputStream();
    try {/*from   w w  w  .  jav a  2 s  . c o m*/
        ImageIO.write(jochreImage.getOriginalImage(), "png", os);
        os.flush();
        paramSource.addValue("image_image", os.toByteArray());
        os.close();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    String sql = "UPDATE ocr_image SET image_image = :image_image" + " WHERE image_id = :image_id";

    LOG.debug(sql);
    logParameters(paramSource);
    jt.update(sql, paramSource);
}

From source file:com.joliciel.jochre.graphics.GraphicsDaoJdbc.java

@Override
public void saveRowOfShapes(RowOfShapes row) {
    try {/* w w  w .ja v a 2 s  .  c om*/
        NamedParameterJdbcTemplate jt = new NamedParameterJdbcTemplate(this.getDataSource());
        MapSqlParameterSource paramSource = new MapSqlParameterSource();
        RowOfShapesInternal iRow = (RowOfShapesInternal) row;

        paramSource.addValue("row_paragraph_id", row.getParagraphId());
        paramSource.addValue("row_index", row.getIndex());
        paramSource.addValue("row_height", row.getXHeight());
        String sql = null;

        if (row.isNew()) {
            sql = "SELECT nextval('ocr_row_id_seq')";
            LOG.debug(sql);
            int rowId = jt.queryForInt(sql, paramSource);
            paramSource.addValue("row_id", rowId);

            ByteArrayOutputStream os = new ByteArrayOutputStream();
            ImageIO.write(row.getImage(), "png", os);
            os.flush();
            paramSource.addValue("row_image", os.toByteArray());
            os.close();

            sql = "INSERT INTO ocr_row (row_id, row_paragraph_id, row_index, row_image, row_height) "
                    + "VALUES (:row_id, :row_paragraph_id, :row_index, :row_image, :row_height)";

            LOG.debug(sql);
            logParameters(paramSource);
            jt.update(sql, paramSource);

            iRow.clearMemory();
            iRow.setId(rowId);
        } else {
            paramSource.addValue("row_id", row.getId());

            sql = "UPDATE ocr_row" + " SET row_paragraph_id = :row_paragraph_id" + ", row_index = :row_index"
                    + ", row_height = :row_height" + " WHERE row_id = :row_id";

            LOG.debug(sql);
            logParameters(paramSource);
            jt.update(sql, paramSource);
        }
    } catch (IOException ioe) {
        throw new RuntimeException(ioe);
    }
}

From source file:com.vodafone360.people.service.transport.http.photouploadmanager.PhotoUploadManager.java

/**
 * Handles the synchronous responses for the authentication calls which go
 * against the API directly by adding it to the queue and checking if the
 * response code was a HTTP 200. TODO: this should be refactored into a
 * AuthenticationManager class./* w ww.j av a 2 s . c o  m*/
 *
 * @param response
 *            The response to add to the decoder.
 * @param reqIds
 *            The request IDs the response is to be decoded for.
 * @throws Exception
 *             Thrown if the status line could not be read or the response
 *             is null.
 */
final public void handleApiResponse(final HttpResponse response, final List<Integer> reqIds) throws Exception {
    byte[] ret = null;
    if (null != response) {
        if (null != response.getStatusLine()) {
            int respCode = response.getStatusLine().getStatusCode();

            switch (respCode) {
            case HttpStatus.SC_OK:
            case HttpStatus.SC_CONTINUE:
            case HttpStatus.SC_CREATED:
            case HttpStatus.SC_ACCEPTED:
            case HttpStatus.SC_NON_AUTHORITATIVE_INFORMATION:
            case HttpStatus.SC_NO_CONTENT:
            case HttpStatus.SC_RESET_CONTENT:
            case HttpStatus.SC_PARTIAL_CONTENT:
            case HttpStatus.SC_MULTI_STATUS:
                HttpEntity entity = response.getEntity();
                if (null != entity) {
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();

                    InputStream is = entity.getContent();
                    if (null != is) {
                        int nextByte = 0;
                        while ((nextByte = is.read()) != -1) {
                            baos.write(nextByte);
                        }
                        baos.flush();
                        ret = baos.toByteArray();
                        baos.close();
                        baos = null;
                    }
                    entity.consumeContent();
                }

                if (Settings.ENABLED_TRANSPORT_TRACE) {
                    int length = 0;
                    if (ret != null) {
                        length = ret.length;
                    }
                    PhotoUploadManager.logI("ResponseReader.handleApiResponse()",
                            "\n \n \n" + "Response with length " + length + " bytes received "
                                    + "<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<" + (length == 0 ? ""
                                            : HessianUtils.getInHessian(new ByteArrayInputStream(ret), false)));

                }
                addToDecoder(ret, reqIds);
                break;
            default:
                addErrorToResponseQueue(reqIds);
            }
        } else {
            throw new Exception("Status line of response was null.");
        }
    } else {
        throw new Exception("Response was null.");
    }
}

From source file:architecture.common.util.TextUtils.java

/**
 * Encode an Object to String by serializing it and encoding using base64.
 *
 * @see #decodeObject(java.lang.String)//from   w  w  w .j ava  2  s .c  o m
 */
public final static String encodeObject(Object o) throws IOException {
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    ObjectOutputStream stream = new ObjectOutputStream(bytes);
    stream.writeObject(o);
    stream.close();
    bytes.flush();

    return Base64.encodeBase64String(bytes.toByteArray());
}

From source file:io.selendroid.standalone.android.impl.AbstractDevice.java

protected byte[] toByteArray(BufferedImage image) throws AndroidDeviceException {
    ByteArrayOutputStream stream = new ByteArrayOutputStream();

    try {//from  w  w w  . j a  v  a  2 s.  c  o m
        if (!ImageIO.write(image, "png", stream)) {
            throw new IOException("Failed to find png writer");
        }
    } catch (IOException e) {
        log.log(Level.SEVERE, "Cannot take screenshot", e);
        throw new AndroidDeviceException(e.getMessage());
    }
    byte[] raw = null;
    try {
        stream.flush();
        raw = stream.toByteArray();
        stream.close();
    } catch (IOException e) {
        throw new RuntimeException("I/O Error while capturing screenshot: " + e.getMessage());
    } finally {
        try {
            stream.close();
        } catch (IOException ioe) {
            // ignore
        }
    }
    return raw;
}

From source file:com.joliciel.jochre.graphics.GraphicsDaoJdbc.java

@Override
public void saveShape(Shape shape) {
    // note: update will not update the pixels (not strictly required).
    try {/*www .  ja va  2s  . c o m*/
        NamedParameterJdbcTemplate jt = new NamedParameterJdbcTemplate(this.getDataSource());
        MapSqlParameterSource paramSource = new MapSqlParameterSource();
        ShapeInternal iShape = (ShapeInternal) shape;

        paramSource.addValue("shape_top", shape.getTop());
        paramSource.addValue("shape_left", shape.getLeft());
        paramSource.addValue("shape_bottom", shape.getBottom());
        paramSource.addValue("shape_right", shape.getRight());
        paramSource.addValue("shape_cap_line", shape.getCapLine());
        paramSource.addValue("shape_mean_line", shape.getMeanLine());
        paramSource.addValue("shape_base_line", shape.getBaseLine());
        paramSource.addValue("shape_letter", shape.getLetter());
        paramSource.addValue("shape_original_guess", shape.getOriginalGuess());
        paramSource.addValue("shape_group_id", shape.getGroupId());
        paramSource.addValue("shape_index", shape.getIndex());
        String sql = null;

        if (shape.isNew()) {
            sql = "SELECT nextval('ocr_shape_id_seq')";
            LOG.debug(sql);
            int shapeId = jt.queryForInt(sql, paramSource);
            paramSource.addValue("shape_id", shapeId);

            ByteArrayOutputStream os = new ByteArrayOutputStream();
            ImageIO.write(shape.getImage(), "png", os);
            os.flush();
            paramSource.addValue("shape_pixels", os.toByteArray());
            os.close();

            sql = "INSERT INTO ocr_shape (shape_id, shape_top, shape_left, shape_bottom, shape_right"
                    + ", shape_cap_line, shape_mean_line, shape_base_line, shape_pixels, shape_letter, shape_group_id"
                    + ", shape_index, shape_original_guess) "
                    + "VALUES (:shape_id, :shape_top, :shape_left, :shape_bottom, :shape_right"
                    + ", :shape_cap_line, :shape_mean_line, :shape_base_line, :shape_pixels, :shape_letter, :shape_group_id"
                    + ", :shape_index, :shape_original_guess)";

            LOG.debug(sql);
            logParameters(paramSource);
            jt.update(sql, paramSource);

            iShape.setId(shapeId);
        } else {
            paramSource.addValue("shape_id", shape.getId());

            sql = "UPDATE ocr_shape" + " SET shape_top = :shape_top" + ", shape_left = :shape_left"
                    + ", shape_bottom = :shape_bottom" + ", shape_right = :shape_right"
                    + ", shape_cap_line = :shape_cap_line" + ", shape_mean_line = :shape_mean_line"
                    + ", shape_base_line = :shape_base_line" + ", shape_letter = :shape_letter"
                    + ", shape_group_id = :shape_group_id" + ", shape_index = :shape_index "
                    + ", shape_original_guess = :shape_original_guess " + " WHERE shape_id = :shape_id";

            LOG.debug(sql);
            logParameters(paramSource);
            jt.update(sql, paramSource);
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.odoko.solrcli.actions.CrawlPostAction.java

/**
 * Reads an input stream into a byte array
 * @param is the input stream/*from  w  w w  .  j a va 2 s .c o  m*/
 * @return the byte array
 * @throws IOException If there is a low-level I/O error.
 */
protected byte[] inputStreamToByteArray(InputStream is) throws IOException {
  ByteArrayOutputStream bos = new ByteArrayOutputStream();
  int next = is.read();
  while (next > -1) {
      bos.write(next);
      next = is.read();
  }
  bos.flush();
  is.close();
  return bos.toByteArray();
}