Example usage for javax.sql.rowset.serial SerialBlob SerialBlob

List of usage examples for javax.sql.rowset.serial SerialBlob SerialBlob

Introduction

In this page you can find the example usage for javax.sql.rowset.serial SerialBlob SerialBlob.

Prototype

public SerialBlob(Blob blob) throws SerialException, SQLException 

Source Link

Document

Constructs a SerialBlob object that is a serialized version of the given Blob object.

Usage

From source file:org.moqui.impl.entity.EntityJavaUtil.java

public static Object convertFromString(String value, FieldInfo fi, L10nFacade l10n) {
    Object outValue;/* w  w  w .  j  ava 2 s .  co  m*/
    boolean isEmpty = value.length() == 0;

    try {
        switch (fi.typeValue) {
        case 1:
            outValue = value;
            break;
        case 2: // outValue = java.sql.Timestamp.valueOf(value);
            if (isEmpty) {
                outValue = null;
                break;
            }
            outValue = l10n.parseTimestamp(value, null);
            if (outValue == null)
                throw new BaseException("The value [" + value + "] is not a valid date/time for field "
                        + fi.entityName + "." + fi.name);
            break;
        case 3: // outValue = java.sql.Time.valueOf(value);
            if (isEmpty) {
                outValue = null;
                break;
            }
            outValue = l10n.parseTime(value, null);
            if (outValue == null)
                throw new BaseException("The value [" + value + "] is not a valid time for field "
                        + fi.entityName + "." + fi.name);
            break;
        case 4: // outValue = java.sql.Date.valueOf(value);
            if (isEmpty) {
                outValue = null;
                break;
            }
            outValue = l10n.parseDate(value, null);
            if (outValue == null)
                throw new BaseException("The value [" + value + "] is not a valid date for field "
                        + fi.entityName + "." + fi.name);
            break;
        case 5: // outValue = Integer.valueOf(value); break
        case 6: // outValue = Long.valueOf(value); break
        case 7: // outValue = Float.valueOf(value); break
        case 8: // outValue = Double.valueOf(value); break
        case 9: // outValue = new BigDecimal(value); break
            if (isEmpty) {
                outValue = null;
                break;
            }
            BigDecimal bdVal = l10n.parseNumber(value, null);
            if (bdVal == null) {
                throw new BaseException("The value [" + value + "] is not valid for type [" + fi.javaType
                        + "] for field " + fi.entityName + "." + fi.name);
            } else {
                bdVal = bdVal.stripTrailingZeros();
                switch (fi.typeValue) {
                case 5:
                    outValue = bdVal.intValue();
                    break;
                case 6:
                    outValue = bdVal.longValue();
                    break;
                case 7:
                    outValue = bdVal.floatValue();
                    break;
                case 8:
                    outValue = bdVal.doubleValue();
                    break;
                default:
                    outValue = bdVal;
                    break;
                }
            }
            break;
        case 10:
            if (isEmpty) {
                outValue = null;
                break;
            }
            outValue = Boolean.valueOf(value);
            break;
        case 11:
            outValue = value;
            break;
        case 12:
            try {
                outValue = new SerialBlob(value.getBytes());
            } catch (SQLException e) {
                throw new BaseException("Error creating SerialBlob for value [" + value + "] for field "
                        + fi.entityName + "." + fi.name);
            }
            break;
        case 13:
            outValue = value;
            break;
        case 14:
            if (isEmpty) {
                outValue = null;
                break;
            }
            Timestamp ts = l10n.parseTimestamp(value, null);
            outValue = new java.util.Date(ts.getTime());
            break;
        // better way for Collection (15)? maybe parse comma separated, but probably doesn't make sense in the first place
        case 15:
            outValue = value;
            break;
        default:
            outValue = value;
            break;
        }
    } catch (IllegalArgumentException e) {
        throw new BaseException("The value [" + value + "] is not valid for type [" + fi.javaType
                + "] for field " + fi.entityName + "." + fi.name, e);
    }

    return outValue;
}

From source file:org.moqui.impl.entity.EntityJavaUtil.java

public static Object getResultSetValue(ResultSet rs, int index, FieldInfo fi, EntityFacade efi)
        throws EntityException {
    if (fi.typeValue == -1)
        throw new EntityException("No typeValue found for " + fi.entityName + "." + fi.name);

    Object value = null;//from w w w.j a va2  s .  com
    try {
        switch (fi.typeValue) {
        case 1:
            // getMetaData and the column type are somewhat slow (based on profiling), and String values are VERY
            //     common, so only do for text-very-long
            if (fi.isTextVeryLong) {
                ResultSetMetaData rsmd = rs.getMetaData();
                if (Types.CLOB == rsmd.getColumnType(index)) {
                    // if the String is empty, try to get a text input stream, this is required for some databases
                    // for larger fields, like CLOBs
                    Clob valueClob = rs.getClob(index);
                    Reader valueReader = null;
                    if (valueClob != null)
                        valueReader = valueClob.getCharacterStream();
                    if (valueReader != null) {
                        // read up to 4096 at a time
                        char[] inCharBuffer = new char[4096];
                        StringBuilder strBuf = new StringBuilder();
                        try {
                            int charsRead;
                            while ((charsRead = valueReader.read(inCharBuffer, 0, 4096)) > 0) {
                                strBuf.append(inCharBuffer, 0, charsRead);
                            }
                            valueReader.close();
                        } catch (IOException e) {
                            throw new EntityException("Error reading long character stream for field ["
                                    + fi.name + "] of entity [" + fi.entityName + "]", e);
                        }
                        value = strBuf.toString();
                    }
                } else {
                    value = rs.getString(index);
                }
            } else {
                value = rs.getString(index);
            }
            break;
        case 2:
            try {
                value = rs.getTimestamp(index, efi.getCalendarForTzLc());
            } catch (SQLException e) {
                if (logger.isTraceEnabled())
                    logger.trace(
                            "Ignoring SQLException for getTimestamp(), leaving null (found this in MySQL with a date/time value of [0000-00-00 00:00:00]): "
                                    + e.toString());
            }
            break;
        case 3:
            value = rs.getTime(index, efi.getCalendarForTzLc());
            break;
        case 4:
            value = rs.getDate(index, efi.getCalendarForTzLc());
            break;
        case 5:
            int intValue = rs.getInt(index);
            if (!rs.wasNull())
                value = intValue;
            break;
        case 6:
            long longValue = rs.getLong(index);
            if (!rs.wasNull())
                value = longValue;
            break;
        case 7:
            float floatValue = rs.getFloat(index);
            if (!rs.wasNull())
                value = floatValue;
            break;
        case 8:
            double doubleValue = rs.getDouble(index);
            if (!rs.wasNull())
                value = doubleValue;
            break;
        case 9:
            BigDecimal bigDecimalValue = rs.getBigDecimal(index);
            if (!rs.wasNull())
                value = bigDecimalValue != null ? bigDecimalValue.stripTrailingZeros() : null;
            break;
        case 10:
            boolean booleanValue = rs.getBoolean(index);
            if (!rs.wasNull())
                value = booleanValue;
            break;
        case 11:
            Object obj = null;
            byte[] originalBytes = rs.getBytes(index);
            InputStream binaryInput = null;
            if (originalBytes != null && originalBytes.length > 0) {
                binaryInput = new ByteArrayInputStream(originalBytes);
            }
            if (originalBytes != null && originalBytes.length <= 0) {
                logger.warn("Got byte array back empty for serialized Object with length ["
                        + originalBytes.length + "] for field [" + fi.name + "] (" + index + ")");
            }
            if (binaryInput != null) {
                ObjectInputStream inStream = null;
                try {
                    inStream = new ObjectInputStream(binaryInput);
                    obj = inStream.readObject();
                } catch (IOException ex) {
                    if (logger.isTraceEnabled())
                        logger.trace("Unable to read BLOB from input stream for field [" + fi.name + "] ("
                                + index + "): " + ex.toString());
                } catch (ClassNotFoundException ex) {
                    if (logger.isTraceEnabled())
                        logger.trace("Class not found: Unable to cast BLOB data to an Java object for field ["
                                + fi.name + "] (" + index
                                + "); most likely because it is a straight byte[], so just using the raw bytes: "
                                + ex.toString());
                } finally {
                    if (inStream != null) {
                        try {
                            inStream.close();
                        } catch (IOException e) {
                            throw new EntityException("Unable to close binary input stream for field ["
                                    + fi.name + "] (" + index + "): " + e.toString(), e);
                        }
                    }
                }
            }
            if (obj != null) {
                value = obj;
            } else {
                value = originalBytes;
            }
            break;
        case 12:
            SerialBlob sblob = null;
            try {
                // NOTE: changed to try getBytes first because Derby blows up on getBlob and on then calling getBytes for the same field, complains about getting value twice
                byte[] fieldBytes = rs.getBytes(index);
                if (!rs.wasNull())
                    sblob = new SerialBlob(fieldBytes);
                // fieldBytes = theBlob != null ? theBlob.getBytes(1, (int) theBlob.length()) : null
            } catch (SQLException e) {
                if (logger.isTraceEnabled())
                    logger.trace("Ignoring exception trying getBytes(), trying getBlob(): " + e.toString());
                Blob theBlob = rs.getBlob(index);
                if (!rs.wasNull())
                    sblob = new SerialBlob(theBlob);
            }
            value = sblob;
            break;
        case 13:
            value = new SerialClob(rs.getClob(index));
            break;
        case 14:
        case 15:
            value = rs.getObject(index);
            break;
        }
    } catch (SQLException sqle) {
        logger.error("SQL Exception while getting value for field: [" + fi.name + "] (" + index + ")", sqle);
        throw new EntityException(
                "SQL Exception while getting value for field: [" + fi.name + "] (" + index + ")", sqle);
    }

    return value;
}

From source file:org.ojbc.adapters.rapbackdatastore.dao.RapbackDAOImpl.java

@Override
public Integer saveCivilFingerPrints(final CivilFingerPrints civilFingerPrints) {
    log.debug("Inserting row into CIVIL_FINGER_PRINTS table : " + civilFingerPrints.toString());

    final String CIVIL_FINGER_PRINTS_INSERT = "insert into CIVIL_FINGER_PRINTS "
            + "(TRANSACTION_NUMBER, FINGER_PRINTS_FILE, FINGER_PRINTS_TYPE_ID) " + "values (?, ?, ?)";

    KeyHolder keyHolder = new GeneratedKeyHolder();
    jdbcTemplate.update(new PreparedStatementCreator() {
        public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
            PreparedStatement ps = connection.prepareStatement(CIVIL_FINGER_PRINTS_INSERT,
                    new String[] { "TRANSACTION_NUMBER", "FINGER_PRINTS_FILE", "FINGER_PRINTS_TYPE" });
            ps.setString(1, civilFingerPrints.getTransactionNumber());

            if (civilFingerPrints.getFingerPrintsFile() != null) {
                ps.setBlob(2, new SerialBlob(ZipUtils.zip(civilFingerPrints.getFingerPrintsFile())));
            }/*ww  w  .  j  ava 2  s.  c om*/
            ps.setInt(3, civilFingerPrints.getFingerPrintsType().ordinal() + 1);
            return ps;
        }
    }, keyHolder);

    return keyHolder.getKey().intValue();
}

From source file:org.ojbc.adapters.rapbackdatastore.dao.RapbackDAOImpl.java

@Override
public Integer saveCivilInitialRapSheet(final CivilInitialRapSheet civilInitialRapSheet) {
    log.debug("Inserting row into CIVIL_INITIAL_RAP_SHEET table : " + civilInitialRapSheet.toString());

    final String CIVIL_INITIAL_RAP_SHEET_INSERT = "insert into CIVIL_INITIAL_RAP_SHEET "
            + "(CIVIL_INITIAL_RESULT_ID, RAP_SHEET) " + "values (?, ?)";

    KeyHolder keyHolder = new GeneratedKeyHolder();
    jdbcTemplate.update(new PreparedStatementCreator() {
        public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
            PreparedStatement ps = connection.prepareStatement(CIVIL_INITIAL_RAP_SHEET_INSERT,
                    new String[] { "CIVIL_INITIAL_RESULT_ID", "RAP_SHEET" });
            ps.setInt(1, civilInitialRapSheet.getCivilIntitialResultId());
            ps.setBlob(2, new SerialBlob(ZipUtils.zip(civilInitialRapSheet.getRapSheet())));
            return ps;
        }/*from ww w .jav  a 2s . c  om*/
    }, keyHolder);

    return keyHolder.getKey().intValue();
}

From source file:org.ojbc.adapters.rapbackdatastore.dao.RapbackDAOImpl.java

@Override
public Integer saveCivilInitialResults(final CivilInitialResults civilInitialResults) {
    log.debug("Inserting row into CIVIL_INITIAL_RESULTS table : " + civilInitialResults.toString());

    final String CIVIL_INITIAL_RESULTS_INSERT = "insert into CIVIL_INITIAL_RESULTS "
            + "(TRANSACTION_NUMBER, SEARCH_RESULT_FILE, " + " RESULTS_SENDER_ID) " + "values (?, ?, ?)";

    KeyHolder keyHolder = new GeneratedKeyHolder();
    jdbcTemplate.update(new PreparedStatementCreator() {
        public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
            PreparedStatement ps = connection.prepareStatement(CIVIL_INITIAL_RESULTS_INSERT,
                    new String[] { "TRANSACTION_NUMBER", "MATCH_NO_MATCH", "RESULTS_SENDER_ID" });
            ps.setString(1, civilInitialResults.getTransactionNumber());
            ps.setBlob(2, new SerialBlob(ZipUtils.zip(civilInitialResults.getSearchResultFile())));
            ps.setInt(3, civilInitialResults.getResultsSender().ordinal() + 1);
            return ps;
        }/*from ww w. ja  v  a  2  s  . c  om*/
    }, keyHolder);

    return keyHolder.getKey().intValue();
}

From source file:org.ojbc.adapters.rapbackdatastore.dao.RapbackDAOImpl.java

@Override
public Integer saveCriminalInitialResults(final CriminalInitialResults criminalInitialResults) {
    log.debug("Inserting row into CRIMINAL_INITIAL_RESULTS table : " + criminalInitialResults.toString());

    final String CRIMINAL_INITIAL_RESULTS_INSERT = "insert into CRIMINAL_INITIAL_RESULTS "
            + "(TRANSACTION_NUMBER, SEARCH_RESULT_FILE, RESULTS_SENDER_ID) " + "values (?, ?, ?)";

    KeyHolder keyHolder = new GeneratedKeyHolder();
    jdbcTemplate.update(new PreparedStatementCreator() {
        public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
            PreparedStatement ps = connection.prepareStatement(CRIMINAL_INITIAL_RESULTS_INSERT,
                    new String[] { "TRANSACTION_NUMBER", "SEARCH_RESULT_FILE", "RESULTS_SENDER_ID" });
            ps.setString(1, criminalInitialResults.getTransactionNumber());
            ps.setBlob(2, new SerialBlob(ZipUtils.zip(criminalInitialResults.getSearchResultFile())));
            ps.setInt(3, criminalInitialResults.getResultsSender().ordinal() + 1);
            return ps;
        }/*from w ww.ja v a 2s  . c om*/
    }, keyHolder);

    return keyHolder.getKey().intValue();
}

From source file:org.ojbc.intermediaries.sn.dao.rapback.FbiRapbackDao.java

public Integer saveSubsequentResults(final SubsequentResults subsequentResults) {
    log.debug("Inserting row into SUBSEQUENT_RESULTS table : " + subsequentResults.toString());

    final String SUBSEQUENT_RESULTS_INSERT = "insert into SUBSEQUENT_RESULTS "
            + "(ucn, RAP_SHEET, RESULTS_SENDER_ID) " + "values (?, ?, ?)";
    KeyHolder keyHolder = new GeneratedKeyHolder();
    jdbcTemplate.update(new PreparedStatementCreator() {
        public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
            PreparedStatement ps = connection.prepareStatement(SUBSEQUENT_RESULTS_INSERT,
                    new String[] { "ucn", "RAP_SHEET", "RESULTS_SENDER_ID" });
            ps.setString(1, subsequentResults.getUcn());
            ps.setBlob(2, new SerialBlob(ZipUtils.zip(subsequentResults.getRapSheet())));
            ps.setInt(3, subsequentResults.getResultsSender().ordinal() + 1);
            return ps;
        }//from   w  w  w.java2  s . c  o m
    }, keyHolder);

    return keyHolder.getKey().intValue();
}

From source file:org.vulpe.commons.util.VulpeStringUtil.java

/**
  * Convert SQL Blob to String./*from   w ww.j  ava2s.  c  om*/
  *
  * @param blob
  * @return
  */
 public static Blob stringToBlob(final String string) {
     Blob blob = null;
     try {
         blob = new SerialBlob(string.getBytes());
     } catch (Exception e) {
         LOG.error(e.getMessage());
     }
     return blob;
 }

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

public void saveRevision(String executionPlanId, String revision, byte[] snapshot) {

    PreparedStatement stmt = null;
    Connection con = null;//from  ww  w  .j a va  2  s  .c  o m
    try {
        try {
            con = dataSource.getConnection();
            con.setAutoCommit(false);
        } catch (SQLException e) {
            log.error("Cannot establish connection to the data source" + dataSourceName, e);
        }
        stmt = con.prepareStatement(executionInfo.getPreparedInsertStatement());
        stmt.setString(1, getTenantId());
        stmt.setString(2, executionPlanId);
        stmt.setString(3, revision);
        stmt.setBlob(4, new SerialBlob(snapshot));
        stmt.executeUpdate();
        con.commit();
    } catch (SQLException e) {
        log.error("Error while saving revision" + revision + " of the execution plan" + executionPlanId
                + "to the database", e);
    } finally {
        cleanupConnections(stmt, con);
    }
}

From source file:org.xenei.jdbc4sparql.iface.TypeConverter.java

@SuppressWarnings("unchecked")
public static <T> T extractData(final Object columnObject, final Class<T> resultingClass) throws SQLException {
    if (columnObject == null) {
        return (T) nullValueMap.get(resultingClass);
    }/*  w  w w  .ja v a2s . c om*/

    // try the simple case
    if (resultingClass.isAssignableFrom(columnObject.getClass())) {
        return resultingClass.cast(columnObject);
    }

    // see if we can do a simple numeric assignment
    if (columnObject instanceof Number) {
        return fromNumber(columnObject, resultingClass);
    }

    // see if we can convert from a string
    if (columnObject instanceof String) {
        return fromString(columnObject, resultingClass);
    }

    if (columnObject instanceof Boolean) {
        final Boolean b = (Boolean) columnObject;
        return fromString(b ? "1" : "0", resultingClass);
    }

    if (columnObject instanceof byte[]) {
        try {
            if (resultingClass.isAssignableFrom(Clob.class)) {
                return resultingClass.cast(
                        new SerialClob(IOUtils.toCharArray(new ByteArrayInputStream((byte[]) columnObject))));
            }
            if (resultingClass.isAssignableFrom(Blob.class)) {
                return resultingClass.cast(new SerialBlob((byte[]) columnObject));
            }
            if (resultingClass.isAssignableFrom(InputStream.class)) {
                return resultingClass.cast(new ByteArrayInputStream((byte[]) columnObject));
            }
            final String s = new String((byte[]) columnObject);
            return fromString(s, resultingClass);
        } catch (final IOException e) {
            throw new SQLException(e.getMessage(), e);
        }
    }

    if (columnObject instanceof Blob) {
        try {
            final Blob b = (Blob) columnObject;
            if (resultingClass.isAssignableFrom(byte[].class)) {
                return resultingClass.cast(IOUtils.toByteArray(b.getBinaryStream()));
            }
            if (resultingClass.isAssignableFrom(Clob.class)) {
                return resultingClass.cast(new SerialClob(IOUtils.toCharArray(b.getBinaryStream())));
            }
            if (resultingClass.isAssignableFrom(InputStream.class)) {
                return resultingClass.cast(b.getBinaryStream());
            }
            final String s = new String(IOUtils.toByteArray(((Blob) columnObject).getBinaryStream()));
            return fromString(s, resultingClass);
        } catch (final IOException e) {
            throw new SQLException(e.getMessage(), e);
        }
    }
    if (columnObject instanceof Clob) {
        try {
            final Clob c = (Clob) columnObject;
            if (resultingClass.isAssignableFrom(byte[].class)) {
                return resultingClass.cast(IOUtils.toByteArray(c.getAsciiStream()));
            }
            if (resultingClass.isAssignableFrom(Blob.class)) {
                return resultingClass.cast(new SerialBlob(IOUtils.toByteArray(c.getAsciiStream())));
            }
            if (resultingClass.isAssignableFrom(InputStream.class)) {
                return resultingClass.cast(c.getAsciiStream());
            }
            final String s = String.valueOf(IOUtils.toCharArray(c.getCharacterStream()));
            return fromString(s, resultingClass);
        } catch (final IOException e) {
            throw new SQLException(e.getMessage(), e);
        }
    }
    if (columnObject instanceof InputStream) {
        try {
            final InputStream is = (InputStream) columnObject;
            if (resultingClass.isAssignableFrom(Clob.class)) {
                return resultingClass.cast(new SerialClob(IOUtils.toCharArray(is)));
            }
            if (resultingClass.isAssignableFrom(Blob.class)) {
                return resultingClass.cast(new SerialBlob(IOUtils.toByteArray(is)));
            }
            if (resultingClass.isAssignableFrom(byte[].class)) {
                return resultingClass.cast(IOUtils.toByteArray(is));
            }
            return fromString(new String(IOUtils.toByteArray(is)), resultingClass);
        } catch (final IOException e) {
            throw new SQLException(e.getMessage(), e);
        }
    }
    throw new SQLException(String.format(" Can not cast %s (%s) to %s", columnObject.getClass(),
            columnObject.toString(), resultingClass));
}