Example usage for java.sql Blob length

List of usage examples for java.sql Blob length

Introduction

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

Prototype

long length() throws SQLException;

Source Link

Document

Returns the number of bytes in the BLOB value designated by this Blob object.

Usage

From source file:org.pentaho.reporting.libraries.base.util.IOUtils.java

/**
 * Converts a SQL-Clob object into a String. If the Clob is larger than 2^31 characters, we cannot convert it. If
 * there are errors converting it, this method will log the cause and return null.
 *
 * @param clob the clob to be read as string.
 * @return the string or null in case of errors.
 *//*from  w  w w .ja v  a2 s. co  m*/
public byte[] readBlob(final Blob clob) throws IOException, SQLException {
    final long length = clob.length();
    if (length > Integer.MAX_VALUE) {
        logger.warn("This CLOB contains more than 2^31 characters. We cannot handle that.");
        throw new IOException("This BLOB contains more than 2^31 characters. We cannot handle that.");
    }

    final InputStream inStream = clob.getBinaryStream();
    final MemoryByteArrayOutputStream outStream = new MemoryByteArrayOutputStream((int) length, 65536);
    try {
        IOUtils.getInstance().copyStreams(inStream, outStream);
    } finally {
        try {
            inStream.close();
        } catch (IOException e) {
            logger.warn("Failed to close input stream. No worries, we will be alright anyway.", e);
        }
    }
    return outStream.toByteArray();
}

From source file:edu.clemson.cs.nestbed.server.adaptation.sql.MoteTypeSqlAdapter.java

public Map<Integer, MoteType> readMoteTypes() throws AdaptationException {
    Map<Integer, MoteType> moteTypes = new HashMap<Integer, MoteType>();
    Connection connection = null;
    Statement statement = null;//from   ww w  .ja va2s . c  o  m
    ResultSet resultSet = null;

    try {
        String query = "SELECT * FROM MoteTypes";

        connection = DriverManager.getConnection(CONN_STR);
        statement = connection.createStatement();
        resultSet = statement.executeQuery(query);

        while (resultSet.next()) {
            int id;
            String name;
            int totalROM;
            int totalRAM;
            int totalEEPROM;
            Blob imageBlob;
            String tosPlatform;
            Date timestamp;

            id = resultSet.getInt(Index.ID.index());
            name = resultSet.getString(Index.NAME.index());
            totalROM = resultSet.getInt(Index.TOTALROM.index());
            totalRAM = resultSet.getInt(Index.TOTALRAM.index());
            totalEEPROM = resultSet.getInt(Index.TOTALEEPROM.index());
            imageBlob = resultSet.getBlob(Index.IMAGE.index());
            tosPlatform = resultSet.getString(Index.TOSPLATFORM.index());
            timestamp = resultSet.getDate(Index.TIMESTAMP.index());

            byte[] image = (imageBlob != null && imageBlob.length() > 0)
                    ? imageBlob.getBytes(1, (int) imageBlob.length())
                    : null;

            MoteType moteType = MoteType.getMoteType(id, name, totalROM, totalRAM, totalEEPROM, image,
                    tosPlatform, timestamp);
            moteTypes.put(id, moteType);
        }
    } catch (SQLException ex) {
        String msg = "SQLException in readMoteTypes";
        log.error(msg, ex);
        throw new AdaptationException(msg, ex);
    } finally {
        try {
            resultSet.close();
        } catch (Exception ex) {
        }
        try {
            statement.close();
        } catch (Exception ex) {
        }
        try {
            connection.close();
        } catch (Exception ex) {
        }
    }

    return moteTypes;
}

From source file:se.unlogic.hierarchy.foregroundmodules.imagegallery.GalleryModule.java

public static void writePicture(Picture picture, boolean mediumThumb, HttpServletResponse res)
        throws SQLException, IOException {

    // send thumb to user
    Blob blob = null;
    if (mediumThumb) {
        blob = picture.getMediumThumb();
    } else {/*ww  w  .  jav  a2s .c o  m*/
        blob = picture.getSmallThumb();
    }

    HTTPUtils.setContentLength(blob.length(), res);

    res.setContentType("image/jpeg");
    res.setHeader("Content-Disposition",
            "inline; filename=\"" + FileUtils.toValidHttpFilename(picture.getFilename()) + "\"");

    InputStream in = null;
    OutputStream out = null;

    try {
        in = blob.getBinaryStream();
        out = res.getOutputStream();

        StreamUtils.transfer(in, out);
    } finally {

        StreamUtils.closeStream(in);
        StreamUtils.closeStream(out);
    }
}

From source file:nl.nn.adapterframework.util.JdbcUtil.java

public static String getBlobAsString(Blob blob, String column, String charset, boolean xmlEncode,
        boolean blobIsCompressed, boolean blobSmartGet, boolean encodeBlobBase64)
        throws IOException, JdbcException, SQLException, JMSException {
    if (encodeBlobBase64) {
        InputStream blobStream = JdbcUtil.getBlobInputStream(blob, column, blobIsCompressed);
        return Misc.streamToString(new Base64InputStream(blobStream, true), null, false);
    }/*from  www .  j  a  v  a2 s  .  c o m*/
    if (blobSmartGet) {
        if (blob == null) {
            log.debug("no blob found in column [" + column + "]");
            return null;
        }
        int bl = (int) blob.length();

        InputStream is = blob.getBinaryStream();
        byte[] buf = new byte[bl];
        int bl1 = is.read(buf);

        Inflater decompressor = new Inflater();
        decompressor.setInput(buf);
        ByteArrayOutputStream bos = new ByteArrayOutputStream(buf.length);
        byte[] bufDecomp = new byte[1024];
        boolean decompresOK = true;
        while (!decompressor.finished()) {
            try {
                int count = decompressor.inflate(bufDecomp);
                if (count == 0) {
                    break;
                }
                bos.write(bufDecomp, 0, count);
            } catch (DataFormatException e) {
                log.debug("message in column [" + column + "] is not compressed");
                decompresOK = false;
                break;
            }
        }
        bos.close();
        if (decompresOK)
            buf = bos.toByteArray();

        Object result = null;
        ObjectInputStream ois = null;
        boolean objectOK = true;
        try {
            ByteArrayInputStream bis = new ByteArrayInputStream(buf);
            ois = new ObjectInputStream(bis);
            result = ois.readObject();
        } catch (Exception e) {
            log.debug("message in column [" + column + "] is probably not a serialized object: "
                    + e.getClass().getName());
            objectOK = false;
        }
        if (ois != null)
            ois.close();

        String rawMessage;
        if (objectOK) {
            if (result instanceof IMessageWrapper) {
                rawMessage = ((IMessageWrapper) result).getText();
            } else if (result instanceof TextMessage) {
                rawMessage = ((TextMessage) result).getText();
            } else {
                rawMessage = (String) result;
            }
        } else {
            rawMessage = new String(buf, charset);
        }

        String message = XmlUtils.encodeCdataString(rawMessage);
        return message;
    }
    return Misc.readerToString(getBlobReader(blob, column, charset, blobIsCompressed), null, xmlEncode);
}

From source file:cz.zcu.kiv.eegdatabase.logic.controller.experiment.MeasurationDataOutputController.java

@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    // ModelAndView mav = new ModelAndView("binaryView");
    // There should always be set integer value in this field - it is generated by view, not by user
    int fileId = Integer.parseInt(request.getParameter("fileId"));
    DataFile data = dataFileDao.read(fileId);
    Blob b = data.getFileContent();
    Person user = personDao.getPerson(ControllerUtils.getLoggedUserName());
    Timestamp currentTimestamp = new java.sql.Timestamp(Calendar.getInstance().getTime().getTime());
    History history = new History();
    log.debug("Setting downloading data file");
    history.setDataFile(data);/*from   w  w w .  j ava 2s  .  c om*/
    log.debug("Setting user");
    history.setPerson(user);
    log.debug("Setting time of download");
    history.setDateOfDownload(currentTimestamp);
    log.debug("Saving download history");
    historyDao.create(history);
    response.setHeader("Content-Type", data.getMimetype());
    response.setHeader("Content-Disposition", "attachment;filename=" + data.getFilename());
    response.getOutputStream().write(b.getBytes(1, (int) b.length()));
    //  mav.addObject("dataObject", dataFileDao.read(fileId));
    return null;
}

From source file:eionet.cr.dao.virtuoso.VirtuosoStagingDatabaseDAO.java

@Override
public String getImportLog(int databaseId) throws DAOException {

    ArrayList<Object> params = new ArrayList<Object>();
    params.add(Integer.valueOf(databaseId));

    ResultSet rs = null;// w w w  . j  a  va 2s . c o  m
    Statement stmt = null;
    Connection conn = null;
    try {
        conn = getSQLConnection();
        stmt = conn.createStatement();
        rs = stmt.executeQuery(GET_IMPORT_LOG_SQL.replace("?", String.valueOf(databaseId)));
        if (rs.next()) {
            Blob blob = rs.getBlob(1);
            if (blob != null) {
                try {
                    return blob.length() == 0 ? "" : IOUtils.toString(blob.getBinaryStream());
                } catch (IOException e) {
                    LOGGER.warn("Could not retreive import log of database #" + databaseId + ": " + e);
                    return null;
                }
            } else {
                return null;
            }
        } else {
            return null;
        }

    } catch (SQLException e) {
        throw new DAOException(e.getMessage(), e);
    } finally {
        SQLUtil.close(rs);
        SQLUtil.close(stmt);
        SQLUtil.close(conn);
    }
}

From source file:eionet.cr.dao.virtuoso.VirtuosoStagingDatabaseDAO.java

@Override
public String getExportLog(int exportId) throws DAOException {

    ArrayList<Object> params = new ArrayList<Object>();
    params.add(Integer.valueOf(exportId));

    ResultSet rs = null;/*from www  . ja  v a  2  s.  co m*/
    Statement stmt = null;
    Connection conn = null;
    try {
        conn = getSQLConnection();
        stmt = conn.createStatement();
        rs = stmt.executeQuery(GET_EXPORT_LOG_SQL.replace("?", String.valueOf(exportId)));
        if (rs.next()) {
            Blob blob = rs.getBlob(1);
            if (blob != null) {
                try {
                    return blob.length() == 0 ? "" : IOUtils.toString(blob.getBinaryStream());
                } catch (IOException e) {
                    LOGGER.warn("Could not retreive log of the RDF export with id = " + exportId + ": " + e);
                    return null;
                }
            } else {
                return null;
            }
        } else {
            return null;
        }

    } catch (SQLException e) {
        throw new DAOException(e.getMessage(), e);
    } finally {
        SQLUtil.close(rs);
        SQLUtil.close(stmt);
        SQLUtil.close(conn);
    }
}

From source file:org.osaf.cosmo.migrate.ZeroPointFiveToZeroPointSixMigration.java

private void migrateEvents(Connection conn, String dialect) throws Exception {
    PreparedStatement stmt = null;
    PreparedStatement insertStampStmt1 = null;
    PreparedStatement insertStampStmt2 = null;
    PreparedStatement insertEventStmt = null;
    PreparedStatement insertAttributeStmt1 = null;
    PreparedStatement insertAttributeStmt2 = null;
    PreparedStatement deleteContentDataStmt = null;
    PreparedStatement selectContentDataStmt = null;
    PreparedStatement updateEventStmt = null;
    PreparedStatement updatePropsStmt = null;
    PreparedStatement updateTimerangesStmt = null;

    ResultSet rs = null;//  w ww  .  j a  va2s. co m
    long count = 0;

    System.setProperty("ical4j.unfolding.relaxed", "true");
    CalendarBuilder calBuilder = new CalendarBuilder();

    VersionFourGenerator uidGenerator = new VersionFourGenerator();

    log.debug("begin migrateEvents()");

    try {
        stmt = conn.prepareStatement("select id, contentdataid from item where itemtype=?");
        stmt.setString(1, "event");

        insertStampStmt1 = conn
                .prepareStatement("insert into stamp (stamptype, itemid, isactive) values (?,?,1)");
        insertStampStmt1.setString(1, "event");
        insertStampStmt2 = conn
                .prepareStatement("insert into stamp (stamptype, itemid, id, isactive) values (?,?,?,1)");
        insertStampStmt2.setString(1, "event");

        insertAttributeStmt1 = conn.prepareStatement(
                "insert into attribute (attributetype, namespace, localname, itemid, textvalue, attributename) values (?,?,?,?,?,'a')");
        insertAttributeStmt2 = conn.prepareStatement(
                "insert into attribute (attributetype, namespace, localname, itemid, textvalue, id, attributename) values (?,?,?,?,?,?,'a')");
        insertAttributeStmt1.setString(1, "text");
        insertAttributeStmt2.setString(1, "text");
        insertAttributeStmt1.setString(2, "org.osaf.cosmo.model.NoteItem");
        insertAttributeStmt2.setString(2, "org.osaf.cosmo.model.NoteItem");
        insertAttributeStmt1.setString(3, "body");
        insertAttributeStmt2.setString(3, "body");

        deleteContentDataStmt = conn.prepareStatement("delete from content_data where id=?");
        selectContentDataStmt = conn.prepareStatement("select content from content_data where id=?");

        updateEventStmt = conn.prepareStatement(
                "update item set itemtype=?, contentdataid=?, contentlength=?, icaluid=?, displayname=? where id=?");
        updateEventStmt.setString(1, "note");
        updateEventStmt.setNull(2, Types.BIGINT);

        insertEventStmt = conn.prepareStatement("insert into event_stamp (stampid, icaldata) values (?,?)");
        updatePropsStmt = conn.prepareStatement("update cal_property_index set eventstampid=? where itemid=?");
        updateTimerangesStmt = conn
                .prepareStatement("update cal_timerange_index set eventstampid=? where itemid=?");

        rs = stmt.executeQuery();

        while (rs.next()) {
            count++;
            long itemId = rs.getLong(1);
            long contentDataId = rs.getLong(2);
            long stampId = 0;

            // Add record to stamp
            if ("MySQL5".equals(dialect)) {
                insertStampStmt1.setLong(2, itemId);
                insertStampStmt1.executeUpdate();
            } else {
                stampId = hibernateHelper.getNexIdUsingHiLoGenerator(conn);
                insertStampStmt2.setLong(2, itemId);
                insertStampStmt2.setLong(3, stampId);
                insertStampStmt2.executeUpdate();
            }

            // MySQL uses autogenerated id
            if ("MySQL5".equals(dialect)) {
                ResultSet generatedKeysRs = insertStampStmt1.getGeneratedKeys();
                generatedKeysRs.next();
                stampId = generatedKeysRs.getLong(1);
                generatedKeysRs.close();
            }

            // Get binary content data
            selectContentDataStmt.setLong(1, contentDataId);

            Calendar calendar = null;
            long icalLength = 0;
            String icalUid = null;
            String eventDesc = null;
            String eventSummary = null;
            ResultSet contentDataRs = selectContentDataStmt.executeQuery();
            if (contentDataRs.next()) {
                log.debug("itemid=" + itemId);
                Blob icalBlob = contentDataRs.getBlob(1);
                byte[] icalBytes = icalBlob.getBytes(1, (int) icalBlob.length());
                // have to parse data into Calendar to get right contentlength
                calendar = calBuilder.build(new ByteArrayInputStream(icalBytes));
                VEvent event = (VEvent) calendar.getComponents().getComponents(Component.VEVENT).get(0);

                // Now that we parsed, lets get the UID, DESCRIPTION, and
                // SUMMARY so we can update NoteItem, ContentItem
                Uid uid = event.getUid();

                // Handle the case where events don't have a UID (should be rare)
                if (uid != null)
                    icalUid = event.getUid().getValue();

                if (icalUid == null || "".equals(icalUid))
                    icalUid = null;

                // If there is no UID, create a new one
                if (icalUid == null) {
                    icalUid = uidGenerator.nextIdentifier().toString();
                    if (uid != null)
                        uid.setValue(icalUid);
                    else
                        event.getProperties().add(new Uid(icalUid));
                }

                Property p = event.getProperties().getProperty(Property.DESCRIPTION);
                if (p != null)
                    eventDesc = p.getValue();

                if ("".equals(eventDesc))
                    eventDesc = null;

                p = event.getProperties().getProperty(Property.SUMMARY);
                if (p != null)
                    eventSummary = p.getValue();

                if ("".equals(eventSummary))
                    eventSummary = null;

                // Make sure we can fit summary in displayname column
                if (eventSummary != null && eventSummary.length() >= 255)
                    eventSummary = eventSummary.substring(0, 254);

                // Calculate new length
                icalLength = calendar.toString().getBytes("UTF-8").length;
            }

            contentDataRs.close();

            // update item record with new contentLength, itemtype,
            // icaluid, and displayname
            updateEventStmt.setLong(3, icalLength);
            updateEventStmt.setString(4, icalUid);
            if (eventSummary != null)
                updateEventStmt.setString(5, eventSummary);
            else
                updateEventStmt.setNull(5, Types.VARCHAR);
            updateEventStmt.setLong(6, itemId);
            updateEventStmt.executeUpdate();

            // add event_stamp record
            insertEventStmt.setLong(1, stampId);
            insertEventStmt.setString(2, calendar.toString());

            insertEventStmt.executeUpdate();

            // If there is a DESCRIPTION, add a text attribute
            if (eventDesc != null) {
                if ("MySQL5".equals(dialect)) {
                    insertAttributeStmt1.setLong(4, itemId);
                    insertAttributeStmt1.setString(5, eventDesc);
                    insertAttributeStmt1.executeUpdate();
                } else {
                    long attributeId = hibernateHelper.getNexIdUsingHiLoGenerator(conn);
                    insertAttributeStmt2.setLong(4, itemId);
                    insertAttributeStmt2.setString(5, eventDesc);
                    insertAttributeStmt2.setLong(6, attributeId);
                    insertAttributeStmt2.executeUpdate();
                }
            }

            // Update calendar indexes to reflect item and stamp
            updatePropsStmt.setLong(1, stampId);
            updatePropsStmt.setLong(2, itemId);
            updatePropsStmt.executeUpdate();

            updateTimerangesStmt.setLong(1, stampId);
            updateTimerangesStmt.setLong(2, itemId);
            updateTimerangesStmt.executeUpdate();

            // no longer need content for events
            deleteContentDataStmt.setLong(1, contentDataId);
            deleteContentDataStmt.executeUpdate();
        }

    } finally {
        if (rs != null)
            rs.close();

        if (stmt != null)
            stmt.close();

        if (insertStampStmt1 != null)
            insertStampStmt1.close();

        if (insertStampStmt2 != null)
            insertStampStmt2.close();

        if (insertAttributeStmt1 != null)
            insertAttributeStmt1.close();

        if (insertAttributeStmt2 != null)
            insertAttributeStmt2.close();

        if (deleteContentDataStmt != null)
            deleteContentDataStmt.close();

        if (selectContentDataStmt != null)
            selectContentDataStmt.close();

        if (updateEventStmt != null)
            updateEventStmt.close();

        if (insertEventStmt != null)
            insertEventStmt.close();

        if (updatePropsStmt != null)
            updatePropsStmt.close();

        if (updateTimerangesStmt != null)
            updateTimerangesStmt.close();
    }

    log.debug("processed " + count + " events");
}

From source file:org.wso2.carbon.cluster.coordinator.rdbms.RDBMSCommunicationBusContextImpl.java

@Override
public NodeDetail getRemovedNodeData(String nodeId, String groupId, String removedMemberId)
        throws ClusterCoordinationException {
    Connection connection = null;
    PreparedStatement preparedStatement = null;
    PreparedStatement clearMembershipEvents = null;
    ResultSet resultSet = null;//from   ww w  .j  a  va2 s  . com
    NodeDetail nodeDetail = null;
    try {
        connection = getConnection();
        preparedStatement = connection.prepareStatement(RDBMSConstants.PS_SELECT_REMOVED_MEMBER_DETAILS);
        preparedStatement.setString(1, nodeId);
        preparedStatement.setString(2, removedMemberId);
        preparedStatement.setString(3, groupId);
        resultSet = preparedStatement.executeQuery();
        Map<String, Object> propertiesMap = null;

        if (resultSet.next()) {
            Blob blob = resultSet.getBlob(2);
            if (blob != null) {
                int blobLength = (int) blob.length();
                byte[] bytes = blob.getBytes(1, blobLength);
                ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
                ObjectInputStream ois = new ObjectInputStream(bis);
                Object blobObject = ois.readObject();
                if (blobObject instanceof Map) {
                    propertiesMap = (Map) blobObject;
                }
            }
            nodeDetail = new NodeDetail(removedMemberId, groupId, false, 0, false, propertiesMap);
        }
        clearMembershipEvents = connection
                .prepareStatement(RDBMSConstants.PS_DELETE_REMOVED_MEMBER_DETAIL_FOR_NODE);
        clearMembershipEvents.setString(1, nodeId);
        clearMembershipEvents.setString(2, removedMemberId);
        clearMembershipEvents.setString(3, groupId);
        clearMembershipEvents.executeUpdate();
        connection.commit();
    } catch (SQLException e) {
        String errMsg = RDBMSConstants.TASK_GET_ALL_QUEUES;
        throw new ClusterCoordinationException("Error occurred while " + errMsg, e);
    } catch (ClassNotFoundException e) {
        throw new ClusterCoordinationException("Error retrieving the removed node data. ", e);
    } catch (IOException e) {
        throw new ClusterCoordinationException("Error retrieving the removed node data. ", e);
    } finally {
        close(resultSet, RDBMSConstants.TASK_GET_ALL_QUEUES);
        close(preparedStatement, RDBMSConstants.TASK_GET_ALL_QUEUES);
        close(clearMembershipEvents, RDBMSConstants.TASK_GET_ALL_QUEUES);
        close(connection, RDBMSConstants.TASK_GET_ALL_QUEUES);
    }
    return nodeDetail;
}

From source file:com.healthmarketscience.jackcess.impl.ColumnImpl.java

/**
 * @return an appropriate byte[] representation of the given object.
 * @usage _advanced_method_//ww  w . j  ava2  s . c  om
 */
public static byte[] toByteArray(Object value) throws IOException {
    if (value == null) {
        return null;
    } else if (value instanceof byte[]) {
        return (byte[]) value;
    } else if (value instanceof OleUtil.OleBlobImpl) {
        return ((OleUtil.OleBlobImpl) value).getBytes();
    } else if (value instanceof Blob) {
        try {
            Blob b = (Blob) value;
            // note, start pos is 1-based
            return b.getBytes(1L, (int) b.length());
        } catch (SQLException e) {
            throw (IOException) (new IOException(e.getMessage())).initCause(e);
        }
    }

    ByteArrayOutputStream bout = new ByteArrayOutputStream();

    if (value instanceof InputStream) {
        ByteUtil.copy((InputStream) value, bout);
    } else {
        // if all else fails, serialize it
        ObjectOutputStream oos = new ObjectOutputStream(bout);
        oos.writeObject(value);
        oos.close();
    }

    return bout.toByteArray();
}