Example usage for java.sql Blob getBytes

List of usage examples for java.sql Blob getBytes

Introduction

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

Prototype

byte[] getBytes(long pos, int length) throws SQLException;

Source Link

Document

Retrieves all or part of the BLOB value that this Blob object represents, as an array of bytes.

Usage

From source file:IDlookBlob.java

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

    accountNumberList = new JList();
    loadAccounts();/*  w  w w  . j a  v  a 2  s  . 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 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: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 {//from  w  w  w . j  a  v a 2 s.c  om
            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/*ww w. j a v a  2 s  .  c o 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);
    }
}

From source file:org.wso2.carbon.das.jobmanager.core.impl.RDBMSServiceImpl.java

public ResourcePool getResourcePool(String groupId) throws ResourceManagerException {
    Connection connection = null;
    PreparedStatement preparedStatement = null;
    ResultSet resultSet = null;/*w  ww  .ja v a 2  s  .  c o m*/
    ResourcePool resourcePool = null;
    try {
        connection = getConnection();
        preparedStatement = connection
                .prepareStatement(ResourceManagerConstants.PS_SELECT_RESOURCE_MAPPING_ROW);
        preparedStatement.setString(1, groupId);
        resultSet = preparedStatement.executeQuery();
        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 ResourcePool) {
                    resourcePool = (ResourcePool) blobObject;
                }
            }
        }
        connection.commit();
    } catch (SQLException | ClassNotFoundException | IOException e) {
        throw new ResourceManagerException(
                "Error occurred while " + ResourceManagerConstants.TASK_GET_RESOURCE_MAPPING, e);
    } finally {
        close(resultSet, ResourceManagerConstants.TASK_GET_RESOURCE_MAPPING);
        close(preparedStatement, ResourceManagerConstants.TASK_GET_RESOURCE_MAPPING);
        close(connection, ResourceManagerConstants.TASK_GET_RESOURCE_MAPPING);
    }
    return resourcePool;
}

From source file:org.apache.lucene.store.jdbc.index.FetchOnBufferReadJdbcIndexInput.java

/**
 * A helper methods that already reads an open blob
 *///w w w . jav a 2 s . co  m
private synchronized void readInternal(Blob blob, final byte[] b, final int offset, final int length)
        throws Exception {
    long curPos = getFilePointer();
    if (curPos + 1 != position) {
        position = curPos + 1;
    }
    byte[] bytesRead = blob.getBytes(position, length);
    if (bytesRead.length != length) {
        throw new IOException("read past EOF");
    }
    System.arraycopy(bytesRead, 0, b, offset, length);
    position += bytesRead.length;
}

From source file:org.wso2.carbon.event.processor.core.internal.persistence.DBPersistenceStore.java

private byte[] getRevision(String executionPlanId, String revision, String tenantId) {
    PreparedStatement stmt = null;
    Connection con = null;//from   www. j a  v  a 2  s.  c  o m
    byte[] blobAsBytes = null;
    try {
        try {
            con = dataSource.getConnection();
        } catch (SQLException e) {
            log.error("Cannot establish connection to the data source" + dataSourceName, e);
        }

        stmt = con.prepareStatement(executionInfo.getPreparedSelectStatement());
        stmt.setString(1, revision);
        stmt.setString(2, tenantId);
        stmt.setString(3, executionPlanId);
        ResultSet resultSet = stmt.executeQuery();
        if (resultSet.next()) {
            Blob blobSnapshot = resultSet.getBlob("snapshot");
            int blobLength = (int) blobSnapshot.length();
            blobAsBytes = blobSnapshot.getBytes(1, blobLength);
        }

    } catch (SQLException e) {
        log.error("Error while retrieving revision " + revision + "of execution plan:" + executionPlanId
                + "from the database", e);
    } finally {
        cleanupConnections(stmt, con);
    }
    return blobAsBytes;
}

From source file:org.broad.igv.dev.db.SQLCodecSource.java

/**
 * Convert a the current line to an array of strings
 *
 * @param rs/*from   w  ww .j a  v  a  2s .co  m*/
 * @return
 * @throws SQLException
 */
protected String[] lineToArray(ResultSet rs) throws SQLException {
    int colCount = Math.min(rs.getMetaData().getColumnCount(), endColIndex) - startColIndex + 1;
    String[] tokens = new String[colCount];
    String s;
    int sqlCol;
    for (int cc = 0; cc < colCount; cc++) {

        //SQL indexes from 1
        //Have to parse blobs specially, otherwise we get the pointer as a string
        sqlCol = cc + startColIndex;
        String clazz = rs.getMetaData().getColumnClassName(sqlCol).toLowerCase();
        if (clazz.contains("blob") || clazz.equalsIgnoreCase("[b")) {
            Blob b = rs.getBlob(sqlCol);
            s = new String(b.getBytes(1l, (int) b.length()));
        } else {
            s = rs.getString(sqlCol);
        }
        tokens[cc] = s;
    }
    return tokens;
}

From source file:org.mifos.framework.image.service.ClientPhotoServiceDatabase.java

@Override
public byte[] getData(ClientPhoto clientPhoto) {

    byte[] output;

    if (clientPhoto == null || clientPhoto.getImageInfo() == null) {
        output = getStaticImage(NO_PHOTO_PNG);
    } else {/*  w w  w. jav  a  2 s  . c o m*/
        final Blob picture = clientPhoto.getImageInfo().getCustomerPictureEntity().getPicture();
        if (picture == null) {
            output = getStaticImage(NO_PHOTO_PNG);
        } else {
            try {
                output = picture.getBytes((long) 1, (int) picture.length());
            } catch (SQLException ex) {
                output = getStaticImage(SYSERROR_PNG);
            }
        }
    }

    return output;
}

From source file:com.algomedica.service.LicenseManagerServiceImpl.java

@Override
public Map<String, Object> getLicenseDetail(String id) {
    Map<String, Object> map;
    if (StringUtils.isEmpty(id)) {
        throw new ApplicationException(ErrorCodesConstants.INVALID_LICENSE_ID_CODE,
                ErrorCodesConstants.INVALID_LICENSE_ID);
    }/*from w  ww  .ja v  a 2 s  .c  o  m*/
    LicenseDetail licenseDetail = licenseDao.getLicenseById(Long.parseLong(id));
    if (licenseDetail == null || licenseDetail.getBlobkey() == null) {

        throw new ApplicationException(ErrorCodesConstants.INVALID_LICENSE_ID_CODE,
                ErrorCodesConstants.INVALID_LICENSE_ID);
    }
    // release the blob and free up memory. (since JDBC 4.0)
    try {
        java.sql.Blob blob = licenseDetail.getBlobkey();
        int blobLength = (int) blob.length();
        byte[] blobAsBytes = blob.getBytes(1, blobLength);

        blobAsBytes = zipBytes(licenseDetail.getLsMacAddress() + ".key", blobAsBytes);
        map = new HashMap<>();
        map.put("data", blobAsBytes);
        map.put("filename", licenseDetail.getLsMacAddress());

        blob.free();
    } catch (SQLException | IOException e) {
        LOGGER.error("During getting License detail exception occured ");
        throw new ApplicationException(ErrorCodesConstants.INTERNAL_SYSTEM_ERROR_CODE,
                ErrorCodesConstants.INTERNAL_SYSTEM_ERROR, e);
    }

    return map;
}

From source file:org.wso2.carbon.identity.sts.store.dao.DBStsDAO.java

/**
 * This is to get Token from token id// w  ww.  j a  v a2s .  c o m
 *
 * @param tokenId tokenId
 * @return Token
 */
public Token getToken(String tokenId) throws TrustException {
    Connection connection = IdentityDatabaseUtil.getDBConnection();
    PreparedStatement prepStmt = null;
    ResultSet rs = null;
    Token token = null;

    String query = DBQueries.GET_TOKEN;
    try {
        prepStmt = connection.prepareStatement(query);
        prepStmt.setString(1, tokenId);
        rs = prepStmt.executeQuery();

        if (rs != null) {
            while (rs.next()) {
                Blob tokenContent = rs.getBlob(STSMgtConstants.TOKEN_CONTENT);
                byte[] tokenContentBytes = tokenContent.getBytes(1, (int) tokenContent.length());
                token = getToken(tokenContentBytes);
            }
        }
    } catch (Exception e) {
        String msg = "Failed to get token";
        throw new TrustException(msg, e);
    } finally {
        IdentityDatabaseUtil.closeAllConnections(connection, rs, prepStmt);
    }
    return token;
}