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.cloudgraph.rdb.service.RDBDataConverter.java

private Object convertFrom(ResultSet rs, int columnIndex, int sourceType, Property property)
        throws SQLException {
    Object result = null;//  ww  w . j ava  2  s  . c  o m
    if (!property.getType().isDataType())
        throw new IllegalArgumentException("expected data type property, not " + property.toString());
    DataType targetDataType = DataType.valueOf(property.getType().getName());
    switch (targetDataType) {
    case String:
    case URI:
    case Month:
    case MonthDay:
    case Day:
    case Time:
    case Year:
    case YearMonth:
    case YearMonthDay:
    case Duration:
        result = rs.getString(columnIndex);
        break;
    case Date:
        java.sql.Timestamp ts = rs.getTimestamp(columnIndex);
        if (ts != null)
            result = new java.util.Date(ts.getTime());
        break;
    case DateTime:
        ts = rs.getTimestamp(columnIndex);
        if (ts != null) {
            // format DateTime String for SDO
            java.util.Date date = new java.util.Date(ts.getTime());
            result = DataConverter.INSTANCE.getDateTimeFormat().format(date);
        }
        break;
    case Decimal:
        result = rs.getBigDecimal(columnIndex);
        break;
    case Bytes:
        if (sourceType != Types.BLOB) {
            result = rs.getBytes(columnIndex);
        } else if (sourceType == Types.BLOB) {
            Blob blob = rs.getBlob(columnIndex);
            if (blob != null) {
                long blobLen = blob.length(); // for debugging
                // Note: blob.getBytes(columnIndex, blob.length()); is
                // somehow truncating the array
                // by something like 14 bytes (?!!) even though
                // blob.length() returns the expected length
                // using getBinaryStream which is preferred anyway
                InputStream is = blob.getBinaryStream();
                try {
                    byte[] bytes = IOUtils.toByteArray(is);
                    long len = bytes.length; // for debugging
                    result = bytes;
                } catch (IOException e) {
                    throw new RDBServiceException(e);
                } finally {
                    try {
                        is.close();
                    } catch (IOException e) {
                        log.error(e.getMessage(), e);
                    }
                }
            }
        }
        break;
    case Byte:
        result = rs.getByte(columnIndex);
        break;
    case Boolean:
        result = rs.getBoolean(columnIndex);
        break;
    case Character:
        result = rs.getInt(columnIndex);
        break;
    case Double:
        result = rs.getDouble(columnIndex);
        break;
    case Float:
        result = rs.getFloat(columnIndex);
        break;
    case Int:
        result = rs.getInt(columnIndex);
        break;
    case Integer:
        result = new BigInteger(rs.getString(columnIndex));
        break;
    case Long:
        result = rs.getLong(columnIndex);
        break;
    case Short:
        result = rs.getShort(columnIndex);
        break;
    case Strings:
        String value = rs.getString(columnIndex);
        if (value != null) {
            String[] values = value.split("\\s");
            List<String> list = new ArrayList<String>(values.length);
            for (int i = 0; i < values.length; i++)
                list.add(values[i]); // what no Java 5 sugar for this ??
            result = list;
        }
        break;
    case Object:
    default:
        result = rs.getObject(columnIndex);
        break;
    }
    return result;
}

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

public Map<Integer, Testbed> readTestbeds() throws AdaptationException {
    Map<Integer, Testbed> testbeds = new HashMap<Integer, Testbed>();
    Connection connection = null;
    Statement statement = null;//from   w  w  w.  j  av  a  2 s.c o m
    ResultSet resultSet = null;

    ProjectAdapter projectAdapter = AdapterFactory.createProjectAdapter(AdapterType.SQL);

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

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

        while (resultSet.next()) {
            int id;
            String name;
            String description;
            Blob imageBlob;
            Date timestamp;

            id = resultSet.getInt(Index.ID.index());
            name = resultSet.getString(Index.NAME.index());
            description = resultSet.getString(Index.DESCRIPTION.index());
            imageBlob = resultSet.getBlob(Index.IMAGE.index());
            timestamp = resultSet.getDate(Index.TIMESTAMP.index());

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

            Testbed testbed = new Testbed(id, name, description, image, timestamp);
            testbeds.put(id, testbed);
        }
    } catch (SQLException ex) {
        String msg = "SQLException in readTestbeds";
        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 testbeds;
}

From source file:org.infoglue.calendar.controllers.ResourceController.java

private void dumpResource(Resource resource) {
    if (resource == null) {
        log.warn("Tried to dump event resource to disk but the reference was null");
    }//from   w w  w . ja  v  a  2 s  .  c  o  m
    FileOutputStream fos = null;
    try {
        File outputFile = getResourceFile(resource);
        fos = new FileOutputStream(outputFile);

        Blob blob = resource.getResource();
        byte[] bytes = blob.getBytes(1, (int) blob.length());
        fos.write(bytes);
        fos.flush();
        fos.close();
    } catch (FileNotFoundException ex) {
        log.error("FileNotFoundException when dumping calendar resource to disk. " + resource.getFileName()
                + ". Exception message: " + ex.getMessage());
        log.warn("FileNotFoundException when dumping calendar resource to disk. " + resource.getFileName(), ex);
    } catch (SQLException ex) {
        log.error("SQLException when dumping calendar resource to disk. " + resource.getFileName()
                + ". Exception message: " + ex.getMessage());
        log.warn("SQLException when dumping calendar resource to disk. " + resource.getFileName(), ex);
    } catch (IOException ex) {
        log.error("IOException when dumping calendar resource to disk. " + resource.getFileName()
                + ". Exception message: " + ex.getMessage());
        log.warn("IOException when dumping calendar resource to disk. " + resource.getFileName(), ex);
    } finally {
        if (fos != null) {
            try {
                fos.close();
            } catch (IOException ex) {
                log.error(
                        "Could not close file after an exception occured while dumping resource to disk. Resource: "
                                + resource.getFileName() + " . Message: " + ex.getMessage());
            }
        }
    }
}

From source file:org.agnitas.backend.DBase.java

public byte[] asBlob(Object o) {
    if (o == null) {
        return null;
    } else if (o.getClass().getName().equals("[B")) {
        return (byte[]) o;
    } else {/*  w w  w .  j a va  2 s. co m*/
        Blob blob = (Blob) o;

        try {
            return blob == null ? null : blob.getBytes(1, (int) blob.length());
        } catch (SQLException e) {
            failure("blob parse", e);
        }
        return null;
    }
}

From source file:org.sakaiproject.component.common.edu.person.InetOrgPersonImpl.java

private byte[] toByteArray(Blob fromBlob) {
    if (LOG.isDebugEnabled()) {
        LOG.debug("toByteArray(Blob " + fromBlob + ")");
    }/* w  ww .  j a v  a  2  s.  c  om*/

    try {
        if (fromBlob == null || fromBlob.length() < 1) {
            return null;
        }
    } catch (SQLException e1) {
        LOG.error(e1.getMessage(), e1);
    }
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {
        return toByteArray(fromBlob, baos);
    } catch (Exception e) {
        LOG.error(e.getMessage(), e);
        throw new RuntimeException(e);
    } finally {
        if (baos != null) {
            try {
                baos.close();
            } catch (IOException ex) {
                LOG.error(ex.getMessage(), ex);
            }
        }
    }
}

From source file:com.p5solutions.core.jpa.orm.oracle.ConversionUtilityImpl.java

/**
 * To blob./*from   w  w  w.  ja  va 2  s.  c  o  m*/
 * 
 * @param pb
 *          the pb
 * @param value
 *          the value
 * @param targetType
 *          the target type
 * @return the object
 */
private Object toJavaBlob(ParameterBinder pb, Object value, Class<?> targetType) {

    if (value instanceof Blob) {
        boolean isBlob = ReflectionUtility.isBlob(targetType);
        boolean isInputStream = ReflectionUtility.isInputStream(targetType);
        boolean isByteArray = ReflectionUtility.isByteArray(targetType);
        boolean isString = ReflectionUtility.isStringClass(targetType);

        Blob blob = (Blob) value;

        // if the target entity->property is of blob, return quickly.
        if (isBlob) {
            return blob;
        }

        try {
            // if the target is a string, then convert the buffer
            if (isString) {
                // if the target entity->property is a string
                int length = (int) blob.length();
                byte[] ba = blob.getBytes(0L, length);
                return new String(ba, charset);
            } else if (isByteArray) {
                // if the target entity->property is a byte array
                int length = (int) blob.length();
                byte[] ba = blob.getBytes(0L, length);
                return ba;
            } else if (isInputStream) {
                return blob.getBinaryStream();
            } else if (BlobStream.class.isAssignableFrom(targetType)) {
                BlobStream bs = new BlobStream(blob.getBinaryStream());
                return bs;
            }

        } catch (Exception e) {
            logger.error("Unable to copy data from blob stream into target byte array on entity "
                    + pb.getEntityClass() + " paramater " + pb.getBindingPath() + " and column "
                    + pb.getColumnName());
        }
    }

    return null;
}

From source file:org.springframework.jdbc.support.lob.OracleLobHandler.java

@Override
public byte[] getBlobAsBytes(ResultSet rs, int columnIndex) throws SQLException {
    logger.debug("Returning Oracle BLOB as bytes");
    Blob blob = rs.getBlob(columnIndex);
    initializeResourcesBeforeRead(rs.getStatement().getConnection(), blob);
    byte[] retVal = (blob != null ? blob.getBytes(1, (int) blob.length()) : null);
    releaseResourcesAfterRead(rs.getStatement().getConnection(), blob);
    return retVal;
}

From source file:net.sf.jasperreports.engine.JRResultSetDataSource.java

protected byte[] readBytes(Integer columnIndex) throws SQLException, IOException {
    InputStream is = null;/*from   www. j  a v  a  2 s. com*/
    long size = -1;

    int columnType = resultSet.getMetaData().getColumnType(columnIndex);
    switch (columnType) {
    case Types.BLOB:
        Blob blob = resultSet.getBlob(columnIndex);
        if (!resultSet.wasNull()) {
            is = blob.getBinaryStream();
            size = blob.length();
        }
        break;

    default:
        is = resultSet.getBinaryStream(columnIndex);
        if (resultSet.wasNull()) {
            is = null;
        }
    }

    byte[] bytes = null;
    if (is != null) {
        bytes = readBytes(is, size);
    }

    return bytes;
}

From source file:org.sakaiproject.component.common.edu.person.InetOrgPersonImpl.java

private byte[] toByteArray(Blob fromBlob, ByteArrayOutputStream baos) throws SQLException, IOException {
    if (LOG.isDebugEnabled()) {
        LOG.debug("toByteArray(Blob " + fromBlob + ", ByteArrayOutputStream " + baos + ")");
    }/*w w w . java  2 s .c  om*/

    if (fromBlob == null || fromBlob.length() < 1
            || ServerConfigurationService.getString("profile.photoRepositoryPath", null) != null) {
        return null;
    }
    byte[] buf = new byte[4000];
    InputStream is = fromBlob.getBinaryStream();
    try {
        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.error(ex.getMessage(), ex);
            }
        }
    }
    return baos.toByteArray();
}

From source file:IDlookGetStream.java

private void buildGUI() {
    Container c = getContentPane();
    c.setLayout(new FlowLayout());

    accountNumberList = new JList();
    loadAccounts();//w w  w .j  a va 2s. c  om
    accountNumberList.setVisibleRowCount(2);
    JScrollPane accountNumberListScrollPane = new JScrollPane(accountNumberList);

    //Do Get Account Button
    getAccountButton = new JButton("Get Account");
    getAccountButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            try {
                rs.beforeFirst();
                while (rs.next()) {
                    if (rs.getString("acc_id").equals(accountNumberList.getSelectedValue()))
                        break;
                }
                if (!rs.isAfterLast()) {
                    accountIDText.setText(rs.getString("acc_id"));
                    thumbIDText.setText(rs.getString("thumb_id"));
                    Blob blob = rs.getBlob("pic");

                    int b;
                    InputStream bis = rs.getBinaryStream("pic");
                    FileOutputStream f = new FileOutputStream("pic.jpg");
                    while ((b = bis.read()) >= 0) {
                        f.write(b);
                    }
                    f.close();
                    bis.close();

                    icon = new ImageIcon(blob.getBytes(1L, (int) blob.length()));
                    createThumbnail();
                    photographLabel.setIcon(iconThumbnail);
                }
            } catch (Exception selectException) {
                displaySQLErrors(selectException);
            }
        }
    });

    //Do Update Account Button
    updateAccountButton = new JButton("Update Account");
    updateAccountButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            try {
                byte[] bytes = new byte[50000];
                FileInputStream fs = new FileInputStream(nailFileText.getText());
                BufferedInputStream bis = new BufferedInputStream(fs);
                bis.read(bytes);

                rs.updateBytes("thumbnail.pic", bytes);
                rs.updateRow();
                bis.close();

                accountNumberList.removeAll();
                loadAccounts();
            } catch (SQLException insertException) {
                displaySQLErrors(insertException);
            } catch (Exception generalE) {
                generalE.printStackTrace();
            }
        }
    });

    //Do insert Account Button
    insertAccountButton = new JButton("Insert Account");
    insertAccountButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            try {
                byte[] bytes = new byte[50000];
                FileInputStream fs = new FileInputStream(nailFileText.getText());
                BufferedInputStream bis = new BufferedInputStream(fs);
                bis.read(bytes);

                rs.moveToInsertRow();
                rs.updateInt("thumb_id", Integer.parseInt(thumbIDText.getText()));
                rs.updateInt("acc_id", Integer.parseInt(accountIDText.getText()));
                rs.updateBytes("pic", bytes);
                rs.updateObject("sysobject", null);
                rs.updateTimestamp("ts", new Timestamp(0));
                rs.updateTimestamp("act_ts", new Timestamp(new java.util.Date().getTime()));
                rs.insertRow();
                bis.close();

                accountNumberList.removeAll();
                loadAccounts();
            } catch (SQLException insertException) {
                displaySQLErrors(insertException);
            } catch (Exception generalE) {
                generalE.printStackTrace();
            }
        }
    });

    photographLabel = new JLabel();
    photographLabel.setHorizontalAlignment(JLabel.CENTER);
    photographLabel.setVerticalAlignment(JLabel.CENTER);
    photographLabel.setVerticalTextPosition(JLabel.CENTER);
    photographLabel.setHorizontalTextPosition(JLabel.CENTER);

    JPanel first = new JPanel(new GridLayout(4, 1));
    first.add(accountNumberListScrollPane);
    first.add(getAccountButton);
    first.add(updateAccountButton);
    first.add(insertAccountButton);

    accountIDText = new JTextField(15);
    thumbIDText = new JTextField(15);
    errorText = new JTextArea(5, 15);
    errorText.setEditable(false);

    JPanel second = new JPanel();
    second.setLayout(new GridLayout(2, 1));
    second.add(thumbIDText);
    second.add(accountIDText);

    JPanel third = new JPanel();
    third.add(new JScrollPane(errorText));

    nailFileText = new JTextField(25);

    c.add(first);
    c.add(second);
    c.add(third);
    c.add(nailFileText);
    c.add(photographLabel);

    setSize(500, 500);
    show();
}