Java Examples for java.sql.Blob

The following java examples will help you to understand the usage of java.sql.Blob. These source code samples are taken from different open source projects.

Example 1
Project: paoding-rose-master  File: TypeUtils.java View source code
public static boolean isColumnType(Class<?> columnTypeCandidate) {
    return // NL
    String.class == columnTypeCandidate || // NL
    ClassUtils.isPrimitiveOrWrapper(columnTypeCandidate) || // NL
    Date.class.isAssignableFrom(columnTypeCandidate) || // NL
    columnTypeCandidate == byte[].class || // NL
    columnTypeCandidate == BigDecimal.class || // NL
    columnTypeCandidate == Blob.class || columnTypeCandidate == Clob.class;
}
Example 2
Project: Carbonado-master  File: JDBCBlob.java View source code
java.sql.Blob getInternalBlobForFetch() throws FetchException {
    if (mBlob == null) {
        if ((mBlob = mLoader.load(mRepo)) == null) {
            throw new FetchNoneException("Blob value is null");
        }
        try {
            JDBCTransaction txn = mRepo.localTransactionScope().getTxn();
            if (txn != null) {
                txn.register(this);
            }
        } catch (Exception e) {
            throw mRepo.toFetchException(e);
        }
    }
    return mBlob;
}
Example 3
Project: tddl-master  File: DataTypeUtil.java View source code
public static DataType getTypeOfObject(Object v) {
    if (v == null) {
        return DataType.NullType;
    }
    Class clazz = v.getClass();
    if (clazz == Integer.class || clazz == int.class) {
        return DataType.IntegerType;
    }
    if (clazz == Long.class || clazz == long.class) {
        return DataType.LongType;
    }
    if (clazz == Short.class || clazz == short.class) {
        return DataType.ShortType;
    }
    if (clazz == Float.class || clazz == float.class) {
        return DataType.FloatType;
    }
    if (clazz == Double.class || clazz == double.class) {
        return DataType.DoubleType;
    }
    if (clazz == Byte.class || clazz == byte.class) {
        return DataType.ByteType;
    }
    if (clazz == Boolean.class || clazz == boolean.class) {
        return DataType.BooleanType;
    }
    if (clazz == BigInteger.class) {
        return DataType.BigIntegerType;
    }
    if (clazz == BigDecimal.class) {
        return DataType.BigDecimalType;
    }
    if (clazz == Timestamp.class || clazz == java.util.Date.class || Calendar.class.isAssignableFrom(clazz)) {
        return DataType.TimestampType;
    }
    if (clazz == java.sql.Date.class) {
        return DataType.DateType;
    }
    if (clazz == Time.class) {
        return DataType.TimeType;
    }
    if (clazz == Byte[].class || clazz == byte[].class || Blob.class.isAssignableFrom(clazz)) {
        return DataType.BytesType;
    }
    if (clazz == String.class || Clob.class.isAssignableFrom(clazz)) {
        return DataType.StringType;
    }
    throw new TddlRuntimeException("type: " + v.getClass().getSimpleName() + " is not supported");
}
Example 4
Project: geolatte-geom-jpa-master  File: SqlServerConverter.java View source code
@SuppressWarnings("unchecked")
@Override
public T convertToEntityAttribute(final Object dbData) {
    if (null == dbData) {
        return null;
    } else {
        Throwable cause = null;
        if (dbData instanceof Blob) {
            try {
                final Blob blob = (Blob) dbData;
                return (T) Decoders.decode(blob.getBytes(1, (int) blob.length()));
            } catch (final SQLException sqle) {
                cause = sqle;
            }
        } else if (dbData instanceof byte[]) {
            return (T) Decoders.decode((byte[]) dbData);
        }
        throw new IllegalStateException("Unable to convert data value:" + dbData, cause);
    }
}
Example 5
Project: geolatte-geom-master  File: SqlServerConverter.java View source code
@SuppressWarnings("unchecked")
@Override
public T convertToEntityAttribute(final Object dbData) {
    if (null == dbData) {
        return null;
    } else {
        Throwable cause = null;
        if (dbData instanceof Blob) {
            try {
                final Blob blob = (Blob) dbData;
                return (T) Decoders.decode(blob.getBytes(1, (int) blob.length()));
            } catch (final SQLException sqle) {
                cause = sqle;
            }
        } else if (dbData instanceof byte[]) {
            return (T) Decoders.decode((byte[]) dbData);
        }
        throw new IllegalStateException("Unable to convert data value:" + dbData, cause);
    }
}
Example 6
Project: OEPv2-master  File: ApplicationLocalServiceClp.java View source code
@Override
public org.oep.ssomgt.model.Application addApplication(java.lang.String appCode, java.lang.String appName, java.lang.String appPin, java.lang.String appUrl, java.sql.Blob appBigIcon, java.sql.Blob appSmallIcon, java.util.Date pingTime, int sequenceNo, java.lang.String publicKey, com.liferay.portal.service.ServiceContext serviceContext) throws com.liferay.portal.kernel.exception.PortalException, com.liferay.portal.kernel.exception.SystemException {
    Object returnObj = null;
    try {
        returnObj = _invokableLocalService.invokeMethod(_methodName21, _methodParameterTypes21, new Object[] { ClpSerializer.translateInput(appCode), ClpSerializer.translateInput(appName), ClpSerializer.translateInput(appPin), ClpSerializer.translateInput(appUrl), ClpSerializer.translateInput(appBigIcon), ClpSerializer.translateInput(appSmallIcon), ClpSerializer.translateInput(pingTime), sequenceNo, ClpSerializer.translateInput(publicKey), ClpSerializer.translateInput(serviceContext) });
    } catch (Throwable t) {
        t = ClpSerializer.translateThrowable(t);
        if (t instanceof com.liferay.portal.kernel.exception.PortalException) {
            throw (com.liferay.portal.kernel.exception.PortalException) t;
        }
        if (t instanceof com.liferay.portal.kernel.exception.SystemException) {
            throw (com.liferay.portal.kernel.exception.SystemException) t;
        }
        if (t instanceof RuntimeException) {
            throw (RuntimeException) t;
        } else {
            throw new RuntimeException(t.getClass().getName() + " is not a valid exception");
        }
    }
    return (org.oep.ssomgt.model.Application) ClpSerializer.translateOutput(returnObj);
}
Example 7
Project: sql2o-master  File: ByteArrayConverter.java View source code
public byte[] convert(Object val) throws ConverterException {
    if (val == null)
        return null;
    if (val instanceof Blob) {
        Blob b = (Blob) val;
        InputStream stream = null;
        try {
            try {
                stream = b.getBinaryStream();
                return IOUtils.toByteArray(stream);
            } finally {
                if (stream != null) {
                    try {
                        stream.close();
                    } catch (Throwable ignore) {
                    }
                }
                try {
                    b.free();
                } catch (Throwable ignore) {
                }
            }
        } catch (SQLException e) {
            throw new ConverterException("Error converting Blob to byte[]", e);
        } catch (IOException e) {
            throw new ConverterException("Error converting Blob to byte[]", e);
        }
    }
    if (val instanceof byte[]) {
        return (byte[]) val;
    }
    throw new RuntimeException("could not convert " + val.getClass().getName() + " to byte[]");
}
Example 8
Project: ToxOtis-master  File: ErrorIterator.java View source code
@Override
public ErrorReport next() throws DbException {
    ErrorReport nextReport = null;
    try {
        VRI uriToSet = new VRI(baseUri).augment("error", rs.getString(1));
        nextReport = new ErrorReport(new VRI(baseUri).augment("error", rs.getString(1)));
        nextReport.setHttpStatus(rs.getInt(2));
        nextReport.setActor(rs.getString(3));
        nextReport.setMessage(rs.getString(4));
        nextReport.setDetails(rs.getString(5));
        nextReport.setErrorCode(rs.getString(6));
        String errorCause = rs.getString("errorCause");
        if (errorCause != null) {
            if (!retrieveStackTrace) {
                nextReport.setErrorCause(new ErrorReport(new VRI(baseUri).augment("error", errorCause)));
            } else {
                FindError stackTraceFinder = new FindError(baseUri);
                stackTraceFinder.setSearchById(errorCause);
                IDbIterator<ErrorReport> stackTraceIterator = stackTraceFinder.list();
                if (stackTraceIterator.hasNext()) {
                    nextReport.setErrorCause(stackTraceIterator.next());
                }
                stackTraceIterator.close();
                stackTraceFinder.close();
            }
        }
        Blob metaInfoBlob = rs.getBlob(8);
        if (metaInfoBlob != null) {
            MetaInfoDeblobber mid = new MetaInfoDeblobber(metaInfoBlob);
            MetaInfo mi = mid.toMetaInfo();
            nextReport.setMeta(mi);
            metaInfoBlob.free();
        }
    } catch (final SQLException ex) {
        final String msg = "Error reading result set on error reports";
        logger.warn(msg, ex);
        throw new DbException(msg, ex);
    }
    return nextReport;
}
Example 9
Project: eclipselink.runtime-master  File: CloudscapePlatform.java View source code
/**
     * seems compatible with informix
     */
protected Hashtable buildFieldTypes() {
    Hashtable fieldTypeMapping;
    fieldTypeMapping = new Hashtable();
    fieldTypeMapping.put(Boolean.class, new FieldTypeDefinition("SMALLINT default 0", false));
    fieldTypeMapping.put(Integer.class, new FieldTypeDefinition("INTEGER", false));
    fieldTypeMapping.put(Long.class, new FieldTypeDefinition("NUMERIC", 19));
    fieldTypeMapping.put(Float.class, new FieldTypeDefinition("FLOAT(16)", false));
    fieldTypeMapping.put(Double.class, new FieldTypeDefinition("FLOAT(32)", false));
    fieldTypeMapping.put(Short.class, new FieldTypeDefinition("SMALLINT", false));
    fieldTypeMapping.put(Byte.class, new FieldTypeDefinition("SMALLINT", false));
    fieldTypeMapping.put(java.math.BigInteger.class, new FieldTypeDefinition("DECIMAL", 32));
    fieldTypeMapping.put(java.math.BigDecimal.class, new FieldTypeDefinition("DECIMAL", 32).setLimits(32, -19, 19));
    fieldTypeMapping.put(Number.class, new FieldTypeDefinition("DECIMAL", 32).setLimits(32, -19, 19));
    fieldTypeMapping.put(String.class, new FieldTypeDefinition("VARCHAR", DEFAULT_VARCHAR_SIZE));
    fieldTypeMapping.put(Character.class, new FieldTypeDefinition("CHAR", 1));
    fieldTypeMapping.put(Byte[].class, new FieldTypeDefinition("BYTE", false));
    fieldTypeMapping.put(Character[].class, new FieldTypeDefinition("TEXT", false));
    fieldTypeMapping.put(byte[].class, new FieldTypeDefinition("BYTE", false));
    fieldTypeMapping.put(char[].class, new FieldTypeDefinition("TEXT", false));
    fieldTypeMapping.put(java.sql.Blob.class, new FieldTypeDefinition("BYTE", false));
    fieldTypeMapping.put(java.sql.Clob.class, new FieldTypeDefinition("TEXT", false));
    fieldTypeMapping.put(java.sql.Date.class, new FieldTypeDefinition("DATE", false));
    fieldTypeMapping.put(java.sql.Time.class, new FieldTypeDefinition("DATETIME HOUR TO SECOND", false));
    fieldTypeMapping.put(java.sql.Timestamp.class, new FieldTypeDefinition("DATETIME YEAR TO FRACTION(5)", false));
    return fieldTypeMapping;
}
Example 10
Project: teiid-designer-master  File: ObjectConverterUtil.java View source code
protected static byte[] convertBlobToByteArray(final java.sql.Blob data) throws TeiidExecutionException {
    try {
        // Open a stream to read the BLOB data
        InputStream l_blobStream = data.getBinaryStream();
        return convertToByteArray(l_blobStream);
    } catch (IOException ioe) {
        final Object[] params = new Object[] { data.getClass().getName() };
        throw new TeiidExecutionException(IStatus.ERROR, ioe);
    } catch (SQLException sqe) {
        final Object[] params = new Object[] { data.getClass().getName() };
        throw new TeiidExecutionException(IStatus.ERROR, sqe);
    }
}
Example 11
Project: teiid-master  File: ObjectConverterUtil.java View source code
protected static byte[] convertBlobToByteArray(final java.sql.Blob data) throws TeiidException {
    try {
        // Open a stream to read the BLOB data
        InputStream l_blobStream = data.getBinaryStream();
        return convertToByteArray(l_blobStream);
    } catch (IOException ioe) {
        final Object[] params = new Object[] { data.getClass().getName() };
        throw new TeiidException(CorePlugin.Event.TEIID10030, ioe, CorePlugin.Util.gs(CorePlugin.Event.TEIID10030, params));
    } catch (SQLException sqe) {
        final Object[] params = new Object[] { data.getClass().getName() };
        throw new TeiidException(CorePlugin.Event.TEIID10030, sqe, CorePlugin.Util.gs(CorePlugin.Event.TEIID10030, params));
    }
}
Example 12
Project: jentrata-msh-master  File: DataSourceQuery.java View source code
/**
     * Executes the query and stores the result as a list of DataSourceDVO or 
     * raw data list.
     * 
     * @throws DAOException if unable to execute the query.
     * @see hk.hku.cecid.piazza.commons.dao.ds.DataSourceProcess#doTransaction(DataSourceTransaction)
     */
protected void doTransaction(DataSourceTransaction tx) throws DAOException {
    ResultSet rs = null;
    PreparedStatement pStmt = null;
    try {
        if (sql == null) {
            throw new DAOException("SQL in query cannot be NULL");
        }
        pStmt = tx.getConnection().prepareStatement(sql);
        int noOfParas = getParameterCount(pStmt, sql);
        // check the input parameters for the SQL statement
        if (noOfParas > 0) {
            if (params == null || params.length != noOfParas) {
                throw new DAOException("Number of parameters specified do not match in the SQL");
            } else {
                for (int i = 0; i < noOfParas; i++) {
                    setParameter(pStmt, i + 1, params[i]);
                }
            }
        }
        // execute the query
        rs = pStmt.executeQuery();
        ResultSetMetaData rsmd = rs.getMetaData();
        int numberOfColumns = rsmd.getColumnCount();
        String[] columnNames = new String[numberOfColumns];
        for (int i = 0; i < columnNames.length; i++) {
            columnNames[i] = rsmd.getColumnName(i + 1);
        }
        // pack the data retrieved into a List of DataSourceDVO
        List result = new ArrayList();
        while (rs.next()) {
            if (isRawResult) {
                List data = new ArrayList();
                int cc = rsmd.getColumnCount();
                for (int i = 1; i <= cc; i++) {
                    Object value = rs.getObject(i);
                    data.add(value);
                }
                result.add(data);
            } else {
                Hashtable values = new Hashtable();
                for (int i = 0; i < columnNames.length; i++) {
                    Object value = rs.getObject(columnNames[i]);
                    String columnCodeName = getDAO().getColumnCodeName(columnNames[i]);
                    if (value != null && columnCodeName != null) {
                        if (value instanceof java.sql.Blob) {
                            java.sql.Blob blob = (java.sql.Blob) value;
                            byte[] b = new byte[8196];
                            int j = 0;
                            InputStream is = blob.getBinaryStream();
                            ByteArrayOutputStream baos = new ByteArrayOutputStream();
                            while ((j = is.read(b)) > 0) {
                                baos.write(b, 0, j);
                            }
                            values.put(columnCodeName, baos.toByteArray());
                        } else {
                            values.put(columnCodeName, value);
                        }
                    }
                }
                DataSourceDVO data = (DataSourceDVO) getDAO().createDVO();
                data.setData(values);
                result.add(data);
            }
        }
        setResult(result);
    } catch (Exception e) {
        throw new DAOException("Error in executing query: " + sql, e);
    } finally {
        if (rs != null) {
            try {
                rs.close();
            } catch (Exception ex) {
                throw new DAOException("Error in closing result set: ", ex);
            }
        }
        if (pStmt != null) {
            try {
                pStmt.close();
            } catch (Exception ex) {
                throw new DAOException("Error in closing prepared statement: ", ex);
            }
        }
    }
}
Example 13
Project: maven-h2o-master  File: DataSourceQuery.java View source code
/**
     * Executes the query and stores the result as a list of DataSourceDVO or 
     * raw data list.
     * 
     * @throws DAOException if unable to execute the query.
     * @see hk.hku.cecid.piazza.commons.dao.ds.DataSourceProcess#doTransaction(DataSourceTransaction)
     */
protected void doTransaction(DataSourceTransaction tx) throws DAOException {
    ResultSet rs = null;
    PreparedStatement pStmt = null;
    try {
        if (sql == null) {
            throw new DAOException("SQL in query cannot be NULL");
        }
        pStmt = tx.getConnection().prepareStatement(sql);
        int noOfParas = getParameterCount(pStmt, sql);
        // check the input parameters for the SQL statement
        if (noOfParas > 0) {
            if (params == null || params.length != noOfParas) {
                throw new DAOException("Number of parameters specified do not match in the SQL");
            } else {
                for (int i = 0; i < noOfParas; i++) {
                    setParameter(pStmt, i + 1, params[i]);
                }
            }
        }
        // execute the query
        rs = pStmt.executeQuery();
        ResultSetMetaData rsmd = rs.getMetaData();
        int numberOfColumns = rsmd.getColumnCount();
        String[] columnNames = new String[numberOfColumns];
        for (int i = 0; i < columnNames.length; i++) {
            columnNames[i] = rsmd.getColumnName(i + 1);
        }
        // pack the data retrieved into a List of DataSourceDVO
        List result = new ArrayList();
        while (rs.next()) {
            if (isRawResult) {
                List data = new ArrayList();
                int cc = rsmd.getColumnCount();
                for (int i = 1; i <= cc; i++) {
                    Object value = rs.getObject(i);
                    data.add(value);
                }
                result.add(data);
            } else {
                Hashtable values = new Hashtable();
                for (int i = 0; i < columnNames.length; i++) {
                    Object value = rs.getObject(columnNames[i]);
                    String columnCodeName = getDAO().getColumnCodeName(columnNames[i]);
                    if (value != null && columnCodeName != null) {
                        if (value instanceof java.sql.Blob) {
                            java.sql.Blob blob = (java.sql.Blob) value;
                            byte[] b = new byte[8196];
                            int j = 0;
                            InputStream is = blob.getBinaryStream();
                            ByteArrayOutputStream baos = new ByteArrayOutputStream();
                            while ((j = is.read(b)) > 0) {
                                baos.write(b, 0, j);
                            }
                            values.put(columnCodeName, baos.toByteArray());
                        } else {
                            values.put(columnCodeName, value);
                        }
                    }
                }
                DataSourceDVO data = (DataSourceDVO) getDAO().createDVO();
                data.setData(values);
                result.add(data);
            }
        }
        setResult(result);
    } catch (Exception e) {
        throw new DAOException("Error in executing query: " + sql, e);
    } finally {
        if (rs != null) {
            try {
                rs.close();
            } catch (Exception ex) {
                throw new DAOException("Error in closing result set: ", ex);
            }
        }
        if (pStmt != null) {
            try {
                pStmt.close();
            } catch (Exception ex) {
                throw new DAOException("Error in closing prepared statement: ", ex);
            }
        }
    }
}
Example 14
Project: Quartz-master  File: WebLogicDelegate.java View source code
//---------------------------------------------------------------------------
// protected methods that can be overridden by subclasses
//---------------------------------------------------------------------------
/**
     * <p>
     * This method should be overridden by any delegate subclasses that need
     * special handling for BLOBs. The default implementation uses standard
     * JDBC <code>java.sql.Blob</code> operations.
     * </p>
     * 
     * @param rs
     *          the result set, already queued to the correct row
     * @param colName
     *          the column name for the BLOB
     * @return the deserialized Object from the ResultSet BLOB
     * @throws ClassNotFoundException
     *           if a class found during deserialization cannot be found
     * @throws IOException
     *           if deserialization causes an error
     */
@Override
protected Object getObjectFromBlob(ResultSet rs, String colName) throws ClassNotFoundException, IOException, SQLException {
    Object obj = null;
    Blob blobLocator = rs.getBlob(colName);
    InputStream binaryInput = null;
    try {
        if (null != blobLocator && blobLocator.length() > 0) {
            binaryInput = blobLocator.getBinaryStream();
        }
    } catch (Exception ignore) {
    }
    if (null != binaryInput) {
        ObjectInputStream in = new ObjectInputStream(binaryInput);
        try {
            obj = in.readObject();
        } finally {
            in.close();
        }
    }
    return obj;
}
Example 15
Project: quartz-scheduler-master  File: WebLogicDelegate.java View source code
//---------------------------------------------------------------------------
// protected methods that can be overridden by subclasses
//---------------------------------------------------------------------------
/**
     * <p>
     * This method should be overridden by any delegate subclasses that need
     * special handling for BLOBs. The default implementation uses standard
     * JDBC <code>java.sql.Blob</code> operations.
     * </p>
     * 
     * @param rs
     *          the result set, already queued to the correct row
     * @param colName
     *          the column name for the BLOB
     * @return the deserialized Object from the ResultSet BLOB
     * @throws ClassNotFoundException
     *           if a class found during deserialization cannot be found
     * @throws IOException
     *           if deserialization causes an error
     */
@Override
protected Object getObjectFromBlob(ResultSet rs, String colName) throws ClassNotFoundException, IOException, SQLException {
    Object obj = null;
    Blob blobLocator = rs.getBlob(colName);
    InputStream binaryInput = null;
    try {
        if (null != blobLocator && blobLocator.length() > 0) {
            binaryInput = blobLocator.getBinaryStream();
        }
    } catch (Exception ignore) {
    }
    if (null != binaryInput) {
        ObjectInputStream in = new ObjectInputStream(binaryInput);
        try {
            obj = in.readObject();
        } finally {
            in.close();
        }
    }
    return obj;
}
Example 16
Project: siena-master  File: JdbcMappingUtils.java View source code
public static Object fromObject(Field field, Object value) {
    Class<?> type = field.getType();
    // in H2 database, mediumtext is mapped to CLOB
    if (Json.class.isAssignableFrom(type) && value != null && java.sql.Clob.class.isAssignableFrom(value.getClass())) {
        java.sql.Clob clob = (java.sql.Clob) value;
        try {
            return Json.load(new BufferedReader(clob.getCharacterStream()));
        } catch (SQLException e) {
            throw new SienaException(e);
        }
    }
    if (field.getAnnotation(Embedded.class) != null && value != null && java.sql.Clob.class.isAssignableFrom(value.getClass())) {
        java.sql.Clob clob = (java.sql.Clob) value;
        try {
            Json data = Json.load(new BufferedReader(clob.getCharacterStream()));
            return JsonSerializer.deserialize(field, data);
        } catch (SQLException e) {
            throw new SienaException(e);
        }
    }
    // issue https://github.com/mandubian/siena/issues/5
    if (value != null && java.sql.Clob.class.isAssignableFrom(value.getClass())) {
        java.sql.Clob clob = (java.sql.Clob) value;
        try {
            // @see http://osdir.com/ml/h2-database/2011-06/msg00170.html
            return clob.getSubString(1, (int) clob.length());
        } catch (SQLException e) {
            throw new SienaException(e);
        }
    }
    if (field.isAnnotationPresent(Polymorphic.class)) {
        try {
            if (java.sql.Blob.class.isAssignableFrom(value.getClass())) {
                java.sql.Blob blob = (java.sql.Blob) value;
                ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(blob.getBytes(0, (int) blob.length())));
                return in.readObject();
            } else {
                ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream((byte[]) value));
                return in.readObject();
            }
        } catch (IOException e) {
            throw new SienaException(e);
        } catch (ClassNotFoundException e) {
            throw new SienaException(e);
        } catch (SQLException e) {
            throw new SienaException(e);
        }
    }
    if (byte[].class == type && value != null && java.sql.Blob.class.isAssignableFrom(value.getClass())) {
        java.sql.Blob blob = (java.sql.Blob) value;
        try {
            // TODO what to do with a very long blob????
            return blob.getBytes(0, (int) blob.length());
        } catch (SQLException e) {
            throw new SienaException(e);
        }
    }
    if (BigDecimal.class == type) {
        DecimalPrecision ann = field.getAnnotation(DecimalPrecision.class);
        if (ann == null) {
            return (BigDecimal) value;
        } else {
            switch(ann.storageType()) {
                case DOUBLE:
                    return BigDecimal.valueOf((Double) value);
                case STRING:
                    return new BigDecimal((String) value);
                case NATIVE:
                    return (BigDecimal) value;
            }
        }
    }
    return Util.fromObject(field, value);
}
Example 17
Project: jetbrick-all-1x-master  File: CallableStatementGetter.java View source code
public static Object getValue(CallableStatement cs, int index, Class<?> requiredType) throws SQLException {
    Object value = null;
    boolean wasNullCheck = false;
    if (requiredType == null) {
        return cs.getObject(index);
    }
    requiredType = ClassUtils.primitiveToWrapper(requiredType);
    // Explicitly extract typed value, as far as possible.
    if (String.class.equals(requiredType)) {
        value = cs.getString(index);
    } else if (Integer.class.equals(requiredType)) {
        value = Integer.valueOf(cs.getInt(index));
        wasNullCheck = true;
    } else if (Double.class.equals(requiredType)) {
        value = new Double(cs.getDouble(index));
        wasNullCheck = true;
    } else if (Boolean.class.equals(requiredType)) {
        value = (cs.getBoolean(index) ? Boolean.TRUE : Boolean.FALSE);
        wasNullCheck = true;
    } else if (java.sql.Date.class.equals(requiredType)) {
        value = cs.getDate(index);
    } else if (java.sql.Time.class.equals(requiredType)) {
        value = cs.getTime(index);
    } else if (java.sql.Timestamp.class.equals(requiredType)) {
        value = cs.getTimestamp(index);
    } else if (java.util.Date.class.equals(requiredType)) {
        value = new java.util.Date(cs.getTimestamp(index).getTime());
    } else if (Byte.class.equals(requiredType)) {
        value = Byte.valueOf(cs.getByte(index));
        wasNullCheck = true;
    } else if (Short.class.equals(requiredType)) {
        value = Short.valueOf(cs.getShort(index));
        wasNullCheck = true;
    } else if (Long.class.equals(requiredType)) {
        value = Long.valueOf(cs.getLong(index));
        wasNullCheck = true;
    } else if (Float.class.equals(requiredType)) {
        value = new Float(cs.getFloat(index));
        wasNullCheck = true;
    } else if (Number.class.equals(requiredType)) {
        value = new Double(cs.getDouble(index));
        wasNullCheck = true;
    } else if (byte[].class.equals(requiredType)) {
        value = cs.getBytes(index);
    } else if (java.math.BigDecimal.class.equals(requiredType)) {
        value = cs.getBigDecimal(index);
    } else if (java.sql.Blob.class.equals(requiredType)) {
        value = cs.getBlob(index);
    } else if (java.sql.Clob.class.equals(requiredType)) {
        value = cs.getClob(index);
    } else if (java.net.URL.class.equals(requiredType)) {
        value = cs.getURL(index);
    } else {
        // Some unknown type desired -> rely on getObject.
        value = cs.getObject(index);
    }
    // JDBC driver returns as primitives).
    if (wasNullCheck && value != null && cs.wasNull()) {
        value = null;
    }
    return value;
}
Example 18
Project: midao-master  File: BaseTypeHandler.java View source code
/**
     * {@inheritDoc}
     */
public void afterExecute(Statement stmt, QueryParameters processedInput, QueryParameters params) throws SQLException {
    Object value = null;
    Object convertedValue = null;
    Connection conn = stmt.getConnection();
    for (String parameterName : params.keySet()) {
        value = params.getValue(parameterName);
        convertedValue = processedInput.getValue(parameterName);
        try {
            if (params.getType(parameterName) == MjdbcTypes.ARRAY) {
                if (value instanceof Object[] || value instanceof Collection) {
                    if (convertedValue != null && MappingUtils.objectImplements(convertedValue, "java.sql.Array") == true) {
                        MappingUtils.invokeFunction(convertedValue, "free", new Class[] {}, new Object[] {});
                    }
                }
            } else if (params.getType(parameterName) == MjdbcTypes.BLOB) {
                if (value instanceof String || value instanceof InputStream || value instanceof byte[]) {
                    if (convertedValue != null && MappingUtils.objectImplements(convertedValue, "java.sql.Blob") == true) {
                        MappingUtils.invokeFunction(convertedValue, "free", new Class[] {}, new Object[] {});
                    }
                }
            } else if (params.getType(parameterName) == MjdbcTypes.CLOB) {
                if (value instanceof String || value instanceof InputStream || value instanceof byte[]) {
                    if (convertedValue != null && MappingUtils.objectImplements(convertedValue, "java.sql.Clob") == true) {
                        MappingUtils.invokeFunction(convertedValue, "free", new Class[] {}, new Object[] {});
                    }
                }
            } else if (params.getType(parameterName) == MjdbcTypes.SQLXML) {
                if (value instanceof String || value instanceof InputStream || value instanceof byte[]) {
                    if (convertedValue != null && MappingUtils.objectImplements(convertedValue, "java.sql.SQLXML") == true) {
                        MappingUtils.invokeFunction(convertedValue, "free", new Class[] {}, new Object[] {});
                    }
                }
            }
        } catch (MjdbcException ex) {
            logger.warning("Failed to close/free resource: " + parameterName + ". Might lead to resource leak!");
        }
    }
}
Example 19
Project: quartz-1.8.3-optivo-master  File: WebLogicDelegate.java View source code
//---------------------------------------------------------------------------
// protected methods that can be overridden by subclasses
//---------------------------------------------------------------------------
/**
     * <p>
     * This method should be overridden by any delegate subclasses that need
     * special handling for BLOBs. The default implementation uses standard
     * JDBC <code>java.sql.Blob</code> operations.
     * </p>
     * 
     * @param rs
     *          the result set, already queued to the correct row
     * @param colName
     *          the column name for the BLOB
     * @return the deserialized Object from the ResultSet BLOB
     * @throws ClassNotFoundException
     *           if a class found during deserialization cannot be found
     * @throws IOException
     *           if deserialization causes an error
     */
protected Object getObjectFromBlob(ResultSet rs, String colName) throws ClassNotFoundException, IOException, SQLException {
    Object obj = null;
    Blob blobLocator = rs.getBlob(colName);
    InputStream binaryInput = null;
    try {
        if (null != blobLocator && blobLocator.length() > 0) {
            binaryInput = blobLocator.getBinaryStream();
        }
    } catch (Exception ignore) {
    }
    if (null != binaryInput) {
        ObjectInputStream in = new ObjectInputStream(binaryInput);
        try {
            obj = in.readObject();
        } finally {
            in.close();
        }
    }
    return obj;
}
Example 20
Project: cayenne-master  File: OracleByteArrayType.java View source code
@Override
public void setJdbcObject(PreparedStatement st, byte[] val, int pos, int type, int scale) throws Exception {
    if (type == Types.BLOB) {
        if (isUsingBlobs()) {
            Blob blob = st.getConnection().createBlob();
            blob.setBytes(1, val);
            st.setBlob(pos, blob);
        } else {
            st.setBytes(pos, val);
        }
    } else {
        if (scale != -1) {
            st.setObject(pos, val, type, scale);
        } else {
            st.setObject(pos, val, type);
        }
    }
}
Example 21
Project: com.revolsys.open-master  File: PostgreSQLJdbcBlobFieldDefinition.java View source code
@Override
public int setPreparedStatementValue(final PreparedStatement statement, final int parameterIndex, final Object value) throws SQLException {
    if (value == null) {
        final int sqlType = getSqlType();
        statement.setNull(parameterIndex, sqlType);
    } else {
        Blob blob;
        if (value instanceof Blob) {
            blob = (Blob) value;
            statement.setBlob(parameterIndex, blob);
        } else {
            InputStream in;
            if (value instanceof InputStream) {
                in = (InputStream) value;
            } else if (value instanceof byte[]) {
                final byte[] bytes = (byte[]) value;
                in = new ByteArrayInputStream(bytes);
            } else if (value instanceof CharSequence) {
                final String string = ((CharSequence) value).toString();
                final byte[] bytes = string.getBytes(StandardCharsets.UTF_8);
                in = new ByteArrayInputStream(bytes);
            } else {
                try {
                    final Resource resource = Resource.getResource(value);
                    in = resource.newBufferedInputStream();
                } catch (final IllegalArgumentException e) {
                    throw new IllegalArgumentException(value.getClass() + " not valid for a blob column");
                }
            }
            try {
                final PGConnection pgConnection = (PGConnection) ((DelegatingConnection<?>) statement.getConnection()).getInnermostDelegate();
                final LargeObjectManager lobManager = pgConnection.getLargeObjectAPI();
                final long lobId = lobManager.createLO(LargeObjectManager.READ | LargeObjectManager.WRITE);
                final LargeObject lob = lobManager.open(lobId, LargeObjectManager.WRITE);
                try {
                    final byte buffer[] = new byte[2048];
                    int readCount = 0;
                    while ((readCount = in.read(buffer, 0, 2048)) > 0) {
                        lob.write(buffer, 0, readCount);
                    }
                } finally {
                    lob.close();
                }
                statement.setLong(parameterIndex, lobId);
            } catch (final IOException e) {
                Exceptions.throwUncheckedException(e);
            }
        }
    }
    return parameterIndex + 1;
}
Example 22
Project: ef-orm-master  File: BlobFileMapping.java View source code
public Object jdbcGet(IResultSet rs, int n) throws SQLException {
    Object obj = rs.getObject(n);
    if (obj == null)
        return null;
    if (obj.getClass().isArray()) {
        try {
            File file = File.createTempFile("tmp", ".io");
            IOUtils.saveAsFile(file, (byte[]) obj);
            return file;
        } catch (IOException e) {
            throw new SQLException("Error at saving Blob to file", e);
        }
    }
    Blob blob = (Blob) obj;
    InputStream in = blob.getBinaryStream();
    try {
        return IOUtils.saveAsTempFile(in);
    } catch (IOException e) {
        throw new SQLException("Error at saving Blob to file", e);
    }
}
Example 23
Project: esper-master  File: TestSQLTypeMapUtil.java View source code
public void testMapping() {
    Map<Integer, Class> testData = new HashMap<Integer, Class>();
    testData.put(Types.CHAR, String.class);
    testData.put(Types.VARCHAR, String.class);
    testData.put(Types.LONGVARCHAR, String.class);
    testData.put(Types.NUMERIC, BigDecimal.class);
    testData.put(Types.DECIMAL, BigDecimal.class);
    testData.put(Types.BIT, Boolean.class);
    testData.put(Types.BOOLEAN, Boolean.class);
    testData.put(Types.TINYINT, Byte.class);
    testData.put(Types.SMALLINT, Short.class);
    testData.put(Types.INTEGER, Integer.class);
    testData.put(Types.BIGINT, Long.class);
    testData.put(Types.REAL, Float.class);
    testData.put(Types.FLOAT, Double.class);
    testData.put(Types.DOUBLE, Double.class);
    testData.put(Types.BINARY, byte[].class);
    testData.put(Types.VARBINARY, byte[].class);
    testData.put(Types.LONGVARBINARY, byte[].class);
    testData.put(Types.DATE, java.sql.Date.class);
    testData.put(Types.TIMESTAMP, java.sql.Timestamp.class);
    testData.put(Types.TIME, java.sql.Time.class);
    testData.put(Types.CLOB, java.sql.Clob.class);
    testData.put(Types.BLOB, java.sql.Blob.class);
    testData.put(Types.ARRAY, java.sql.Array.class);
    testData.put(Types.STRUCT, java.sql.Struct.class);
    testData.put(Types.REF, java.sql.Ref.class);
    testData.put(Types.DATALINK, java.net.URL.class);
    for (int type : testData.keySet()) {
        Class result = SQLTypeMapUtil.sqlTypeToClass(type, null, ClassForNameProviderDefault.INSTANCE);
        log.debug(".testMapping Mapping " + type + " to " + result.getSimpleName());
        assertEquals(testData.get(type), result);
    }
    assertEquals(String.class, SQLTypeMapUtil.sqlTypeToClass(Types.JAVA_OBJECT, "java.lang.String", ClassForNameProviderDefault.INSTANCE));
    assertEquals(String.class, SQLTypeMapUtil.sqlTypeToClass(Types.DISTINCT, "java.lang.String", ClassForNameProviderDefault.INSTANCE));
}
Example 24
Project: geotools-2.7.x-master  File: LobConverterFactory.java View source code
public <T> T convert(Object source, Class<T> target) throws Exception {
    if (source instanceof Blob && byte[].class.isAssignableFrom(target)) {
        Blob blob = (Blob) source;
        InputStream blobIS = blob.getBinaryStream();
        byte[] blobBA = new byte[blobIS.available()];
        blobIS.read(blobBA);
        blobIS.close();
        return (T) blobBA;
    }
    return null;
}
Example 25
Project: geotools-old-master  File: LobConverterFactory.java View source code
public <T> T convert(Object source, Class<T> target) throws Exception {
    if (source instanceof Blob && byte[].class.isAssignableFrom(target)) {
        Blob blob = (Blob) source;
        InputStream blobIS = blob.getBinaryStream();
        byte[] blobBA = new byte[blobIS.available()];
        blobIS.read(blobBA);
        blobIS.close();
        return (T) blobBA;
    }
    return null;
}
Example 26
Project: hbase-dsl-master  File: BlobConverter.java View source code
@Override
public byte[] toBytes(Blob t) {
    InputStream binaryStream;
    try {
        binaryStream = t.getBinaryStream();
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream((int) t.length());
        byte[] buffer = new byte[1024];
        int num = -1;
        while ((num = binaryStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, num);
        }
        binaryStream.close();
        return outputStream.toByteArray();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
Example 27
Project: hibernate-orm-master  File: SqlServer2008GeometryTypeDescriptor.java View source code
private Geometry toGeometry(Object obj) {
    byte[] raw = null;
    if (obj == null) {
        return null;
    }
    if ((obj instanceof byte[])) {
        raw = (byte[]) obj;
    } else if (obj instanceof Blob) {
        raw = toByteArray((Blob) obj);
    } else {
        throw new IllegalArgumentException("Expected byte array or BLOB");
    }
    return Decoders.decode(raw);
}
Example 28
Project: nd4j-master  File: MysqlLoaderTest.java View source code
//simple litmus test, unfortunately relies on an external database
@Test
@Ignore
public void testMysqlLoader() throws Exception {
    ComboPooledDataSource ds = new ComboPooledDataSource();
    ds.setJdbcUrl("jdbc:mysql://localhost:3306/nd4j?user=nd4j&password=nd4j");
    MysqlLoader loader = new MysqlLoader(ds, "jdbc:mysql://localhost:3306/nd4j?user=nd4j&password=nd4j", "ndarrays", "array");
    loader.delete("1");
    INDArray load = loader.load(loader.loadForID("1"));
    if (load != null) {
        loader.delete("1");
    }
    loader.save(Nd4j.create(new float[] { 1, 2, 3 }), "1");
    Blob b = loader.loadForID("1");
    INDArray loaded = loader.load(b);
    assertEquals((Nd4j.create(new float[] { 1, 2, 3 })), loaded);
}
Example 29
Project: olingo-odata2-master  File: OnDBWriteContent.java View source code
@Override
public Blob getJPABlob(final byte[] binaryData) throws ODataJPARuntimeException {
    try {
        return new JDBCBlob(binaryData);
    } catch (SerialException e) {
        ODataJPARuntimeException.throwException(ODataJPARuntimeException.INNER_EXCEPTION, e);
    } catch (SQLException e) {
        ODataJPARuntimeException.throwException(ODataJPARuntimeException.INNER_EXCEPTION, e);
    }
    return null;
}
Example 30
Project: railo-master  File: OracleBlob.java View source code
public static Blob createBlob(Connection conn, byte[] barr, Blob defaultValue) {
    try {
        Class clazz = ClassUtil.loadClass("oracle.sql.BLOB");
        // BLOB.DURATION_SESSION
        if (duration == null)
            duration = Caster.toInteger(clazz.getField("DURATION_SESSION").getInt(null));
        // BLOB.MODE_READWRITE
        if (mode == null)
            mode = Caster.toInteger(clazz.getField("MODE_READWRITE").getInt(null));
        //BLOB blob = BLOB.createTemporary(conn, false, BLOB.DURATION_SESSION);
        if (createTemporary == null || createTemporary.getDeclaringClass() != clazz)
            createTemporary = clazz.getMethod("createTemporary", new Class[] { Connection.class, boolean.class, int.class });
        Object blob = createTemporary.invoke(null, new Object[] { conn, Boolean.FALSE, duration });
        //blob.open(BLOB.MODE_READWRITE);
        if (open == null || open.getDeclaringClass() != clazz)
            open = clazz.getMethod("open", new Class[] { int.class });
        open.invoke(blob, new Object[] { mode });
        //blob.setBytes(1,barr);
        if (setBytes == null || setBytes.getDeclaringClass() != clazz)
            setBytes = clazz.getMethod("setBytes", new Class[] { long.class, byte[].class });
        setBytes.invoke(blob, new Object[] { Long.valueOf(1), barr });
        return (Blob) blob;
    } catch (Throwable t) {
    }
    return defaultValue;
}
Example 31
Project: speedment-master  File: BlobToByteArrayMapper.java View source code
@Override
public byte[] toJavaType(Column column, Class<?> entityType, Blob value) {
    if (value == null) {
        return null;
    } else
        try {
            if (value.length() < Integer.MAX_VALUE) {
                return value.getBytes(1, (int) value.length());
            } else {
                throw new SpeedmentTypeMapperException("The provided Clob contains too many characters >" + Integer.MAX_VALUE);
            }
        } catch (final SQLException sqle) {
            throw new SpeedmentTypeMapperException("Unable to convert Blob to byte[].", sqle);
        }
}
Example 32
Project: symmetric-ds-master  File: PostgresLobHandler.java View source code
public byte[] getBlobAsBytes(ResultSet rs, int columnIndex, int jdbcTypeCode, String jdbcTypeName) throws SQLException {
    if (PostgreSqlDatabasePlatform.isBlobStoredByReference(jdbcTypeName)) {
        Blob blob = rs.getBlob(columnIndex);
        if (blob != null) {
            return blob.getBytes(1, (int) blob.length());
        } else {
            return null;
        }
    } else {
        return getDefaultHandler().getBlobAsBytes(rs, columnIndex);
    }
}
Example 33
Project: tomee-master  File: PatchedStdJDBCDelegate.java View source code
@Override
protected Object getObjectFromBlob(final ResultSet rs, final String colName) throws ClassNotFoundException, IOException, SQLException {
    Object obj = null;
    final Blob blobLocator = rs.getBlob(colName);
    if (blobLocator != null && blobLocator.length() != 0) {
        final InputStream binaryInput = blobLocator.getBinaryStream();
        if (null != binaryInput) {
            if (!(binaryInput instanceof ByteArrayInputStream) || ((ByteArrayInputStream) binaryInput).available() != 0) {
                final ObjectInputStream in = new QuartzObjectInputStream(binaryInput, classLoadHelper);
                try {
                    obj = in.readObject();
                } finally {
                    in.close();
                }
            }
        }
    }
    return obj;
}
Example 34
Project: Zong-master  File: AudioAction.java View source code
@Override
public boolean performTry(Request request, Webserver server, HttpServletResponse response) throws SQLException, IOException {
    AudioRequest audioRequest = getAs(AudioRequest.class, request);
    Connection db = server.getDBConnection();
    //get ID of document
    PreparedStatement stmtID = stmt(db, "SELECT id FROM docs WHERE public_id = ?", audioRequest.id);
    ResultSet resID = stmtID.executeQuery();
    if (!resID.next()) {
        stmtID.close();
        return false;
    }
    int docID = resID.getInt(1);
    stmtID.close();
    //deliver audio data
    PreparedStatement stmtAudio = stmt(db, "SELECT audio FROM audio WHERE doc_id = ?" + " AND format = ?", docID, audioRequest.format);
    ResultSet resAudio = stmtAudio.executeQuery();
    if (!resAudio.next()) {
        stmtAudio.close();
        return false;
    }
    Blob blob = resAudio.getBlob(1);
    byte[] imageData = blob.getBytes(1, (int) blob.length());
    stmtAudio.close();
    //header
    response.setHeader("Content-Type", (audioRequest.format.equals("OGG") ? "application/ogg" : "audio/mpeg"));
    response.setHeader("Content-Disposition", "attachment; filename=\"" + audioRequest.id + (audioRequest.format.equals("OGG") ? ".ogg" : ".mp3") + "\"");
    //data
    response.getOutputStream().write(imageData);
    //update access time
    PreparedStatement stmtTime = stmt(db, "UPDATE docs SET last_access = ? WHERE id = ?", unixTime(), docID);
    stmtTime.executeUpdate();
    stmtTime.close();
    return true;
}
Example 35
Project: aerogear-unifiedpush-server-master  File: CertificateBlobToBase64.java View source code
@Override
public SqlStatement[] generateStatements(Database database) throws CustomChangeException {
    List<SqlStatement> statements = new ArrayList<>();
    Connection conn = ((JdbcConnection) (database.getConnection())).getWrappedConnection();
    try {
        conn.setAutoCommit(false);
        ResultSet resultSet = conn.createStatement().executeQuery("SELECT id, certificate from ios_variant");
        while (resultSet.next()) {
            String id = resultSet.getString("id");
            Blob blob = resultSet.getBlob("certificate");
            InputStream certificate = blob.getBinaryStream();
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            int bytesRead = -1;
            byte[] buffer = new byte[1024];
            while ((bytesRead = certificate.read(buffer)) != -1) {
                stream.write(buffer, 0, bytesRead);
            }
            final String certificateData = Base64.getEncoder().encodeToString(stream.toByteArray());
            UpdateStatement updateStatement = new UpdateStatement(null, null, "ios_variant").addNewColumnValue("cert_data", certificateData).setWhereClause("id='" + id + "'");
            statements.add(updateStatement);
        }
        conn.commit();
        if (!statements.isEmpty()) {
            confirmationMessage = "updated certificate data successfully";
        }
        return statements.toArray(new SqlStatement[statements.size()]);
    } catch (Exception e) {
        throw new CustomChangeException("Failed to migrate certificate data");
    }
}
Example 36
Project: aliada-tool-master  File: ImageAction.java View source code
/**
     * Read the organisation logo from DB.
     * @return byte[]
     * @see
     * @since 1.0
     */
public byte[] getCustomImageInBytes() {
    String userName = (String) ServletActionContext.getRequest().getSession().getAttribute("logedUser");
    Connection connection;
    byte[] blobAsBytes = null;
    try {
        connection = new DBConnectionManager().getConnection();
        Statement statement = connection.createStatement();
        ResultSet rs = statement.executeQuery("SELECT org_logo FROM aliada.organisation o INNER JOIN aliada.user u ON o.organisationId = u.organisationId " + "WHERE u.user_name='" + userName + "';");
        if (rs.next() && rs.getBlob("org_logo") != null) {
            Blob logo = rs.getBlob("org_logo");
            int blobLength = (int) logo.length();
            blobAsBytes = logo.getBytes(1, blobLength);
            //release the blob and free up memory. (since JDBC 4.0)
            logo.free();
        }
        statement.close();
        connection.close();
    } catch (SQLException e) {
        logger.error(MessageCatalog._00011_SQL_EXCEPTION, e);
    }
    return blobAsBytes;
}
Example 37
Project: beanlib-master  File: BlobUtils.java View source code
public byte[] toByteArray(Blob fromBlob, int bufferSize) {
    if (fromBlob == null)
        return ArrayUtils.EMPTY_BYTE_ARRAY;
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {
        return toByteArrayImpl(fromBlob, baos, bufferSize);
    } catch (SQLException e) {
        log.error("", e);
        throw new BeanlibException(e);
    } catch (IOException e) {
        log.error("", e);
        throw new BeanlibException(e);
    } finally {
        if (baos != null) {
            try {
                baos.close();
            } catch (IOException ex) {
                log.warn("", ex);
            }
        }
    }
}
Example 38
Project: clinic-softacad-master  File: AbstractDescriptorTest.java View source code
@Test
public void testMutabilityPlan() {
    assertTrue(shouldBeMutable() == typeDescriptor.getMutabilityPlan().isMutable());
    if (Clob.class.isInstance(testData.copyOfOriginalValue) || Blob.class.isInstance(testData.copyOfOriginalValue)) {
        return;
    }
    T copy = typeDescriptor.getMutabilityPlan().deepCopy(testData.copyOfOriginalValue);
    assertTrue(typeDescriptor.areEqual(copy, testData.copyOfOriginalValue));
    if (!shouldBeMutable()) {
        assertTrue(copy == testData.copyOfOriginalValue);
    }
    // ensure the symmetry of assemble/disassebly
    Serializable cached = typeDescriptor.getMutabilityPlan().disassemble(testData.copyOfOriginalValue);
    if (!shouldBeMutable()) {
        assertTrue(cached == testData.copyOfOriginalValue);
    }
    T reassembled = typeDescriptor.getMutabilityPlan().assemble(cached);
    assertTrue(typeDescriptor.areEqual(testData.originalValue, reassembled));
}
Example 39
Project: com.idega.core-master  File: InformixSchemaAdapter.java View source code
public String getSQLType(String javaClassName, int maxlength) {
    if (javaClassName.equals("java.lang.Integer")) {
        return "INTEGER";
    }
    if (javaClassName.equals("java.lang.String")) {
        if (maxlength == EntityAttribute.UNLIMITED_LENGTH) {
            return "TEXT";
        }
        if (maxlength < 0) {
            return "VARCHAR(255)";
        }
        if (maxlength <= 255) {
            return "VARCHAR(" + maxlength + ")";
        }
        if (maxlength <= 2000) {
            return "LVARCHAR";
        }
        return "TEXT";
    }
    if (javaClassName.equals("java.lang.Boolean")) {
        return "CHAR(1)";
    }
    if (javaClassName.equals("java.lang.Float")) {
        return "FLOAT";
    }
    if (javaClassName.equals("java.lang.Double")) {
        return "FLOAT(15)";
    }
    if (javaClassName.equals("java.sql.Timestamp")) {
        return "DATETIME YEAR TO FRACTION";
    }
    if (javaClassName.equals("java.sql.Date") || javaClassName.equals("java.util.Date")) {
        return "DATE";
    }
    if (javaClassName.equals("java.sql.Blob")) {
        return "BYTE";
    }
    if (javaClassName.equals("java.sql.Time")) {
        return "DATETIME HOUR TO FRACTION";
    }
    if (javaClassName.equals("com.idega.util.Gender")) {
        return "VARCHAR(1)";
    }
    if (javaClassName.equals("com.idega.data.BlobWrapper")) {
        return "BYTE";
    }
    return "";
}
Example 40
Project: druid-master  File: ClobTest.java View source code
public void test_clob() throws Exception {
    DruidDataSource dataSource = new DruidDataSource();
    dataSource.setFilters("stat");
    dataSource.setUrl("jdbc:mock:");
    Connection conn = dataSource.getConnection();
    Statement stmt = conn.createStatement();
    ResultSet rs = stmt.executeQuery("SELECT NULL");
    Assert.assertTrue(rs.next());
    {
        Clob x = rs.getClob(1);
        Assert.assertNull(x);
    }
    {
        NClob x = rs.getNClob(1);
        Assert.assertNull(x);
    }
    {
        Blob x = rs.getBlob(1);
        Assert.assertNull(x);
    }
    {
        SQLXML x = rs.getSQLXML(1);
        Assert.assertNull(x);
    }
    {
        String x = rs.getString(1);
        Assert.assertNull(x);
    }
    Assert.assertNull(rs.getRowId(1));
    Assert.assertNull(rs.getBigDecimal(1));
    Assert.assertNull(rs.getObject(1));
    rs.close();
    stmt.close();
    conn.close();
    dataSource.close();
}
Example 41
Project: FlowerPaper-master  File: DocumentController.java View source code
@RequestMapping(value = "/save", method = RequestMethod.POST)
public String save(@Valid @ModelAttribute("document") Document document, BindingResult result, @RequestParam("file") MultipartFile file) {
    if (result.hasErrors()) {
        return "doc/documents.tiles";
    }
    System.out.println("Name:" + document.getName());
    System.out.println("Desc:" + document.getDescription());
    System.out.println("File:" + file.getName());
    System.out.println("ContentType:" + file.getContentType());
    try {
        Blob blob = Hibernate.createBlob(file.getInputStream());
        document.setFilename(file.getOriginalFilename());
        document.setContent(blob);
        document.setContentType(file.getContentType());
    } catch (IOException e) {
        e.printStackTrace();
    }
    try {
        documentService.save(document);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return "redirect:/doc/index";
}
Example 42
Project: geotools-master  File: LobConverterFactory.java View source code
public <T> T convert(Object source, Class<T> target) throws Exception {
    if (source instanceof Blob && byte[].class.isAssignableFrom(target)) {
        Blob blob = (Blob) source;
        InputStream blobIS = blob.getBinaryStream();
        byte[] blobBA = new byte[blobIS.available()];
        blobIS.read(blobBA);
        blobIS.close();
        return (T) blobBA;
    }
    return null;
}
Example 43
Project: geotools_trunk-master  File: LobConverterFactory.java View source code
public <T> T convert(Object source, Class<T> target) throws Exception {
    if (source instanceof Blob && byte[].class.isAssignableFrom(target)) {
        Blob blob = (Blob) source;
        InputStream blobIS = blob.getBinaryStream();
        byte[] blobBA = new byte[blobIS.available()];
        blobIS.read(blobBA);
        blobIS.close();
        return (T) blobBA;
    }
    return null;
}
Example 44
Project: hibernate-core-3.6.x-mod-master  File: AbstractDescriptorTest.java View source code
public void testMutabilityPlan() {
    assertTrue(shouldBeMutable() == typeDescriptor.getMutabilityPlan().isMutable());
    if (Clob.class.isInstance(testData.copyOfOriginalValue) || Blob.class.isInstance(testData.copyOfOriginalValue)) {
        return;
    }
    T copy = typeDescriptor.getMutabilityPlan().deepCopy(testData.copyOfOriginalValue);
    assertTrue(typeDescriptor.areEqual(copy, testData.copyOfOriginalValue));
    if (!shouldBeMutable()) {
        assertTrue(copy == testData.copyOfOriginalValue);
    }
    // ensure the symmetry of assemble/disassebly
    Serializable cached = typeDescriptor.getMutabilityPlan().disassemble(testData.copyOfOriginalValue);
    if (!shouldBeMutable()) {
        assertTrue(cached == testData.copyOfOriginalValue);
    }
    T reassembled = typeDescriptor.getMutabilityPlan().assemble(cached);
    assertTrue(typeDescriptor.areEqual(testData.originalValue, reassembled));
}
Example 45
Project: hibernate-core-ogm-master  File: AbstractDescriptorTest.java View source code
@Test
public void testMutabilityPlan() {
    assertTrue(shouldBeMutable() == typeDescriptor.getMutabilityPlan().isMutable());
    if (Clob.class.isInstance(testData.copyOfOriginalValue) || Blob.class.isInstance(testData.copyOfOriginalValue)) {
        return;
    }
    T copy = typeDescriptor.getMutabilityPlan().deepCopy(testData.copyOfOriginalValue);
    assertTrue(typeDescriptor.areEqual(copy, testData.copyOfOriginalValue));
    if (!shouldBeMutable()) {
        assertTrue(copy == testData.copyOfOriginalValue);
    }
    // ensure the symmetry of assemble/disassebly
    Serializable cached = typeDescriptor.getMutabilityPlan().disassemble(testData.copyOfOriginalValue);
    if (!shouldBeMutable()) {
        assertTrue(cached == testData.copyOfOriginalValue);
    }
    T reassembled = typeDescriptor.getMutabilityPlan().assemble(cached);
    assertTrue(typeDescriptor.areEqual(testData.originalValue, reassembled));
}
Example 46
Project: hivedb-blobject-master  File: BlobSetter.java View source code
@SuppressWarnings("unchecked")
public void set(Object target, Object value, SessionFactoryImplementor sessionFactory) throws HibernateException {
    InputStream stream;
    try {
        stream = ((Blob) value).getBinaryStream();
        log.debug(stream);
    } catch (SQLException e) {
        throw new HibernateException(e);
    }
    Object defrosted = XmlXStreamSerializationProvider.instance().getSerializer(target.getClass()).deserialize(stream);
    Class<?> clazz = ReflectionTools.whichIsImplemented((Class) defrosted.getClass(), (Collection<Class>) XmlXStreamSerializationProvider.instance().getSerializableInterfaces());
    if (clazz == null)
        throw new RuntimeException(String.format("Could not find a serializable interface matching defrosted class %s", defrosted.getClass()));
    for (Method get : ReflectionTools.getGetters(clazz)) {
        if (get.getDeclaringClass().equals(Object.class) || AnnotationHelper.getAnnotationDeeply(clazz, ReflectionTools.getPropertyNameOfAccessor(get), SerializerIgnore.class) != null)
            continue;
        Object propertyValue;
        try {
            propertyValue = get.invoke(defrosted, new Object[] {});
        } catch (IllegalArgumentException e) {
            throw new HibernateException(e);
        } catch (IllegalAccessException e) {
            throw new HibernateException(e);
        } catch (InvocationTargetException e) {
            throw new HibernateException(e);
        }
        ReflectionTools.invokeSetter(target, BeanUtils.findPropertyForMethod(get).getName(), propertyValue);
    }
}
Example 47
Project: iciql-master  File: JavaSerializationTypeAdapter.java View source code
@SuppressWarnings("unchecked")
@Override
public final T deserialize(Object value) {
    InputStream is = null;
    if (value instanceof Blob) {
        Blob blob = (Blob) value;
        try {
            is = blob.getBinaryStream();
        } catch (SQLException e) {
            throw new IciqlException(e);
        }
    } else if (value instanceof byte[]) {
        byte[] bytes = (byte[]) value;
        is = new ByteArrayInputStream(bytes);
    }
    try {
        T object = (T) new ObjectInputStream(is).readObject();
        return object;
    } catch (Exception e) {
        throw new IciqlException(e);
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                throw new IciqlException(e);
            }
        }
    }
}
Example 48
Project: jdbclint-master  File: BlobProxy.java View source code
@Override
public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable {
    String name = method.getName();
    if (name.equals("free")) {
        boolean previouslyFreed = freed.getAndSet(true);
        if (config.isEnabled(Check.BLOB_DOUBLE_FREE) && previouslyFreed) {
            Utils.fail(config, exception, "Blob already freed");
        }
    }
    Object returnVal;
    try {
        returnVal = method.invoke(blob, args);
    } catch (InvocationTargetException ite) {
        throw ite.getTargetException();
    }
    return returnVal;
}
Example 49
Project: JSqlIde-master  File: ClobEditorPanel.java View source code
/**
	 * Tries to read the blob as a string.
	 * @param blob The blob to set.
	 */
public void setBlob(Blob blob) {
    edtEditor.setFont(ProgramConfig.getInstance().getResultSetFont());
    this.blob = blob;
    final Blob ourBlob = blob;
    edtEditor.setText("Reading CLOB. Please wait...");
    Thread clobReader = new Thread() {

        public void run() {
            String result = "";
            try {
                result = readBlob(ourBlob);
            } catch (Exception ex) {
                result = ex.toString();
            } finally {
                final String text = result;
                SwingUtilities.invokeLater(new Runnable() {

                    public void run() {
                        edtEditor.setText(text);
                        edtEditor.setSelectionStart(0);
                        edtEditor.setSelectionEnd(0);
                    }
                });
            }
        }
    };
    clobReader.start();
}
Example 50
Project: killbill-meter-plugin-master  File: TimelineChunkMapper.java View source code
@Override
public TimelineChunk map(final int index, final ResultSet rs, final StatementContext ctx) throws SQLException {
    final int chunkId = rs.getInt("record_id");
    final int sourceId = rs.getInt("source_record_id");
    final int metricId = rs.getInt("metric_record_id");
    final int sampleCount = rs.getInt("sample_count");
    final DateTime startTime = DateTimeUtils.dateTimeFromUnixSeconds(rs.getInt("start_time"));
    final DateTime endTime = DateTimeUtils.dateTimeFromUnixSeconds(rs.getInt("end_time"));
    final int aggregationLevel = rs.getInt("aggregation_level");
    final boolean notValid = rs.getInt("not_valid") == 0 ? false : true;
    final boolean dontAggregate = rs.getInt("dont_aggregate") == 0 ? false : true;
    byte[] samplesAndTimes = rs.getBytes("in_row_samples");
    if (rs.wasNull()) {
        final Blob blobSamples = rs.getBlob("blob_samples");
        if (rs.wasNull()) {
            samplesAndTimes = new byte[4];
        } else {
            samplesAndTimes = blobSamples.getBytes(1, (int) blobSamples.length());
        }
    }
    final TimeBytesAndSampleBytes bytesPair = TimesAndSamplesCoder.getTimesBytesAndSampleBytes(samplesAndTimes);
    return new TimelineChunk(chunkId, sourceId, metricId, startTime, endTime, bytesPair, sampleCount, aggregationLevel, notValid, dontAggregate);
}
Example 51
Project: Lucee-master  File: OracleBlob.java View source code
public static Blob createBlob(Connection conn, byte[] barr, Blob defaultValue) {
    try {
        Class clazz = ClassUtil.loadClass("oracle.sql.BLOB");
        // BLOB.DURATION_SESSION
        if (duration == null)
            duration = Caster.toInteger(clazz.getField("DURATION_SESSION").getInt(null));
        // BLOB.MODE_READWRITE
        if (mode == null)
            mode = Caster.toInteger(clazz.getField("MODE_READWRITE").getInt(null));
        //BLOB blob = BLOB.createTemporary(conn, false, BLOB.DURATION_SESSION);
        if (createTemporary == null || createTemporary.getDeclaringClass() != clazz)
            createTemporary = clazz.getMethod("createTemporary", new Class[] { Connection.class, boolean.class, int.class });
        Object blob = createTemporary.invoke(null, new Object[] { conn, Boolean.FALSE, duration });
        //blob.open(BLOB.MODE_READWRITE);
        if (open == null || open.getDeclaringClass() != clazz)
            open = clazz.getMethod("open", new Class[] { int.class });
        open.invoke(blob, new Object[] { mode });
        //blob.setBytes(1,barr);
        if (setBytes == null || setBytes.getDeclaringClass() != clazz)
            setBytes = clazz.getMethod("setBytes", new Class[] { long.class, byte[].class });
        setBytes.invoke(blob, new Object[] { Long.valueOf(1), barr });
        return (Blob) blob;
    } catch (Throwable t) {
        ExceptionUtil.rethrowIfNecessary(t);
    }
    return defaultValue;
}
Example 52
Project: platform2-master  File: DerbySchemaAdapter.java View source code
/* (non-Javadoc)
	 * @see com.idega.data.DatastoreInterface#getSQLType(java.lang.String, int)
	 */
public String getSQLType(String javaClassName, int maxlength) {
    String theReturn;
    if (javaClassName.equals("java.lang.Integer")) {
        theReturn = "INTEGER";
    } else if (javaClassName.equals("java.lang.String")) {
        if (maxlength < 0) {
            theReturn = "VARCHAR(255)";
        } else if (maxlength <= 32000) {
            theReturn = "VARCHAR(" + maxlength + ")";
        } else {
            theReturn = "CLOB";
        }
    } else if (javaClassName.equals("java.lang.Boolean")) {
        theReturn = "CHAR(1)";
    } else if (javaClassName.equals("java.lang.Float")) {
        theReturn = "FLOAT";
    } else if (javaClassName.equals("java.lang.Double")) {
        theReturn = "DOUBLE";
    } else if (javaClassName.equals("java.sql.Timestamp")) {
        theReturn = "TIMESTAMP";
    } else if (javaClassName.equals("java.sql.Date") || javaClassName.equals("java.util.Date")) {
        theReturn = "DATE";
    } else if (javaClassName.equals("java.sql.Blob")) {
        theReturn = "BLOB";
    } else if (javaClassName.equals("java.sql.Time")) {
        theReturn = "TIME";
    } else if (javaClassName.equals("com.idega.util.Gender")) {
        theReturn = "VARCHAR(1)";
    } else if (javaClassName.equals("com.idega.data.BlobWrapper")) {
        theReturn = "BLOB";
    } else {
        theReturn = "";
    }
    return theReturn;
}
Example 53
Project: sakai-cle-master  File: HibernateByteBlobType.java View source code
public void nullSafeSet(PreparedStatement statement, Object value, int index) throws SQLException {
    final byte[] bytes = (byte[]) value;
    if (bytes == null) {
        try {
            statement.setBinaryStream(index, null, 0);
        } catch (SQLException exception) {
            Blob nullBlob = null;
            statement.setBlob(index, nullBlob);
        }
    } else {
        statement.setBinaryStream(index, new ByteArrayInputStream(bytes), bytes.length);
    }
}
Example 54
Project: scriptella-etl-master  File: H2ScriptTest.java View source code
/**
     * Runs the script and checks if transformations has been made.
     *
     * @throws EtlExecutorException
     * @throws SQLException
     * @throws ClassNotFoundException
     */
public void test() throws EtlExecutorException, SQLException, ClassNotFoundException, IOException {
    Class.forName("org.h2.Driver");
    //Opening a connection before executing a script to disable shutdown on last connection close.
    Connection con = DriverManager.getConnection("jdbc:h2:mem:tst");
    EtlExecutor se = newEtlExecutor();
    se.execute();
    ResultSet rs = con.createStatement().executeQuery("SELECT * FROM Test ORDER BY ID");
    List<Integer> actual = new ArrayList<Integer>();
    while (rs.next()) {
        Integer n = (Integer) rs.getObject(1);
        actual.add(n);
        byte[] expBlob = new byte[4];
        Arrays.fill(expBlob, n.byteValue());
        Blob blob = (Blob) rs.getObject(2);
        byte[] actualBlob = blob.getBytes(0, 4);
        //no bytes are left
        assertEquals(4, blob.length());
        assertTrue(Arrays.equals(expBlob, actualBlob));
    }
    List exp = Arrays.asList(1, 2, 3);
    assertEquals(exp, actual);
}
Example 55
Project: seasar2-master  File: BlobType.java View source code
public String getValue(ResultSet resultSet, int index) throws SQLException {
    Blob blob = resultSet.getBlob(index);
    if (blob == null) {
        return null;
    }
    final long length = blob.length();
    if (length == 0) {
        return Base64Util.encode(EMPTY_BYTES);
    }
    if (length > Integer.MAX_VALUE) {
        throw new ArrayIndexOutOfBoundsException();
    }
    return Base64Util.encode(blob.getBytes(1L, (int) length));
}
Example 56
Project: SimpleFlatMapper-master  File: JDBCTypeHelperTest.java View source code
@Test
public void testSqlTypeMapping() {
    testSqlTypes(Array.class, Types.ARRAY);
    testSqlTypes(String.class, Types.CHAR, Types.VARCHAR, Types.LONGNVARCHAR);
    testSqlTypes(BigDecimal.class, Types.NUMERIC, Types.DECIMAL);
    testSqlTypes(boolean.class, Types.BIT);
    testSqlTypes(byte.class, Types.TINYINT);
    testSqlTypes(short.class, Types.SMALLINT);
    testSqlTypes(int.class, Types.INTEGER);
    testSqlTypes(long.class, Types.BIGINT);
    testSqlTypes(float.class, Types.REAL);
    testSqlTypes(double.class, Types.FLOAT, Types.DOUBLE);
    testSqlTypes(byte[].class, Types.BINARY, Types.VARBINARY, Types.LONGVARBINARY);
    testSqlTypes(Date.class, Types.DATE);
    testSqlTypes(Time.class, Types.TIME);
    testSqlTypes(Timestamp.class, Types.TIMESTAMP);
    testSqlTypes(Clob.class, Types.CLOB);
    testSqlTypes(Blob.class, Types.BLOB);
    testSqlTypes(Struct.class, Types.STRUCT);
    testSqlTypes(Ref.class, Types.REF);
    //IFJAVA8_START
    testSqlTypes(OffsetTime.class, Types.TIME_WITH_TIMEZONE);
    testSqlTypes(OffsetDateTime.class, Types.TIMESTAMP_WITH_TIMEZONE);
//IFJAVA8_END
}
Example 57
Project: spring-data-jpa-master  File: JpaResultConverters.java View source code
@Override
public byte[] convert(Blob source) {
    if (source == null) {
        return null;
    }
    InputStream blobStream = null;
    try {
        blobStream = source.getBinaryStream();
        if (blobStream != null) {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            StreamUtils.copy(blobStream, baos);
            return baos.toByteArray();
        }
    } catch (SQLException e) {
        throw new DataRetrievalFailureException("Couldn't retrieve data from blob.", e);
    } catch (IOException e) {
        throw new DataRetrievalFailureException("Couldn't retrieve data from blob.", e);
    } finally {
        if (blobStream != null) {
            try {
                blobStream.close();
            } catch (IOException e) {
                throw new CleanupFailureDataAccessException("Couldn't close binary stream for given blob.", e);
            }
        }
    }
    return null;
}
Example 58
Project: teiid-samples-master  File: TeiidServerPlatform.java View source code
protected Hashtable buildFieldTypes() {
    Hashtable fieldTypeMapping = super.buildFieldTypes();
    fieldTypeMapping.put(Boolean.class, new FieldTypeDefinition("varchar", false));
    fieldTypeMapping.put(byte[].class, new FieldTypeDefinition("varbinary", false));
    fieldTypeMapping.put(Character.class, new FieldTypeDefinition("char", false));
    fieldTypeMapping.put(Boolean.class, new FieldTypeDefinition("boolean", false));
    fieldTypeMapping.put(Byte.class, new FieldTypeDefinition("tinyint", false));
    fieldTypeMapping.put(Short.class, new FieldTypeDefinition("smallint", false));
    fieldTypeMapping.put(Integer.class, new FieldTypeDefinition("integer", false));
    fieldTypeMapping.put(Long.class, new FieldTypeDefinition("bigint", false));
    fieldTypeMapping.put(BigInteger.class, new FieldTypeDefinition("biginteger", false));
    fieldTypeMapping.put(Float.class, new FieldTypeDefinition("float", false));
    fieldTypeMapping.put(Double.class, new FieldTypeDefinition("double", false));
    fieldTypeMapping.put(BigDecimal.class, new FieldTypeDefinition("bigdecimal", false));
    fieldTypeMapping.put(Date.class, new FieldTypeDefinition("date", false));
    fieldTypeMapping.put(Time.class, new FieldTypeDefinition("time", false));
    fieldTypeMapping.put(Timestamp.class, new FieldTypeDefinition("timestamp", false));
    fieldTypeMapping.put(Object.class, new FieldTypeDefinition("object", false));
    fieldTypeMapping.put(Blob.class, new FieldTypeDefinition("blob", false));
    fieldTypeMapping.put(Clob.class, new FieldTypeDefinition("clob", false));
    fieldTypeMapping.put(SQLXML.class, new FieldTypeDefinition("xml", false));
    return fieldTypeMapping;
}
Example 59
Project: wicket-master  File: BlobImageResource.java View source code
@Override
protected byte[] getImageData(Attributes attributes) {
    try {
        Blob blob = getBlob(attributes);
        if (blob != null) {
            InputStream in = blob.getBinaryStream();
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            Streams.copy(in, out);
            return out.toByteArray();
        }
        return new byte[0];
    } catch (SQLException e) {
        throw new WicketRuntimeException("Error while reading image data", e);
    } catch (IOException e) {
        throw new WicketRuntimeException("Error while reading image data", e);
    }
}
Example 60
Project: agile4techos-master  File: Blob.java View source code
/**
	 * Returns as an array of bytes, part or all of the BLOB value that this
	 * Blob object designates.
	 * 
	 * @param pos
	 *            where to start the part of the BLOB
	 * @param length
	 *            the length of the part of the BLOB you want returned.
	 * 
	 * @return the bytes stored in the blob starting at position
	 *         <code>pos</code> and having a length of <code>length</code>.
	 * 
	 * @throws SQLException
	 *             if a database error occurs
	 */
public byte[] getBytes(long pos, int length) throws SQLException {
    if (pos < 1) {
        throw //$NON-NLS-1$
        SQLError.createSQLException(//$NON-NLS-1$
        Messages.getString("Blob.2"), SQLError.SQL_STATE_ILLEGAL_ARGUMENT);
    }
    byte[] newData = new byte[length];
    System.arraycopy(getBinaryData(), (int) (pos - 1), newData, 0, length);
    return newData;
}
Example 61
Project: GestionBibliotheque-master  File: Blob.java View source code
/**
	 * Returns as an array of bytes, part or all of the BLOB value that this
	 * Blob object designates.
	 * 
	 * @param pos
	 *            where to start the part of the BLOB
	 * @param length
	 *            the length of the part of the BLOB you want returned.
	 * 
	 * @return the bytes stored in the blob starting at position
	 *         <code>pos</code> and having a length of <code>length</code>.
	 * 
	 * @throws SQLException
	 *             if a database error occurs
	 */
public byte[] getBytes(long pos, int length) throws SQLException {
    if (pos < 1) {
        throw //$NON-NLS-1$
        SQLError.createSQLException(//$NON-NLS-1$
        Messages.getString("Blob.2"), SQLError.SQL_STATE_ILLEGAL_ARGUMENT);
    }
    byte[] newData = new byte[length];
    System.arraycopy(getBinaryData(), (int) (pos - 1), newData, 0, length);
    return newData;
}
Example 62
Project: openelisglobal-core-master  File: LIMSRawDataUserType.java View source code
//bugzilla 1908 modified this method. This seems to work for postgres (bytea) AND oracle (Blob)
public void set(PreparedStatement st, Object value, int index, SessionImplementor session) throws HibernateException, SQLException {
    if (value == null) {
        //1908 changed from Types.Blob to Types.BINARY for postgres
        st.setNull(index, Types.BINARY);
    } else {
        if (value instanceof SerializableBlob) {
            value = ((SerializableBlob) value).getWrappedBlob();
        }
        BlobImpl blob = (BlobImpl) value;
        st.setBinaryStream(index, blob.getBinaryStream(), (int) blob.length());
    }
}
Example 63
Project: pljava-master  File: BlobValue.java View source code
public byte[] getBytes(long pos, int length) throws SQLException {
    if (pos < 0L || length < 0)
        throw new IllegalArgumentException();
    if (length == 0)
        return new byte[0];
    if (pos + length > m_nBytes)
        throw new SQLException("Attempt to read beyond end of Blob data");
    long skip = pos - m_streamPos;
    if (skip < 0)
        throw new SQLException("Cannot position Blob stream backwards");
    try {
        if (skip > 0)
            this.skip(skip);
        byte[] buf = new byte[length];
        this.read(buf);
        return buf;
    } catch (IOException e) {
        throw new SQLException("Error reading Blob data: " + e.getMessage());
    }
}
Example 64
Project: querydsl-master  File: SimpleTypesTest.java View source code
@Test
public void simple_types() throws IllegalAccessException, NoSuchFieldException {
    start(QSimpleTypesTest_SimpleTypes.class, QSimpleTypesTest_SimpleTypes.simpleTypes);
    match(NumberPath.class, "id");
    matchType(Long.class, "id");
    match(NumberPath.class, "bigDecimal");
    matchType(BigDecimal.class, "bigDecimal");
    match(NumberPath.class, "bigInteger");
    matchType(BigInteger.class, "bigInteger");
    //        match(PNumber.class, "bbyte");
    match(NumberPath.class, "bbyte2");
    matchType(Byte.class, "bbyte");
    match(NumberPath.class, "ddouble");
    matchType(Double.class, "ddouble");
    match(NumberPath.class, "ddouble2");
    matchType(Double.class, "ddouble2");
    match(NumberPath.class, "ffloat");
    matchType(Float.class, "ffloat");
    match(NumberPath.class, "ffloat2");
    matchType(Float.class, "ffloat2");
    //        match(PNumber.class, "iint");
    match(NumberPath.class, "iint2");
    matchType(Integer.class, "iint2");
    match(NumberPath.class, "llong");
    matchType(Long.class, "llong");
    match(NumberPath.class, "llong2");
    matchType(Long.class, "llong2");
    match(ComparablePath.class, "cchar");
    matchType(Character.class, "cchar");
    match(ComparablePath.class, "cchar2");
    matchType(Character.class, "cchar2");
    match(StringPath.class, "sstring");
    match(DateTimePath.class, "date");
    matchType(Date.class, "date");
    match(DateTimePath.class, "calendar");
    matchType(Calendar.class, "calendar");
    //        match(PDateTime.class, "timestamp");
    match(TimePath.class, "time");
    matchType(Time.class, "time");
    match(SimplePath.class, "llocale");
    matchType(Locale.class, "llocale");
    match(SimplePath.class, "serializable");
    matchType(Serializable.class, "serializable");
    match(SimplePath.class, "object");
    matchType(Object.class, "object");
    match(SimplePath.class, "clazz");
    matchType(Class.class, "clazz");
    match(SimplePath.class, "packageAsLiteral");
    matchType(Package.class, "packageAsLiteral");
    match(SimplePath.class, "clob");
    matchType(Clob.class, "clob");
    match(SimplePath.class, "blob");
    matchType(Blob.class, "blob");
    match(EnumPath.class, "myEnum");
    matchType(MyEnum.class, "myEnum");
}
Example 65
Project: repominerEvo-master  File: AbstractEntityManager.java View source code
protected void setParameter(PreparedStatement stmt, int index, Object value, int sqlType) {
    try {
        if (value == null) {
            stmt.setNull(index, sqlType);
        } else if (value instanceof Boolean) {
            stmt.setBoolean(index, (Boolean) value);
        } else if (value instanceof Byte) {
            stmt.setByte(index, (Byte) value);
        } else if (value instanceof Short) {
            stmt.setShort(index, (Short) value);
        } else if (value instanceof Integer) {
            stmt.setInt(index, (Integer) value);
        } else if (value instanceof Long) {
            stmt.setLong(index, (Long) value);
        } else if (value instanceof Float) {
            stmt.setFloat(index, (Float) value);
        } else if (value instanceof Double) {
            stmt.setDouble(index, (Double) value);
        } else if (value instanceof byte[]) {
            stmt.setBytes(index, (byte[]) value);
        } else if (value instanceof char[]) {
            stmt.setString(index, new String((char[]) value));
        } else if (value instanceof String) {
            stmt.setString(index, (String) value);
        } else if (value instanceof BigDecimal) {
            stmt.setBigDecimal(index, (BigDecimal) value);
        } else if (value instanceof java.util.Date) {
            stmt.setTimestamp(index, new java.sql.Timestamp(((java.util.Date) value).getTime()));
        } else if (value instanceof java.sql.Date) {
            stmt.setDate(index, (java.sql.Date) value);
        } else if (value instanceof java.sql.Time) {
            stmt.setTime(index, (java.sql.Time) value);
        } else if (value instanceof java.sql.Timestamp) {
            stmt.setTimestamp(index, (java.sql.Timestamp) value);
        } else if (value instanceof java.sql.Clob) {
            stmt.setClob(index, (java.sql.Clob) value);
        } else if (value instanceof java.sql.Blob) {
            stmt.setBlob(index, (java.sql.Blob) value);
        } else {
            throw new RuntimeSQLException("Unsupported type '" + value.getClass().getName() + "'");
        }
    } catch (SQLException e) {
        throw new RuntimeSQLException(e);
    }
}
Example 66
Project: StreamFS-master  File: Blob.java View source code
/**
	 * Returns as an array of bytes, part or all of the BLOB value that this
	 * Blob object designates.
	 * 
	 * @param pos
	 *            where to start the part of the BLOB
	 * @param length
	 *            the length of the part of the BLOB you want returned.
	 * 
	 * @return the bytes stored in the blob starting at position
	 *         <code>pos</code> and having a length of <code>length</code>.
	 * 
	 * @throws SQLException
	 *             if a database error occurs
	 */
public byte[] getBytes(long pos, int length) throws SQLException {
    if (pos < 1) {
        throw //$NON-NLS-1$
        SQLError.createSQLException(//$NON-NLS-1$
        Messages.getString("Blob.2"), SQLError.SQL_STATE_ILLEGAL_ARGUMENT);
    }
    byte[] newData = new byte[length];
    System.arraycopy(getBinaryData(), (int) (pos - 1), newData, 0, length);
    return newData;
}
Example 67
Project: voltdb-master  File: JDBCStatementReader.java View source code
@Override
Object convert() throws SQLException {
    Object val = null;
    java.sql.Blob blob = null;
    try {
        val = m_rslt.getObject(m_idx);
        if (m_rslt.wasNull())
            return null;
        blob = (java.sql.Blob) val;
        if (blob.length() > MAX_COLUMN_SIZE) {
            throw new SQLException("blobs may not be greater than " + MAX_COLUMN_SIZE);
        }
        return blob.getBytes(0, (int) blob.length());
    } finally {
        if (blob != null) {
            try {
                blob.free();
            } catch (Exception ignoreIt) {
            }
        }
    }
}
Example 68
Project: activeobjects-master  File: BlobType.java View source code
@Override
public Object pullFromDatabase(EntityManager manager, ResultSet res, Class<?> type, String field) throws SQLException {
    if (manager.getProvider().getURI().startsWith("jdbc:postgres")) {
        if (type.equals(InputStream.class)) {
            return res.getBinaryStream(field);
        } else if (type.equals(byte[].class)) {
            return res.getBytes(field);
        }
        return null;
    }
    Blob blob = res.getBlob(field);
    if (type.equals(InputStream.class)) {
        // derby handles BLOBs oddly
        if (manager.getProvider().getURI().startsWith("jdbc:derby")) {
            return new ByteArrayInputStream(blob.getBytes(1, (int) blob.length()));
        }
        return blob.getBinaryStream();
    } else if (type.equals(byte[].class)) {
        return blob.getBytes(1, (int) blob.length());
    }
    return null;
}
Example 69
Project: AnalyzerBeans-master  File: MetaModelInputRow.java View source code
private Object convertValue(Object value) {
    if (value instanceof Clob) {
        try {
            Reader reader = ((Clob) value).getCharacterStream();
            try {
                value = FileHelper.readAsString(reader);
            } finally {
                FileHelper.safeClose(reader);
            }
        } catch (SQLException e) {
            logger.error("Failed to convert CLOB to String", e);
            value = null;
        }
    } else if (value instanceof Blob) {
        try {
            InputStream inputStream = ((Blob) value).getBinaryStream();
            try {
                value = FileHelper.readAsBytes(inputStream);
            } finally {
                FileHelper.safeClose(inputStream);
            }
        } catch (SQLException e) {
            logger.error("Failed to convert BLOB to byte[]", e);
            value = null;
        }
    }
    return value;
}
Example 70
Project: ariadne-repository-master  File: InsertMetadataIBMDB2DbImpl.java View source code
/*
     * NOTE: Collection is not implemented!
     * 
     * */
public synchronized void insertMetadata(String identifier, String metadata, String collection) throws InsertMetadataException {
    try {
        Connection con = getConnection();
        PreparedStatement pstmt;
        pstmt = con.prepareStatement("DELETE FROM " + tableName + " WHERE " + identifierColumnName + " = ?");
        pstmt.setString(1, identifier);
        pstmt.execute();
        pstmt.close();
        java.sql.Blob blobData = com.ibm.db2.jcc.t2zos.DB2LobFactory.createBlob(metadata.getBytes("UTF-8"));
        pstmt = con.prepareStatement("INSERT INTO " + tableName + " (" + identifierColumnName + ", " + columnName + ") " + "VALUES(?, XMLPARSE(document cast(? as Blob) strip whitespace))");
        pstmt.setString(1, identifier);
        pstmt.setBlob(2, blobData);
        pstmt.execute();
        pstmt.close();
        con.close();
        log.info("insertMetadata:identifier:\"" + identifier + "\"");
    } catch (SQLException e) {
        log.error("insertMetadata:identifier:\"" + identifier + "\" ", e);
        throw new InsertMetadataException(e);
    } catch (UnsupportedEncodingException e) {
        log.error("insertMetadata:identifier:\"" + identifier + "\" ", e);
        throw new InsertMetadataException(e);
    }
}
Example 71
Project: AriadneRepository-master  File: InsertMetadataIBMDB2DbImpl.java View source code
/*
     * NOTE: Collection is not implemented!
     * 
     * */
public synchronized void insertMetadata(String identifier, String metadata, String collection) throws InsertMetadataException {
    try {
        Connection con = getConnection();
        PreparedStatement pstmt;
        pstmt = con.prepareStatement("DELETE FROM " + tableName + " WHERE " + identifierColumnName + " = ?");
        pstmt.setString(1, identifier);
        pstmt.execute();
        pstmt.close();
        java.sql.Blob blobData = com.ibm.db2.jcc.t2zos.DB2LobFactory.createBlob(metadata.getBytes("UTF-8"));
        pstmt = con.prepareStatement("INSERT INTO " + tableName + " (" + identifierColumnName + ", " + columnName + ") " + "VALUES(?, XMLPARSE(document cast(? as Blob) strip whitespace))");
        pstmt.setString(1, identifier);
        pstmt.setBlob(2, blobData);
        pstmt.execute();
        pstmt.close();
        con.close();
        log.info("insertMetadata:identifier:\"" + identifier + "\"");
    } catch (SQLException e) {
        log.error("insertMetadata:identifier:\"" + identifier + "\" ", e);
        throw new InsertMetadataException(e);
    } catch (UnsupportedEncodingException e) {
        log.error("insertMetadata:identifier:\"" + identifier + "\" ", e);
        throw new InsertMetadataException(e);
    }
}
Example 72
Project: Asper-master  File: TestSQLTypeMapUtil.java View source code
public void testMapping() {
    Map<Integer, Class> testData = new HashMap<Integer, Class>();
    testData.put(Types.CHAR, String.class);
    testData.put(Types.VARCHAR, String.class);
    testData.put(Types.LONGVARCHAR, String.class);
    testData.put(Types.NUMERIC, BigDecimal.class);
    testData.put(Types.DECIMAL, BigDecimal.class);
    testData.put(Types.BIT, Boolean.class);
    testData.put(Types.BOOLEAN, Boolean.class);
    testData.put(Types.TINYINT, Byte.class);
    testData.put(Types.SMALLINT, Short.class);
    testData.put(Types.INTEGER, Integer.class);
    testData.put(Types.BIGINT, Long.class);
    testData.put(Types.REAL, Float.class);
    testData.put(Types.FLOAT, Double.class);
    testData.put(Types.DOUBLE, Double.class);
    testData.put(Types.BINARY, byte[].class);
    testData.put(Types.VARBINARY, byte[].class);
    testData.put(Types.LONGVARBINARY, byte[].class);
    testData.put(Types.DATE, java.sql.Date.class);
    testData.put(Types.TIMESTAMP, java.sql.Timestamp.class);
    testData.put(Types.TIME, java.sql.Time.class);
    testData.put(Types.CLOB, java.sql.Clob.class);
    testData.put(Types.BLOB, java.sql.Blob.class);
    testData.put(Types.ARRAY, java.sql.Array.class);
    testData.put(Types.STRUCT, java.sql.Struct.class);
    testData.put(Types.REF, java.sql.Ref.class);
    testData.put(Types.DATALINK, java.net.URL.class);
    for (int type : testData.keySet()) {
        Class result = SQLTypeMapUtil.sqlTypeToClass(type, null);
        log.debug(".testMapping Mapping " + type + " to " + result.getSimpleName());
        assertEquals(testData.get(type), result);
    }
    assertEquals(String.class, SQLTypeMapUtil.sqlTypeToClass(Types.JAVA_OBJECT, "java.lang.String"));
    assertEquals(String.class, SQLTypeMapUtil.sqlTypeToClass(Types.DISTINCT, "java.lang.String"));
}
Example 73
Project: brigen-base-master  File: PostgresqlTypeComparator.java View source code
@Override
public boolean compare(Class<?> fieldType, String columnType) {
    boolean ret = false;
    if (fieldType.isPrimitive()) {
        if (fieldType.equals(Boolean.TYPE)) {
            if (columnType.toLowerCase().matches("^bool$")) {
                ret = true;
            }
        } else if (fieldType.equals(Byte.TYPE)) {
        // unsupported
        } else if (fieldType.equals(Short.TYPE)) {
            if (columnType.toLowerCase().matches("^int2$")) {
                ret = true;
            }
        } else if (fieldType.equals(Character.TYPE)) {
        // unsupported
        } else if (fieldType.equals(Integer.TYPE)) {
            if (columnType.toLowerCase().matches("^(int4|serial)$")) {
                ret = true;
            }
        } else if (fieldType.equals(Long.TYPE)) {
            if (columnType.toLowerCase().matches("^(int8|bigserial)$")) {
                ret = true;
            }
        } else if (fieldType.equals(Float.TYPE)) {
            if (columnType.toLowerCase().matches("^float4$")) {
                ret = true;
            }
        } else if (fieldType.equals(Double.TYPE)) {
            if (columnType.toLowerCase().matches("^float8$")) {
                ret = true;
            }
        }
    } else {
        if (Boolean.class.isAssignableFrom(fieldType)) {
            if (columnType.toLowerCase().matches("^bool$")) {
                ret = true;
            }
        } else if (Number.class.isAssignableFrom(fieldType)) {
            if (Byte.class.isAssignableFrom(fieldType)) {
            // unsupported
            } else if (Short.class.isAssignableFrom(fieldType)) {
                if (columnType.toLowerCase().matches("^int2$")) {
                    ret = true;
                }
            } else if (Integer.class.isAssignableFrom(fieldType)) {
                if (columnType.toLowerCase().matches("^(int4|serial)$")) {
                    ret = true;
                }
            } else if (Long.class.isAssignableFrom(fieldType)) {
                if (columnType.toLowerCase().matches("^(int8|bigserial)$")) {
                    ret = true;
                }
            } else if (Float.class.isAssignableFrom(fieldType)) {
                if (columnType.toLowerCase().matches("^float4$")) {
                    ret = true;
                }
            } else if (Double.class.isAssignableFrom(fieldType)) {
                if (columnType.toLowerCase().matches("^float8$")) {
                    ret = true;
                }
            } else if (BigDecimal.class.isAssignableFrom(fieldType)) {
                if (columnType.toLowerCase().matches("^numeric$")) {
                    ret = true;
                }
            }
        } else if (Character.class.isAssignableFrom(fieldType)) {
        // unsupported
        } else if (String.class.isAssignableFrom(fieldType)) {
            if (columnType.toLowerCase().matches("^(bpchar|varchar|text|bit)$")) {
                ret = true;
            }
        } else if (Date.class.isAssignableFrom(fieldType)) {
            if (java.sql.Timestamp.class.isAssignableFrom(fieldType)) {
                if (columnType.toLowerCase().matches("^(timestamp|timestamptz)$")) {
                    ret = true;
                }
            } else if (java.sql.Time.class.isAssignableFrom(fieldType)) {
                if (columnType.toLowerCase().matches("^(time|timetz)$")) {
                    ret = true;
                }
            } else if (java.sql.Date.class.isAssignableFrom(fieldType)) {
                if (columnType.toLowerCase().matches("^date$")) {
                    ret = true;
                }
            } else {
                if (columnType.toLowerCase().matches("^(date|time|timetz|timestamp|timestamptz)$")) {
                    ret = true;
                }
            }
        } else if (fieldType.isArray()) {
            if (fieldType.getComponentType().equals(Byte.TYPE)) {
                if (columnType.toLowerCase().matches("^bytea$")) {
                    ret = true;
                }
            }
        } else if (Blob.class.isAssignableFrom(fieldType)) {
            if (columnType.toLowerCase().matches("^blob$")) {
                ret = true;
            }
        } else if (Clob.class.isAssignableFrom(fieldType)) {
            if (columnType.toLowerCase().matches("^clob$")) {
                ret = true;
            }
        }
    }
    return ret;
}
Example 74
Project: cdo-master  File: HibernateCDOPackageUnitDTO.java View source code
private byte[] toByteArray(Blob blob) {
    try {
        final InputStream is = blob.getBinaryStream();
        final ByteArrayOutputStream bos = new ByteArrayOutputStream();
        int dataSize;
        final byte[] buffer = new byte[4000];
        try {
            while ((dataSize = is.read(buffer)) != -1) {
                bos.write(buffer, 0, dataSize);
            }
        } finally {
            IOUtil.close(is);
        }
        return bos.toByteArray();
    } catch (Exception e) {
        throw WrappedException.wrap(e);
    }
}
Example 75
Project: compass-fork-master  File: FetchOnOpenJdbcIndexInput.java View source code
public Object execute(ResultSet rs) throws Exception {
    if (!rs.next()) {
        throw new JdbcStoreException("No entry for [" + name + "] table " + jdbcDirectory.getTable());
    }
    length = rs.getInt(3);
    Blob blob = rs.getBlob(2);
    data = blob.getBytes(1, length);
    if (data.length != length) {
        throw new IOException("read past EOF");
    }
    return null;
}
Example 76
Project: cosmo-master  File: BufferedContentTypeDescriptor.java View source code
@Override
public <X> BufferedContent wrap(X value, WrapperOptions options) {
    if (value == null) {
        return null;
    }
    if (BufferedContent.class.isInstance(value)) {
        return (BufferedContent) value;
    }
    if (InputStream.class.isInstance(value)) {
        try {
            return new BufferedContent((InputStream) value);
        } catch (IOException e) {
            throw new CosmoIOException(e);
        }
    }
    if (Blob.class.isInstance(value)) {
        try {
            return new BufferedContent(((Blob) value).getBinaryStream());
        } catch (IOExceptionSQLException |  e) {
            throw new CosmoIOException(e);
        }
    }
    throw unknownWrap(value.getClass());
}
Example 77
Project: dbflute-master  File: BinaryType.java View source code
private byte[] toByteArray(Blob blob) throws SQLException {
    if (blob == null) {
        return null;
    }
    long l = blob.length();
    if (Integer.MAX_VALUE < l) {
        String msg = "The length of the BLOB value should be less (equal) than integer:";
        msg = msg + " length=" + l + " value=" + blob;
        throw new ArrayIndexOutOfBoundsException(msg);
    }
    return blob.getBytes(1, (int) l);
}
Example 78
Project: fly-gdx-master  File: IOSCursor.java View source code
@Override
public byte[] getBlob(int columnIndex) {
    try {
        Blob blob = resultSet.getBlob(columnIndex + 1);
        return blob.getBytes(1, (int) blob.length());
    } catch (SQLException e) {
        Gdx.app.log(DatabaseFactory.ERROR_TAG, "There was an error in getting the blob", e);
        throw new SQLiteGdxRuntimeException(e);
    }
}
Example 79
Project: gaiandb-master  File: SampleUDFs.java View source code
public static Blob fheSearch(final String bytesURI) throws Exception {
    // The initial URI scheme targets a file through GaianNode using syntax: "<NodeID> <FilePath>"
    // New schemes could be used in future, e.g. to target a db table or a web location.
    int idx = bytesURI.indexOf(' ');
    if (0 > idx)
        throw new Exception("FHE_SEARCH() argument 'bytesURI' does not conform to syntax: '<NodeID> <FilePath>'");
    final String nodeID = bytesURI.substring(0, idx);
    final String filePath = bytesURI.substring(idx + 1);
    idx = filePath.lastIndexOf('/');
    final String fileName = 0 > idx ? filePath : filePath.substring(idx + 1);
    Connection c = null;
    try {
        final String connectionDetails = GaianDBConfig.getRDBConnectionDetailsAsString(nodeID);
        c = GaianDBConfig.getNewDBConnector(GaianDBConfig.getConnectionTokens(connectionDetails)).getConnection();
        ResultSet rs = c.createStatement().executeQuery("select getFileBZ(''" + filePath + "'') fzbytes from sysibm.sysdummy1");
        byte[] bytes = rs.getBytes(1);
        File file = new File(fileName);
        System.out.println("Received file: " + fileName + ", size: " + file.length());
        writeToFileAfterUnzip(file, bytes);
        rs.close();
        /** Call to FHE code **/
        Process process = new ProcessBuilder("sleep", "3").start();
        try {
            process.waitFor();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        file = new File(fileName);
        System.out.println("Resulting FHE bytes file: " + fileName + ", size: " + file.length());
        bytes = readAndZipFileBytes(file);
        // Cast to EmbedConnection as we know Derby supports createBlob() regardless of Java version
        Blob blob = ((EmbedConnection) getDefaultDerbyConnection()).createBlob();
        blob.setBytes(1, bytes);
        return blob;
    } catch (Exception e) {
        throw new Exception("Unable to get bytes from node: " + nodeID + ", file: " + filePath + ": " + e);
    } finally {
        logger.logInfo("Closing connection");
        if (// Return connection to pool (may get closed immediately if not referenced by a data source or sourcelist)
        null != nodeID && null != c)
            DataSourcesManager.getSourceHandlesPool(GaianDBConfig.getRDBConnectionDetailsAsString(nodeID)).push(c);
    }
}
Example 80
Project: geoserver-2.0.x-master  File: BoundingBoxType.java View source code
public Object nullSafeGet(ResultSet rs, String[] names, Object owner) throws HibernateException, SQLException {
    double minx = rs.getDouble(names[0]);
    double miny = rs.getDouble(names[1]);
    double maxx = rs.getDouble(names[2]);
    double maxy = rs.getDouble(names[3]);
    Blob blob = rs.getBlob(names[4]);
    if (blob != null) {
        String wkt = new String(blob.getBytes(1, (int) blob.length()));
        CoordinateReferenceSystem crs;
        try {
            crs = CRS.parseWKT(wkt);
        } catch (Exception e) {
            String msg = "Unable to create crs from wkt: " + wkt;
            throw new HibernateException(msg, e);
        }
        return new ReferencedEnvelope(minx, maxx, miny, maxy, crs);
    } else {
        return new ReferencedEnvelope(minx, maxx, miny, maxy, null);
    }
}
Example 81
Project: geoserver-master  File: ErrorUserType.java View source code
public Object nullSafeGet(ResultSet rs, String[] names, Object owner) throws HibernateException, SQLException {
    Blob blob = rs.getBlob(names[0]);
    if (blob == null) {
        return null;
    }
    //        byte[] bytes = rs.getBytes(names[0]);
    //        if (bytes == null) {
    //            return null;
    //        }
    ObjectInputStream in = null;
    try {
        //in = new ObjectInputStream(new ByteArrayInputStream(bytes));
        in = new ObjectInputStream(blob.getBinaryStream());
        return in.readObject();
    } catch (IOException e) {
        throw new HibernateException(e);
    } catch (ClassNotFoundException e) {
        throw new HibernateException(e);
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
            }
        }
    }
}
Example 82
Project: geoserver-old-master  File: ErrorUserType.java View source code
public Object nullSafeGet(ResultSet rs, String[] names, Object owner) throws HibernateException, SQLException {
    Blob blob = rs.getBlob(names[0]);
    if (blob == null) {
        return null;
    }
    //        byte[] bytes = rs.getBytes(names[0]);
    //        if (bytes == null) {
    //            return null;
    //        }
    ObjectInputStream in = null;
    try {
        //in = new ObjectInputStream(new ByteArrayInputStream(bytes));
        in = new ObjectInputStream(blob.getBinaryStream());
        return in.readObject();
    } catch (IOException e) {
        throw new HibernateException(e);
    } catch (ClassNotFoundException e) {
        throw new HibernateException(e);
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
            }
        }
    }
}
Example 83
Project: geoserver_trunk-master  File: ErrorUserType.java View source code
public Object nullSafeGet(ResultSet rs, String[] names, Object owner) throws HibernateException, SQLException {
    Blob blob = rs.getBlob(names[0]);
    if (blob == null) {
        return null;
    }
    //        byte[] bytes = rs.getBytes(names[0]);
    //        if (bytes == null) {
    //            return null;
    //        }
    ObjectInputStream in = null;
    try {
        //in = new ObjectInputStream(new ByteArrayInputStream(bytes));
        in = new ObjectInputStream(blob.getBinaryStream());
        return in.readObject();
    } catch (IOException e) {
        throw new HibernateException(e);
    } catch (ClassNotFoundException e) {
        throw new HibernateException(e);
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
            }
        }
    }
}
Example 84
Project: ha-jdbc-master  File: BlobTest.java View source code
@Test
public void test() throws Exception {
    JDBCDataSource ds1 = new JDBCDataSource();
    ds1.setUrl("jdbc:hsqldb:mem:db1");
    JDBCDataSource ds2 = new JDBCDataSource();
    ds2.setUrl("jdbc:hsqldb:mem:db2");
    try (DataSource ds = new DataSource()) {
        ds.setCluster("cluster");
        DataSourceDatabaseClusterConfigurationBuilder builder = ds.getConfigurationBuilder();
        builder.addDatabase("db1").dataSource(ds1);
        builder.addDatabase("db2").dataSource(ds2);
        builder.addSynchronizationStrategy("passive");
        builder.defaultSynchronizationStrategy("passive").dialect("hsqldb").metaDataCache("none").durability("none").state("simple");
        try (Connection c = ds.getConnection()) {
            c.setAutoCommit(true);
            createTable(c);
            c.setAutoCommit(false);
            try {
                Assert.assertFalse(c.getMetaData().locatorsUpdateCopy());
                ConnectionInvocationHandler<javax.sql.DataSource, DataSourceDatabase, javax.sql.DataSource> handler = (ConnectionInvocationHandler<javax.sql.DataSource, DataSourceDatabase, javax.sql.DataSource>) Proxy.getInvocationHandler(c);
                ConnectionProxyFactory<javax.sql.DataSource, DataSourceDatabase, javax.sql.DataSource> proxyFactory = handler.getProxyFactory();
                DataSourceDatabase db1 = proxyFactory.getDatabaseCluster().getDatabase("db1");
                DataSourceDatabase db2 = proxyFactory.getDatabaseCluster().getDatabase("db2");
                Connection c1 = proxyFactory.get(db1);
                Connection c2 = proxyFactory.get(db2);
                Blob blob = c.createBlob();
                String expected = "test";
                try (Writer writer = new OutputStreamWriter(blob.setBinaryStream(1))) {
                    writer.write(expected);
                    writer.flush();
                }
                try (PreparedStatement ps = c.prepareStatement("INSERT INTO test (id, lob) VALUES (?, ?)")) {
                    ps.setInt(1, 1);
                    ps.setBlob(2, blob);
                    ps.executeUpdate();
                }
                c.commit();
                blob.free();
                validate(c1, expected);
                validate(c2, expected);
                try (PreparedStatement ps = c.prepareStatement("SELECT lob FROM test WHERE id = ?", ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE)) {
                    ps.setInt(1, 1);
                    try (ResultSet results = ps.executeQuery()) {
                        Assert.assertTrue(results.next());
                        blob = results.getBlob(1);
                        expected = "1234";
                        blob.truncate(blob.length());
                        /* Not supported by HSQLDB
							writer = new OutputStreamWriter(blob.setBinaryStream(1));
							writer.write(expected);
							writer.close();
							*/
                        blob.setBytes(1, expected.getBytes());
                        results.updateRow();
                        Assert.assertFalse(results.next());
                        c.commit();
                        blob.free();
                    }
                }
                validate(c1, expected);
                validate(c2, expected);
            } finally {
                c.setAutoCommit(true);
                dropTable(c);
            }
        }
    }
}
Example 85
Project: heliosearch-master  File: FieldStreamDataSource.java View source code
@Override
public InputStream getData(String query) {
    Object o = wrapper.getVariableResolver().resolve(dataField);
    if (o == null) {
        throw new DataImportHandlerException(SEVERE, "No field available for name : " + dataField);
    }
    if (o instanceof Blob) {
        Blob blob = (Blob) o;
        try {
            //Most of the JDBC drivers have getBinaryStream defined as public
            // so let us just check it
            Method m = blob.getClass().getDeclaredMethod("getBinaryStream");
            if (Modifier.isPublic(m.getModifiers())) {
                return (InputStream) m.invoke(blob);
            } else {
                // force invoke
                m.setAccessible(true);
                return (InputStream) m.invoke(blob);
            }
        } catch (Exception e) {
            LOG.info("Unable to get data from BLOB");
            return null;
        }
    } else if (o instanceof byte[]) {
        byte[] bytes = (byte[]) o;
        return new ByteArrayInputStream(bytes);
    } else {
        throw new RuntimeException("unsupported type : " + o.getClass());
    }
}
Example 86
Project: hibernate-search-master  File: TikaBridgeProvider.java View source code
private void validateMemberType(ExtendedBridgeProviderContext context) {
    Class<?> elementType = context.getReturnType();
    // Example: URI, List<URI>, List<byte[]>
    if (!Blob.class.isAssignableFrom(elementType) && !String.class.isAssignableFrom(elementType) && !byte[].class.isAssignableFrom(elementType) && !URI.class.isAssignableFrom(elementType)) {
        // byte[] is actually an array but we want to treat it as a simple element
        Class<?> returnType = context.getElementOrContainerReturnType();
        if (!byte[].class.isAssignableFrom(returnType)) {
            throw LOG.unsupportedTikaBridgeType(returnType);
        }
    }
}
Example 87
Project: hibernate-semantic-query-master  File: PrimitiveByteArrayJavaDescriptor.java View source code
@SuppressWarnings({ "unchecked" })
public <X> X unwrap(byte[] value, Class<X> type, WrapperOptions options) {
    if (value == null) {
        return null;
    }
    if (byte[].class.isAssignableFrom(type)) {
        return (X) value;
    }
    if (InputStream.class.isAssignableFrom(type)) {
        return (X) new ByteArrayInputStream(value);
    }
    if (BinaryStream.class.isAssignableFrom(type)) {
        return (X) new BinaryStreamImpl(value);
    }
    if (Blob.class.isAssignableFrom(type)) {
        return (X) options.getLobCreator().createBlob(value);
    }
    throw unknownUnwrap(type);
}
Example 88
Project: InfoButtons-master  File: ProfilesDaoImpl.java View source code
/*
     * (non-Javadoc)
     * @see edu.utah.further.profiledb.service.ProfilesDao#getResourceProfile(long, int, 
     *                              edu.utah.further.profiledb.service.FileandMarker)
     */
@Override
@Transactional
public void getResourceProfile(long id, int status, FileandMarker fm) {
    boolean finish = false;
    Profiles p = null;
    while (!finish) {
        final Map<String, Object> properties = new HashMap<String, Object>();
        properties.put("id", new Long(id));
        properties.put("status", new Integer(status));
        final List l = dao.findByProperties(Profiles.class, properties);
        id++;
        fm.setMarker((int) id);
        if (l.size() != 0) {
            p = (Profiles) l.get(0);
            finish = true;
        }
    }
    try {
        final Blob b = p.getContent();
        final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        final DocumentBuilder db = dbf.newDocumentBuilder();
        final Document doc = db.parse(b.getBinaryStream());
        fm.setBlobFile(doc);
    // A temporary file is created here
    // fm.setBlobFile(new File("fetch.xml")) ;
    //
    // InputStream in = b.getBinaryStream();
    // BufferedInputStream bufferedInputStream = new BufferedInputStream( in);
    // FileOutputStream outStream = new FileOutputStream(fm.getBlobFile());
    // int data = -1;
    // while ( (data = bufferedInputStream.read( )) != -1 )
    // {
    // outStream.write( data);
    // }
    } catch (final Exception e) {
        e.printStackTrace();
    }
// return fm;
}
Example 89
Project: liferay-portal-master  File: AssertUtils.java View source code
public static void assertEquals(Blob expectedBlob, Blob actualBlob) throws Exception {
    try (InputStream expectInputStream = expectedBlob.getBinaryStream();
        InputStream actualInputStream = actualBlob.getBinaryStream()) {
        while (true) {
            int expectValue = expectInputStream.read();
            int actualValue = actualInputStream.read();
            assertEquals(expectValue, actualValue);
            if (expectValue == -1) {
                break;
            }
        }
    }
}
Example 90
Project: lucene-solr-master  File: FieldStreamDataSource.java View source code
@Override
public InputStream getData(String query) {
    Object o = wrapper.getVariableResolver().resolve(dataField);
    if (o == null) {
        throw new DataImportHandlerException(SEVERE, "No field available for name : " + dataField);
    } else if (o instanceof Blob) {
        Blob blob = (Blob) o;
        try {
            return blob.getBinaryStream();
        } catch (SQLException sqle) {
            LOG.info("Unable to get data from BLOB");
            return null;
        }
    } else if (o instanceof byte[]) {
        byte[] bytes = (byte[]) o;
        return new ByteArrayInputStream(bytes);
    } else {
        throw new RuntimeException("unsupported type : " + o.getClass());
    }
}
Example 91
Project: migration-tools-master  File: SimpleQueryFormat.java View source code
protected String format(Object parameter) {
    if (parameter == null) {
        return "NULL";
    }
    if (parameter instanceof Clob) {
        return "[CLOB]";
    } else if (parameter instanceof Blob) {
        return "[BLOB]";
    } else if (parameter instanceof Number) {
        return valueOf(parameter);
    } else {
        return "'" + valueOf(parameter) + "'";
    }
}
Example 92
Project: miso-lims-master  File: MisoJdbcUserDetailsManager.java View source code
public List<GrantedAuthority> extractData(ResultSet rs) throws SQLException {
    rs.next();
    List<GrantedAuthority> roleList = new ArrayList<GrantedAuthority>();
    Blob roleblob = rs.getBlob("authority");
    if (roleblob != null) {
        if (roleblob.length() > 0) {
            byte[] rbytes = roleblob.getBytes(1, (int) roleblob.length());
            String s1 = new String(rbytes);
            String[] roles = s1.split(",");
            for (String role : roles) {
                System.out.println("Found role " + role + " for " + rs.getString("username"));
                GrantedAuthorityImpl authority = new GrantedAuthorityImpl(role);
                roleList.add(authority);
            }
        } else {
            System.out.println("Cannot process user login - cannot extract roles from database");
        }
    }
    try {
        if (rs.getBoolean("admin"))
            roleList.add(new GrantedAuthorityImpl("ROLE_ADMIN"));
        if (rs.getBoolean("external"))
            roleList.add(new GrantedAuthorityImpl("ROLE_EXTERNAL"));
        if (rs.getBoolean("internal"))
            roleList.add(new GrantedAuthorityImpl("ROLE_INTERNAL"));
    } catch (SQLException e) {
        e.printStackTrace();
        log.warn("Couldn't retrieve a user property to convert to a role: " + e.getMessage());
    }
    if (roleList.isEmpty()) {
        log.warn("User has null roles. This may affect their ability to access MISO.");
    }
    return roleList;
}
Example 93
Project: monitoring-master  File: ObjectConverter.java View source code
private String getParameter(Object param) {
    if (param == null) {
        return "null";
    } else {
        if (param instanceof Byte) {
            return abbreviate(param);
        } else if (param instanceof String) {
            return abbreviate(param);
        } else if (param instanceof BigDecimal) {
            return abbreviate(param);
        } else if (param instanceof Short) {
            return abbreviate(param);
        } else if (param instanceof Integer) {
            return abbreviate(param);
        } else if (param instanceof Long) {
            return abbreviate(param);
        } else if (param instanceof Float) {
            return abbreviate(param);
        } else if (param instanceof Double) {
            return abbreviate(param);
        } else if (param instanceof BigInteger) {
            return abbreviate(param);
        } else if (param instanceof java.sql.Date) {
            return abbreviate(param);
        } else if (param instanceof Time) {
            return abbreviate(param);
        } else if (param instanceof Timestamp) {
            return abbreviate(param);
        } else if (param instanceof Boolean) {
            return abbreviate(param);
        } else if (param instanceof byte[]) {
            return ArrayUtils.abbreviate((byte[]) param);
        } else if (param instanceof InputStream) {
            return getClassName(param);
        } else if (param instanceof java.sql.Blob) {
            return getClassName(param);
        } else if (param instanceof java.sql.Clob) {
            return getClassName(param);
        } else {
            return getClassName(param);
        }
    }
}
Example 94
Project: Oceanus-master  File: LOBTypeCompiler.java View source code
/**
     * @see TypeCompiler#getCorrespondingPrimitiveTypeName
     */
public String getCorrespondingPrimitiveTypeName() {
    int formatId = getStoredFormatIdFromTypeId();
    switch(formatId) {
        case TypeId.FormatIds.BLOB_TYPE_ID:
            return "java.sql.Blob";
        default:
            assert false : "unexpected formatId in getCorrespondingPrimitiveTypeName() - " + formatId;
            return null;
    }
}
Example 95
Project: oddjob-master  File: HSQLAssumptionsTest.java View source code
/**
	 * Tests because HSQL Version 2 didn't look to support blobs as expected.
	 * <p>
	 * - Looks like they've been fixed in version 2.2.5
	 * 
	 * @author rob
	 *
	 */
public void testBytes() throws SQLException, ArooaConversionException {
    Connection connection = ct.toValue();
    PreparedStatement insert = connection.prepareStatement("insert into test (key, job_as_stream, job_as_bytes)" + " values (?, ?, ?)");
    Object job = new BigThing();
    byte[] bytes = new SerializeWithBytes().toBytes(job);
    logger.debug("Saving: " + bytes.length + " bytes.");
    insert.setString(1, "a");
    insert.setBlob(2, new SerializeWithBinaryStream().toStream(job));
    insert.setBytes(3, bytes);
    insert.executeUpdate();
    PreparedStatement select = connection.prepareStatement("select job_as_stream, job_as_bytes from test where key = ?");
    select.setString(1, "a");
    ResultSet rs = select.executeQuery();
    assertTrue(rs.next());
    byte[] bytesCopy = rs.getBytes(1);
    Object copy1 = new SerializeWithBytes().fromBytes(bytesCopy, getClass().getClassLoader());
    assertNotNull(copy1);
    Blob blob = rs.getBlob(2);
    Object copy2 = new SerializeWithBinaryStream().fromStream(blob.getBinaryStream(), getClass().getClassLoader());
    assertNotNull(copy2);
    insert.close();
    select.close();
    connection.close();
}
Example 96
Project: openclouddb-master  File: LOBTypeCompiler.java View source code
/**
     * @see TypeCompiler#getCorrespondingPrimitiveTypeName
     */
public String getCorrespondingPrimitiveTypeName() {
    int formatId = getStoredFormatIdFromTypeId();
    switch(formatId) {
        case TypeId.FormatIds.BLOB_TYPE_ID:
            return "java.sql.Blob";
        default:
            assert false : "unexpected formatId in getCorrespondingPrimitiveTypeName() - " + formatId;
            return null;
    }
}
Example 97
Project: orientdb-jdbc-master  File: OrientJdbcBlobTest.java View source code
@Test
public void shouldLoadBlob() throws SQLException, FileNotFoundException, IOException, NoSuchAlgorithmException {
    File binaryFile = getOutFile();
    String digest = this.calculateMD5checksum(ClassLoader.getSystemResourceAsStream("file.pdf"));
    PreparedStatement stmt = conn.prepareStatement("SELECT FROM Article WHERE uuid = 1 ");
    ResultSet rs = stmt.executeQuery();
    assertThat(rs.next(), is(true));
    rs.next();
    Blob blob = rs.getBlob("attachment");
    assertThat(blob, notNullValue());
    dumpBlobToFile(binaryFile, blob);
    assertTrue("The file '" + binaryFile.getName() + "' does not exist", binaryFile.exists());
    verifyMD5checksum(binaryFile, digest);
}
Example 98
Project: orientdb-master  File: OrientJdbcBlobTest.java View source code
@Test
public void shouldStoreBinaryStream() throws Exception {
    conn.createStatement().executeQuery("CREATE CLASS Blobs");
    PreparedStatement statement = conn.prepareStatement("INSERT INTO Blobs (uuid,attachment) VALUES (?,?)");
    statement.setInt(1, 1);
    statement.setBinaryStream(2, ClassLoader.getSystemResourceAsStream("file.pdf"));
    int rowsInserted = statement.executeUpdate();
    assertThat(rowsInserted).isEqualTo(1);
    //verify the blob
    PreparedStatement stmt = conn.prepareStatement("SELECT FROM Blobs WHERE uuid = 1 ");
    ResultSet rs = stmt.executeQuery();
    assertThat(rs.next()).isTrue();
    rs.next();
    Blob blob = rs.getBlob("attachment");
    verifyBlobAgainstFile(blob);
}
Example 99
Project: p6spy-master  File: P6TestResultSetWithBinary.java View source code
@Before
public void setup() throws SQLException {
    P6LogOptions.getActiveInstance().setExcludebinary(true);
    String update = "insert into img values (?, ?, ?)";
    PreparedStatement prep = getPreparedStatement(update);
    prep.setInt(1, 1000);
    prep.setBytes(2, "foo".getBytes(StandardCharsets.UTF_8));
    if (// java.sql.SQLFeatureNotSupportedException: Method org.postgresql.jdbc4.Jdbc4Connection.createBlob() is not yet implemented.
    //
    "PostgreSQL".equals(db) || // at org.firebirdsql.jdbc.FBBlob.setBytes(FBBlob.java:472)
    "Firebird".equals(//
    db) || // at com.p6spy.engine.wrapper.ConnectionWrapper.createBlob(ConnectionWrapper.java:315)
    "SQLite".equals(db)) {
        prep.setBytes(3, "foo".getBytes(StandardCharsets.UTF_8));
    } else {
        Blob data = connection.createBlob();
        data.setBytes(1, "foo".getBytes(StandardCharsets.UTF_8));
        prep.setBlob(3, data);
    }
    prep.execute();
    resultSet = executeQuery("select val from img where id=1000");
    P6LogOptions.getActiveInstance().setExcludecategories("info,debug,result");
    clearLogEntries();
    clearLastLogStackTrace();
}
Example 100
Project: perecoder-master  File: JsonTypeDescriptor.java View source code
@SuppressWarnings({ "unchecked" })
@Override
public <X> X unwrap(T value, Class<X> type, WrapperOptions options) {
    if (value == null) {
        return null;
    } else if (byte[].class.isAssignableFrom(type)) {
        return (X) toBytes(value);
    } else if (InputStream.class.isAssignableFrom(type)) {
        return (X) new ByteArrayInputStream(toBytes(value));
    } else if (BinaryStream.class.isAssignableFrom(type)) {
        return (X) new BinaryStreamImpl(toBytes(value));
    } else if (Blob.class.isAssignableFrom(type)) {
        return (X) options.getLobCreator().createBlob(toBytes(value));
    }
    throw unknownUnwrap(type);
}
Example 101
Project: pinpoint-master  File: ObjectConverter.java View source code
private String getParameter(Object param) {
    if (param == null) {
        return "null";
    } else {
        if (param instanceof Byte) {
            return abbreviate(param);
        } else if (param instanceof String) {
            return abbreviate(param);
        } else if (param instanceof BigDecimal) {
            return abbreviate(param);
        } else if (param instanceof Short) {
            return abbreviate(param);
        } else if (param instanceof Integer) {
            return abbreviate(param);
        } else if (param instanceof Long) {
            return abbreviate(param);
        } else if (param instanceof Float) {
            return abbreviate(param);
        } else if (param instanceof Double) {
            return abbreviate(param);
        } else if (param instanceof BigInteger) {
            return abbreviate(param);
        } else if (param instanceof java.sql.Date) {
            return abbreviate(param);
        } else if (param instanceof Time) {
            return abbreviate(param);
        } else if (param instanceof Timestamp) {
            return abbreviate(param);
        } else if (param instanceof Boolean) {
            return abbreviate(param);
        } else if (param instanceof byte[]) {
            return ArrayUtils.abbreviate((byte[]) param);
        } else if (param instanceof InputStream) {
            return getClassName(param);
        } else if (param instanceof java.sql.Blob) {
            return getClassName(param);
        } else if (param instanceof java.sql.Clob) {
            return getClassName(param);
        } else {
            return getClassName(param);
        }
    }
}