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:com.orangeandbronze.jblubble.jdbc.springframework.SpringJdbcBlobstoreService.java

protected void serveBlobInternal(BlobKey blobKey, OutputStream out, long start, long end, boolean useEnd) {
    try {/*from  ww w.  ja  va2  s  .c  om*/
        jdbcTemplate.query(getSelectContentByIdSql(), (rs) -> {
            if (!rs.next()) {
                throw new BlobstoreException("Blob not found: " + blobKey);
            }
            Blob blob = rs.getBlob("content");
            try {
                long pos = start + 1;
                long length = useEnd ? (end - start + 1) : blob.length();
                try (InputStream in = new BufferedInputStream(blob.getBinaryStream(pos, length),
                        getBufferSize())) {
                    copy(in, out);
                } catch (IOException ioe) {
                    throw new BlobstoreException("Error while reading blob", ioe);
                }
                return blob.length();
            } finally {
                blob.free();
            }
        }, Long.valueOf(blobKey.stringValue()));
    } catch (DataAccessException e) {
        throw new BlobstoreException(e);
    }
}

From source file:com.npower.dm.export.XMLWriter4Software.java

private void writeFile4Package(SoftwarePackage softwarePackage) throws IOException, SQLException, DMException {
    if (softwarePackage.getBinary() != null) {
        String oldfileName = softwarePackage.getBlobFilename();
        String[] str = StringUtils.splitPreserveAllTokens(oldfileName, '.');
        String newfileName = str[0] + "." + softwarePackage.getId() + "." + str[1];
        File file = new File(System.getProperty("otas.dm.home"), "./output/softwares/packages");
        if (!file.exists()) {
            file.mkdirs();//from ww w. j a  v  a2  s.  co  m
        }
        file = new File(file, newfileName);
        FileOutputStream fos = new FileOutputStream(file);
        Blob binaryBlob = softwarePackage.getBinary().getBinaryBlob();
        fos.write(binaryBlob.getBytes(1, (int) binaryBlob.length()));
        fos.close();
    } else {
        throw new DMException("file of softwarePackage is null");
    }
}

From source file:com.mirth.connect.connectors.jdbc.DatabaseReceiver.java

/**
 * Convert an object into a string for insertion in the XML
 *///from w w w  . ja v  a2 s .c  om
private String objectToString(Object object) throws Exception {
    if (object == null) {
        return null;
    }

    String charsetEncoding = CharsetUtils.getEncoding(connectorProperties.getEncoding(),
            System.getProperty("ca.uhn.hl7v2.llp.charset"));

    if (object instanceof byte[]) {
        return new String((byte[]) object, charsetEncoding);
    }

    if (object instanceof Clob) {
        return clobToString((Clob) object);
    }

    if (object instanceof Blob) {
        Blob blob = (Blob) object;
        return new String(blob.getBytes(1, (int) blob.length()), charsetEncoding);
    }

    return object.toString();
}

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

private final ProgramMessageSymbol getProgramMessageSymbol(ResultSet resultSet) throws SQLException {
    int id = resultSet.getInt(Index.ID.index());
    int programID = resultSet.getInt(Index.PROGRAMID.index());
    String name = resultSet.getString(Index.NAME.index());
    Blob bytecodeBlob = resultSet.getBlob(Index.BYTECODE.index());
    Date timestamp = resultSet.getDate(Index.TIMESTAMP.index());

    byte[] bytecode = bytecodeBlob.getBytes(1, (int) bytecodeBlob.length());

    return new ProgramMessageSymbol(id, programID, name, bytecode, timestamp);
}

From source file:org.apache.sqoop.lib.LargeObjectLoader.java

/**
 * Actually read a BlobRef instance from the ResultSet and materialize
 * the data either inline or to a file.//from  w w w.  j a  v  a 2s.c o  m
 *
 * @param colNum the column of the ResultSet's current row to read.
 * @param r the ResultSet to read from.
 * @return a BlobRef encapsulating the data in this field.
 * @throws IOException if an error occurs writing to the FileSystem.
 * @throws SQLException if an error occurs reading from the database.
 */
public com.cloudera.sqoop.lib.BlobRef readBlobRef(int colNum, ResultSet r)
        throws IOException, InterruptedException, SQLException {

    long maxInlineLobLen = conf.getLong(MAX_INLINE_LOB_LEN_KEY, DEFAULT_MAX_LOB_LENGTH);

    Blob b = r.getBlob(colNum);
    if (null == b) {
        return null;
    } else if (b.length() > maxInlineLobLen) {
        // Deserialize very large BLOBs into separate files.
        long len = b.length();
        LobFile.Writer lobWriter = getBlobWriter();

        long recordOffset = lobWriter.tell();
        InputStream is = null;
        OutputStream os = lobWriter.writeBlobRecord(len);
        try {
            is = b.getBinaryStream();
            copyAll(is, os);
        } finally {
            if (null != os) {
                os.close();
            }

            if (null != is) {
                is.close();
            }

            // Mark the record as finished.
            lobWriter.finishRecord();
        }

        return new com.cloudera.sqoop.lib.BlobRef(getRelativePath(curBlobWriter), recordOffset, len);
    } else {
        // This is a 1-based array.
        return new com.cloudera.sqoop.lib.BlobRef(b.getBytes(1, (int) b.length()));
    }
}

From source file:org.sakaiproject.content.impl.serialize.impl.conversion.Type1BlobCollectionConversionHandler.java

public Object getValidateSource(String id, ResultSet rs) throws SQLException {
    ResultSetMetaData metadata = rs.getMetaData();
    byte[] rv = null;
    switch (metadata.getColumnType(1)) {
    case Types.BLOB:
        Blob blob = rs.getBlob(1);
        if (blob != null) {
            //System.out.println("getValidateSource(" + id + ") blob == " + blob + " blob.length == " + blob.length());
            rv = blob.getBytes(1L, (int) blob.length());
        } else {/*from  w  w  w . j a  v a2 s  .c o m*/
            System.out.println("getValidateSource(" + id + ") blob is null");
        }
        break;
    case Types.CLOB:
        Clob clob = rs.getClob(1);
        if (clob != null) {
            rv = clob.getSubString(1L, (int) clob.length()).getBytes();
        }
        break;
    case Types.CHAR:
    case Types.LONGVARCHAR:
    case Types.VARCHAR:
        rv = rs.getString(1).getBytes();
        break;
    case Types.BINARY:
    case Types.VARBINARY:
    case Types.LONGVARBINARY:
        rv = rs.getBytes(1);
        break;
    }
    //System.out.println("getValidateSource(" + id + ") \n" + rv + "\n");
    return rv;
}

From source file:IDlookBlob.java

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

    accountNumberList = new JList();
    loadAccounts();/*from   w ww  .j a  v  a2  s . c  o  m*/
    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 b = rs.getBlob("pic");

                    icon = new ImageIcon(b.getBytes(1L, (int) b.length()));
                    createThumbnail();
                    photographLabel.setIcon(iconThumbnail);
                }
            } catch (SQLException 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();
}

From source file:com.orangeandbronze.jblubble.jdbc.JdbcBlobstoreService.java

protected void serveBlobInternal(BlobKey blobKey, OutputStream out, long start, long end, boolean useEnd)
        throws IOException, BlobstoreException {
    readBlobInternal(blobKey, new BlobHandler() {
        @Override// w  w  w. ja  v  a2s  .  com
        public void handleBlob(Blob blob) throws SQLException, IOException {
            long pos = start + 1; // for java.sql.Blob the first byte is at position 1
            long length = useEnd ? (end - start + 1) : blob.length();
            try (InputStream in = new BufferedInputStream(blob.getBinaryStream(pos, length), getBufferSize())) {
                copy(in, out);
            }
        }
    });
}

From source file:org.sakaiproject.content.impl.serialize.impl.conversion.Type1BlobResourcesConversionHandler.java

public Object getValidateSource(String id, ResultSet rs) throws SQLException {
    ResultSetMetaData metadata = rs.getMetaData();
    byte[] rv = null;
    switch (metadata.getColumnType(1)) {
    case Types.BLOB:
        Blob blob = rs.getBlob(1);
        if (blob != null) {
            //System.out.println("getValidateSource(" + id + ") blob == " + blob + " blob.length == " + blob.length());
            rv = blob.getBytes(1L, (int) blob.length());
        } else {// w ww  . j  a  v a2  s.  c o  m
            System.out.println("getValidateSource(" + id + ") blob is null");
        }
        break;
    case Types.CLOB:
        Clob clob = rs.getClob(1);
        if (clob != null) {
            rv = clob.getSubString(1L, (int) clob.length()).getBytes();
        }
        break;
    case Types.CHAR:
    case Types.LONGVARCHAR:
    case Types.VARCHAR:
        rv = rs.getString(1).getBytes();
        break;
    case Types.BINARY:
    case Types.VARBINARY:
    case Types.LONGVARBINARY:
        rv = rs.getBytes(1);
        break;
    }
    // System.out.println("getValidateSource(" + id + ") \n" + rv + "\n");
    return rv;

    //return rs.getBytes(1);
}

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

@Override
@Nullable/*from ww w  .j  a  v  a 2 s.co m*/
public byte[] getBlobAsBytes(ResultSet rs, int columnIndex) throws SQLException {
    logger.debug("Returning BLOB as bytes");
    if (this.wrapAsLob) {
        Blob blob = rs.getBlob(columnIndex);
        return blob.getBytes(1, (int) blob.length());
    } else {
        return rs.getBytes(columnIndex);
    }
}