Example usage for java.sql Blob getBinaryStream

List of usage examples for java.sql Blob getBinaryStream

Introduction

In this page you can find the example usage for java.sql Blob getBinaryStream.

Prototype

java.io.InputStream getBinaryStream() throws SQLException;

Source Link

Document

Retrieves the BLOB value designated by this Blob instance as a stream.

Usage

From source file:eionet.cr.dao.readers.StagingDatabaseDTOReader.java

@Override
public void readRow(ResultSet rs) throws SQLException, ResultSetReaderException {

    StagingDatabaseDTO databaseDTO = new StagingDatabaseDTO();
    databaseDTO.setId(rs.getInt("DATABASE_ID"));
    databaseDTO.setName(rs.getString("NAME"));
    databaseDTO.setCreator(rs.getString("CREATOR"));
    databaseDTO.setCreated(rs.getTimestamp("CREATED"));
    databaseDTO.setDescription(rs.getString("DESCRIPTION"));
    databaseDTO.setImportStatus(Enum.valueOf(ImportStatus.class, rs.getString("IMPORT_STATUS")));
    databaseDTO.setImportLog(rs.getString("IMPORT_LOG"));

    try {/*from   w ww  .j av a 2  s. c om*/
        Blob blob = rs.getBlob("DEFAULT_QUERY");
        String query = blob == null ? null : blob.length() == 0 ? "" : IOUtils.toString(blob.getBinaryStream());
        databaseDTO.setDefaultQuery(query);
    } catch (Exception e) {
        LOGGER.warn("Failed to read column: DEFAULT_QUERY", e);
    }

    resultList.add(databaseDTO);
}

From source file:org.deshang.content.indexing.util.jdbc.AbstractRowMapper.java

protected String getBlobContent(Blob blob) throws SQLException {

    LOGGER.debug("Enter getBlobContent(Blob)");
    String blobContent = null;/*from  w  ww .  j a  va  2s. c o  m*/
    try {
        InputStream in = blob.getBinaryStream();
        BufferedInputStream bis = new BufferedInputStream(in);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        int data = -1;
        while ((data = bis.read()) != -1) {
            baos.write(data);
        }
        blobContent = baos.toString("UTF-8");
    } catch (IOException e) {
        throw new SQLException("Can't read blob conent", e);
    }

    LOGGER.debug("Exit getBlobContent(Blob)");
    return blobContent;
}

From source file:de.juwimm.cms.model.DocumentHbmImpl.java

/**
 * @see de.juwimm.cms.model.DocumentHbm#getValue()
 *//*from w w w .j  a  va2  s  . c  o  m*/
@Override
public DocumentValue getValue() {
    DocumentValue vo = new DocumentValue();
    vo.setDocumentId(this.getDocumentId());
    vo.setDocumentName(this.getDocumentName());
    vo.setMimeType(this.getMimeType());
    vo.setTimeStamp(this.getTimeStamp());
    vo.setUseCountLastVersion(this.getUseCountLastVersion());
    vo.setUseCountPublishVersion(this.getUseCountPublishVersion());
    vo.setLabel(this.getLabel());
    vo.setDescription(this.getDescription());
    vo.setSearchable(this.isSearchable());
    vo.setAuthor(this.getAuthor());
    vo.setCategory(this.getCategory());
    vo.setViewDocumentId(this.getViewComponent() != null ? this.getViewComponent().getViewComponentId() : null);
    vo.setUnitId(this.getUnit() != null ? this.getUnit().getUnitId() : null);
    try {
        Blob blob = this.getDocument();
        vo.setDocument(IOUtils.toByteArray(blob.getBinaryStream()));
    } catch (SQLException e) {
        log.error("There was an error in document content fetching", e);
    } catch (IOException e) {
        log.error("There was an error in document content fetching", e);
    }
    return vo;
}

From source file:org.hoteia.qalingo.app.business.job.email.AbstractEmailItemProcessor.java

public Email process(CommonProcessIndicatorItemWrapper<Long, Email> wrapper) throws Exception {
    Email email = wrapper.getItem();/*ww  w  .j  a v  a2  s  .com*/
    Blob emailcontent = email.getEmailContent();

    InputStream is = emailcontent.getBinaryStream();
    ObjectInputStream oip = new ObjectInputStream(is);
    Object object = oip.readObject();

    MimeMessagePreparatorImpl mimeMessagePreparator = (MimeMessagePreparatorImpl) object;

    oip.close();
    is.close();

    try {
        // SANITY CHECK
        if (email.getStatus().equals(Email.EMAIl_STATUS_PENDING)) {

            if (mimeMessagePreparator.isMirroringActivated()) {
                String filePathToSave = mimeMessagePreparator.getMirroringFilePath();
                File file = new File(filePathToSave);

                // SANITY CHECK : create folders
                String absoluteFolderPath = file.getParent();
                File absolutePathFile = new File(absoluteFolderPath);
                if (!absolutePathFile.exists()) {
                    absolutePathFile.mkdirs();
                }

                if (!file.exists()) {
                    FileOutputStream fileOutputStream = new FileOutputStream(file);
                    OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream,
                            Constants.UTF8);
                    Writer out = new BufferedWriter(outputStreamWriter);
                    if (StringUtils.isNotEmpty(mimeMessagePreparator.getHtmlContent())) {
                        out.write(mimeMessagePreparator.getHtmlContent());
                    } else {
                        out.write(mimeMessagePreparator.getPlainTextContent());
                    }

                    try {
                        if (out != null) {
                            out.close();
                        }
                    } catch (IOException e) {
                        logger.debug("Cannot close the file", e);
                    }
                } else {
                    logger.debug("File already exists : " + filePathToSave);
                }
            }

            mailSender.send(mimeMessagePreparator);
            email.setStatus(Email.EMAIl_STATUS_SENDED);
        } else {
            logger.warn("Batch try to send email was already sended!");
        }

    } catch (Exception e) {
        logger.error("Fail to send email! Exception is save in database, id:" + email.getId());
        email.setStatus(Email.EMAIl_STATUS_ERROR);
        emailService.handleEmailException(email, e);
    }

    return email;
}

From source file:com.jaspersoft.jasperserver.api.metadata.common.service.impl.hibernate.persistent.ContentRepoFileResource.java

protected DataContainer createDataContainer(Blob blob) {
    try {/*from w w w  .j  av a2 s .  c om*/
        InputStream dataStream = blob.getBinaryStream();
        DataContainer dataContainer = new FileBufferedDataContainer();
        // copy the raw data, sniffing for gzip
        dataContainer = DataContainerStreamUtil.pipeGzipSniffedData(dataStream, dataContainer);
        return dataContainer;
    } catch (SQLException e) {
        log.error("Error while reading data blob of \"" + getResourceURI() + "\"", e);
        throw new JSExceptionWrapper(e);
    }
}

From source file:metadata.etl.lineage.AzJobChecker.java

/**
 * Read the blob from "flow_data", do a topological sort on the nodes. Give them the sort id.
 * @param startTimeStamp the begin timestamp in milli seconds
 * @param endTimeStamp the end timestamp in milli seconds
 * @return/*  w  w w .  jav  a2s.  com*/
 */
public List<AzkabanJobExecRecord> getRecentFinishedJobFromFlow(long startTimeStamp, long endTimeStamp)
        throws SQLException, IOException {

    logger.info("Get the jobs from time : {} to time : {}", startTimeStamp, endTimeStamp);
    List<AzkabanJobExecRecord> results = new ArrayList<>();
    Statement stmt = conn.createStatement();
    final String cmd = "select exec_id, flow_id, status, submit_user, flow_data from execution_flows where end_time > "
            + startTimeStamp + " and end_time < " + endTimeStamp;
    logger.info("Get recent flow sql : " + cmd);
    final ResultSet rs = stmt.executeQuery(cmd); // this sql take 3 second to execute

    while (rs.next()) {
        long execId = rs.getLong("exec_id");
        Blob flowBlob = rs.getBlob("flow_data");
        GZIPInputStream gzip = new GZIPInputStream(flowBlob.getBinaryStream());
        String flowJson = IOUtils.toString(gzip, "UTF-8");
        results.addAll(parseJson(flowJson, execId));
    }
    return results;
}

From source file:net.sf.beanlib.utils.BlobUtils.java

private byte[] toByteArrayImpl(Blob fromBlob, ByteArrayOutputStream baos, int bufferSize)
        throws SQLException, IOException {
    byte[] buf = new byte[bufferSize];
    InputStream is = fromBlob.getBinaryStream();
    try {/*  ww w  .  java2 s. com*/
        for (;;) {
            int dataSize = is.read(buf);

            if (dataSize == -1)
                break;
            baos.write(buf, 0, dataSize);
        }
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException ex) {
                log.warn("", ex);
            }
        }
    }
    return baos.toByteArray();
}

From source file:org.ambraproject.article.service.ArticleDocumentServiceImpl.java

public Document getDocument(Blob blob) throws Exception {
    InputStream inputStream = null;
    try {//w w  w.j av a2 s . c  o m
        inputStream = blob.getBinaryStream();
        return parseXmlInputStream(inputStream);
    } finally {
        if (inputStream != null) {
            inputStream.close();
        }
    }
}

From source file:com.ebay.pulsar.analytics.dao.mapper.BaseDBMapper.java

@SuppressWarnings("unchecked")
@Override/*from   w ww.  ja  v a  2s  .  c o m*/
public T mapRow(ResultSet r, int index) throws SQLException {
    try {
        T obj = (T) clazz.newInstance();
        if (obj == null) {
            return null;
        }
        try {

            BeanInfo beanInfo = Introspector.getBeanInfo(clazz);
            PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
            for (PropertyDescriptor property : propertyDescriptors) {
                String key = property.getName();
                if (!key.equals("class")) {
                    Object value = null;
                    try {
                        Method setter = property.getWriteMethod();
                        value = r.getObject(key.toLowerCase());
                        if (value != null && value instanceof Number) {
                            @SuppressWarnings("rawtypes")
                            Class[] types = setter.getParameterTypes();
                            value = NumberUtils.convertNumberToTargetClass((Number) value, types[0]);
                        }
                        if (value != null) {
                            if (value.getClass().equals(BigInteger.class)) {
                                setter.invoke(obj, ((BigInteger) value).longValue());
                            } else if (value.getClass().equals(byte[].class)) {
                                setter.invoke(obj, new String((byte[]) value));
                            } else if (Blob.class.isAssignableFrom(value.getClass())) {
                                Blob bv = (Blob) value;
                                byte[] b = new byte[(int) bv.length()];
                                InputStream stream = bv.getBinaryStream();
                                stream.read(b);
                                stream.close();
                                String v = new String(b);
                                setter.invoke(obj, v);
                            } else {
                                setter.invoke(obj, value);
                            }
                        }
                    } catch (Exception e) {
                        logger.error("transBean2Map Error " + e);
                        logger.error("name[" + key + "]=" + (value == null ? "NULL" : value.toString())
                                + ", class:" + (value == null ? "NULL" : value.getClass()) + ", err:"
                                + e.getMessage());
                    }

                }

            }
        } catch (Exception e) {
            logger.error("transBean2Map Error " + e);
        }
        return obj;
    } catch (Exception e) {
        logger.error("Exception:" + e);
    }

    return null;
}

From source file:de.unidue.inf.is.ezdl.dlservices.repository.store.repositories.DBRepository.java

@Override
public StoredDocument getDocument(String oid) {
    Connection con = null;/*from  w  w  w  .  j a  v a  2  s .  c o  m*/
    PreparedStatement st = null;
    ResultSet res = null;
    StoredDocument out = null;
    final String databaseIdForOid = databaseIdForOid(oid);
    try {
        con = provider.connection();
        st = con.prepareStatement(GET);
        st.setString(1, databaseIdForOid);
        res = st.executeQuery();
        if (res.next()) {
            Blob clob = res.getBlob(1);
            out = decode(clob.getBinaryStream());
        }
        con.commit();
    } catch (SQLException e) {
        rollback(con);
        getLogger().error("Error selecting " + databaseIdForOid, e);
    } finally {
        ClosingUtils.close(res);
        ClosingUtils.close(st);
        ClosingUtils.close(con);
    }
    return out;
}