List of usage examples for java.sql Blob getBytes
byte[] getBytes(long pos, int length) throws SQLException;
From source file:au.com.ish.derbydump.derbydump.metadata.Column.java
/** * this is a tricky one. according to/*w w w . ja va2 s . c om*/ <ul> <li>http://db.apache.org/derby/docs/10.2/ref/rrefjdbc96386.html</li> <li>http://stackoverflow.com/questions/7510112/how-to-make-java-ignore-escape-sequences-in-a-string</li> <li>http://dba.stackexchange.com/questions/10642/mysql-mysqldump-uses-n-instead-of-null</li> <li>http://stackoverflow.com/questions/12038814/import-hex-binary-data-into-mysql</li> <li>http://stackoverflow.com/questions/3126210/insert-hex-values-into-mysql</li> <li>http://www.xaprb.com/blog/2009/02/12/5-ways-to-make-hexadecimal-identifiers-perform-better-on-mysql/</li> </ul> and many others, there is no safer way of exporting blobs than separate data files or hex format.<br/> tested, mysql detects and imports hex encoded fields automatically. * @param blob Blob which we will convert to hex encoded string * @return String representation of binary data */ public static String processBinaryData(Blob blob) throws SQLException { if (blob == null) { return "NULL"; } int blobLength = (int) blob.length(); if (blobLength == 0) { return "NULL"; } byte[] bytes = blob.getBytes(1L, blobLength); return "0x" + new String(Hex.encodeHex(bytes)).toUpperCase(); }
From source file:org.springframework.jdbc.support.JdbcUtils.java
/** * Retrieve a JDBC column value from a ResultSet, using the most appropriate * value type. The returned value should be a detached value object, not having * any ties to the active ResultSet: in particular, it should not be a Blob or * Clob object but rather a byte array or String representation, respectively. * <p>Uses the {@code getObject(index)} method, but includes additional "hacks" * to get around Oracle 10g returning a non-standard object for its TIMESTAMP * datatype and a {@code java.sql.Date} for DATE columns leaving out the * time portion: These columns will explicitly be extracted as standard * {@code java.sql.Timestamp} object.//from www . j a v a 2 s .co m * @param rs is the ResultSet holding the data * @param index is the column index * @return the value object * @throws SQLException if thrown by the JDBC API * @see java.sql.Blob * @see java.sql.Clob * @see java.sql.Timestamp */ @Nullable public static Object getResultSetValue(ResultSet rs, int index) throws SQLException { Object obj = rs.getObject(index); String className = null; if (obj != null) { className = obj.getClass().getName(); } if (obj instanceof Blob) { Blob blob = (Blob) obj; obj = blob.getBytes(1, (int) blob.length()); } else if (obj instanceof Clob) { Clob clob = (Clob) obj; obj = clob.getSubString(1, (int) clob.length()); } else if ("oracle.sql.TIMESTAMP".equals(className) || "oracle.sql.TIMESTAMPTZ".equals(className)) { obj = rs.getTimestamp(index); } else if (className != null && className.startsWith("oracle.sql.DATE")) { String metaDataClassName = rs.getMetaData().getColumnClassName(index); if ("java.sql.Timestamp".equals(metaDataClassName) || "oracle.sql.TIMESTAMP".equals(metaDataClassName)) { obj = rs.getTimestamp(index); } else { obj = rs.getDate(index); } } else if (obj instanceof java.sql.Date) { if ("java.sql.Timestamp".equals(rs.getMetaData().getColumnClassName(index))) { obj = rs.getTimestamp(index); } } return obj; }
From source file:org.agnitas.backend.StringOps.java
/** * Converts a DB blob into a string/*w w w . j ava 2 s.co m*/ * * @param blob * the source * @param encoding * the encoding of the blob * @return the extracted string */ public static String blob2string(Blob blob, String encoding) throws SQLException { String rc; try { rc = blob == null ? "" : new String(blob.getBytes(1, (int) blob.length()), encoding); } catch (UnsupportedEncodingException e) { rc = null; } return rc; }
From source file:com.trackplus.ddl.DataReader.java
private static int getBlobTableData(BufferedWriter writer, Connection connection) throws DDLException { try {/* w ww .java 2 s . co m*/ Statement st = connection.createStatement(); ResultSet rs = st.executeQuery("SELECT * FROM TBLOB"); int idx = 0; while (rs.next()) { StringBuilder line = new StringBuilder(); //OBJECTID String value = rs.getString("OBJECTID"); line.append(value).append(","); //BLOBVALUE Blob blobValue = rs.getBlob("BLOBVALUE"); if (blobValue != null) { String str = new String(Base64.encodeBase64(blobValue.getBytes(1l, (int) blobValue.length()))); if (str.length() == 0) { str = " "; } line.append(str); } else { line.append("null"); } line.append(","); //TPUUID value = rs.getString("TPUUID"); line.append(value); writer.write(line.toString()); writer.newLine(); idx++; } rs.close(); return idx; } catch (SQLException ex) { throw new DDLException(ex.getMessage(), ex); } catch (IOException ex) { throw new DDLException(ex.getMessage(), ex); } }
From source file:com.xqdev.sql.MLSQL.java
private static void addResultSet(Element root, ResultSet rs) throws SQLException { Namespace sql = root.getNamespace(); ResultSetMetaData rsmd = rs.getMetaData(); int columnCount = rsmd.getColumnCount(); while (rs.next()) { Element tuple = new Element("tuple", sql); for (int i = 1; i <= columnCount; i++) { String colName = rsmd.getColumnName(i); // names aren't guaranteed OK in xml String colTypeName = rsmd.getColumnTypeName(i); // Decode a BLOB if one is found and place it into the result as a encoded Base 64 string String colValue = ""; if ("BLOB".equalsIgnoreCase(colTypeName)) { Blob b = rs.getBlob(i); if (b != null && b.length() > 0) { Base64 b64 = new Base64(); String b64Blob = b64.encodeBase64String(b.getBytes(1, (int) b.length())); colValue = b64Blob; } else colValue = ""; } else { colValue = rs.getString(i); }/*from www. j av a 2 s . c o m*/ boolean wasNull = rs.wasNull(); Element elt = new Element(colName); if (wasNull) { elt.setAttribute("null", "true"); } if ("UNKNOWN".equalsIgnoreCase(colTypeName)) { tuple.addContent(elt.setText("UNKNOWN TYPE")); // XXX ugly } else { tuple.addContent(elt.setText(colValue)); } } root.addContent(tuple); } }
From source file:org.pentaho.di.jdbc.Support.java
/** * Converts a LOB to the equivalent Java type, i.e. <code>Clob</code> to * <code>String</code> and <code>Blob</code> to <code>byte[]</code>. If the * value passed is not a LOB object, it is left unchanged and no exception * is thrown; the idea is to transparently convert only LOBs. * * @param value an object that may be a LOB * @return if the value was a LOB, the equivalent Java object, otherwise * the original value// w w w.java 2 s. c o m * @throws SQLException if an error occurs while reading the LOB contents */ public static Object convertLOB(Object value) throws SQLException { if (value instanceof Clob) { Clob c = (Clob) value; return c.getSubString(1, (int) c.length()); } if (value instanceof Blob) { Blob b = (Blob) value; return b.getBytes(1, (int) b.length()); } return value; }
From source file:com.siemens.scr.avt.ad.hibernate.BinaryBlobType.java
public Object nullSafeGet(ResultSet rs, String[] names, Object owner) throws HibernateException, SQLException { Blob blob = rs.getBlob(names[0]); return blob.getBytes(1, (int) blob.length()); }
From source file:cognition.pipeline.data.helper.BlobHelper.java
private byte[] getBytesFromSerializableBlob(Object serializableBlobProxy) { SerializableBlobProxy blobProxy = (SerializableBlobProxy) Proxy.getInvocationHandler(serializableBlobProxy); Blob wrappedBlob = blobProxy.getWrappedBlob(); try {//from w w w .j a v a 2s . c om byte[] bytes = wrappedBlob.getBytes(1, (int) wrappedBlob.length()); if (bytes != null) { if (bytes.length == 0) { return null; } } return bytes; } catch (SQLException e) { e.printStackTrace(); } return null; }
From source file:org.moqui.impl.entity.EntityJavaUtil.java
public static void setPreparedStatementValue(PreparedStatement ps, int index, Object value, FieldInfo fi, boolean useBinaryTypeForBlob, EntityFacade efi) throws EntityException { try {// ww w .ja v a 2 s . c o m // allow setting, and searching for, String values for all types; JDBC driver should handle this okay if (value instanceof CharSequence) { ps.setString(index, value.toString()); } else { switch (fi.typeValue) { case 1: if (value != null) { ps.setString(index, value.toString()); } else { ps.setNull(index, Types.VARCHAR); } break; case 2: if (value != null) { Class valClass = value.getClass(); if (valClass == Timestamp.class) { ps.setTimestamp(index, (Timestamp) value, efi.getCalendarForTzLc()); } else if (valClass == java.sql.Date.class) { ps.setDate(index, (java.sql.Date) value, efi.getCalendarForTzLc()); } else if (valClass == java.util.Date.class) { ps.setTimestamp(index, new Timestamp(((java.util.Date) value).getTime()), efi.getCalendarForTzLc()); } else { throw new IllegalArgumentException("Class " + valClass.getName() + " not allowed for date-time (Timestamp) fields, for field " + fi.entityName + "." + fi.name); } } else { ps.setNull(index, Types.TIMESTAMP); } break; case 3: Time tm = (Time) value; // logger.warn("=================== setting time tm=${tm} tm long=${tm.getTime()}, cal=${cal}") if (value != null) { ps.setTime(index, tm, efi.getCalendarForTzLc()); } else { ps.setNull(index, Types.TIME); } break; case 4: if (value != null) { Class valClass = value.getClass(); if (valClass == java.sql.Date.class) { java.sql.Date dt = (java.sql.Date) value; // logger.warn("=================== setting date dt=${dt} dt long=${dt.getTime()}, cal=${cal}") ps.setDate(index, dt, efi.getCalendarForTzLc()); } else if (valClass == Timestamp.class) { ps.setDate(index, new java.sql.Date(((Timestamp) value).getTime()), efi.getCalendarForTzLc()); } else if (valClass == java.util.Date.class) { ps.setDate(index, new java.sql.Date(((java.util.Date) value).getTime()), efi.getCalendarForTzLc()); } else { throw new IllegalArgumentException("Class " + valClass.getName() + " not allowed for date fields, for field " + fi.entityName + "." + fi.name); } } else { ps.setNull(index, Types.DATE); } break; case 5: if (value != null) { ps.setInt(index, ((Number) value).intValue()); } else { ps.setNull(index, Types.NUMERIC); } break; case 6: if (value != null) { ps.setLong(index, ((Number) value).longValue()); } else { ps.setNull(index, Types.NUMERIC); } break; case 7: if (value != null) { ps.setFloat(index, ((Number) value).floatValue()); } else { ps.setNull(index, Types.NUMERIC); } break; case 8: if (value != null) { ps.setDouble(index, ((Number) value).doubleValue()); } else { ps.setNull(index, Types.NUMERIC); } break; case 9: if (value != null) { Class valClass = value.getClass(); // most common cases BigDecimal, Double, Float; then allow any Number if (valClass == BigDecimal.class) { ps.setBigDecimal(index, (BigDecimal) value); } else if (valClass == Double.class) { ps.setDouble(index, (Double) value); } else if (valClass == Float.class) { ps.setFloat(index, (Float) value); } else if (value instanceof Number) { ps.setDouble(index, ((Number) value).doubleValue()); } else { throw new IllegalArgumentException("Class " + valClass.getName() + " not allowed for number-decimal (BigDecimal) fields, for field " + fi.entityName + "." + fi.name); } } else { ps.setNull(index, Types.NUMERIC); } break; case 10: if (value != null) { ps.setBoolean(index, (Boolean) value); } else { ps.setNull(index, Types.BOOLEAN); } break; case 11: if (value != null) { try { ByteArrayOutputStream os = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(os); oos.writeObject(value); oos.close(); byte[] buf = os.toByteArray(); os.close(); ByteArrayInputStream is = new ByteArrayInputStream(buf); ps.setBinaryStream(index, is, buf.length); is.close(); } catch (IOException ex) { throw new EntityException( "Error setting serialized object, for field " + fi.entityName + "." + fi.name, ex); } } else { if (useBinaryTypeForBlob) { ps.setNull(index, Types.BINARY); } else { ps.setNull(index, Types.BLOB); } } break; case 12: if (value instanceof byte[]) { ps.setBytes(index, (byte[]) value); /* } else if (value instanceof ArrayList) { ArrayList valueAl = (ArrayList) value; byte[] theBytes = new byte[valueAl.size()]; valueAl.toArray(theBytes); ps.setBytes(index, theBytes); */ } else if (value instanceof ByteBuffer) { ByteBuffer valueBb = (ByteBuffer) value; ps.setBytes(index, valueBb.array()); } else if (value instanceof Blob) { Blob valueBlob = (Blob) value; // calling setBytes instead of setBlob // ps.setBlob(index, (Blob) value) // Blob blb = value ps.setBytes(index, valueBlob.getBytes(1, (int) valueBlob.length())); } else { if (value != null) { throw new IllegalArgumentException("Type not supported for BLOB field: " + value.getClass().getName() + ", for field " + fi.entityName + "." + fi.name); } else { if (useBinaryTypeForBlob) { ps.setNull(index, Types.BINARY); } else { ps.setNull(index, Types.BLOB); } } } break; case 13: if (value != null) { ps.setClob(index, (Clob) value); } else { ps.setNull(index, Types.CLOB); } break; case 14: if (value != null) { ps.setTimestamp(index, (Timestamp) value); } else { ps.setNull(index, Types.TIMESTAMP); } break; // TODO: is this the best way to do collections and such? case 15: if (value != null) { ps.setObject(index, value, Types.JAVA_OBJECT); } else { ps.setNull(index, Types.JAVA_OBJECT); } break; } } } catch (SQLException sqle) { throw new EntityException("SQL Exception while setting value [" + value + "](" + (value != null ? value.getClass().getName() : "null") + "), type " + fi.type + ", for field " + fi.entityName + "." + fi.name + ": " + sqle.toString(), sqle); } catch (Exception e) { throw new EntityException( "Error while setting value for field " + fi.entityName + "." + fi.name + ": " + e.toString(), e); } }
From source file:org.opencms.db.oracle.CmsSqlManager.java
/** * @see org.opencms.db.generic.CmsSqlManager#getBytes(java.sql.ResultSet, java.lang.String) *//*from w ww. ja v a 2 s . c o m*/ @Override public byte[] getBytes(ResultSet res, String attributeName) throws SQLException { Blob blob = res.getBlob(attributeName); return blob.getBytes(1, (int) blob.length()); }