Java Code Examples for java.sql.Blob#length()
The following examples show how to use
java.sql.Blob#length() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ServerPreparedQueryBindings.java From FoxTelem with GNU General Public License v3.0 | 6 votes |
@Override public void setBlob(int parameterIndex, Blob x) { if (x == null) { setNull(parameterIndex); } else { try { ServerPreparedQueryBindValue binding = getBinding(parameterIndex, true); this.sendTypesToServer.compareAndSet(false, binding.resetToType(MysqlType.FIELD_TYPE_BLOB, this.numberOfExecutions)); binding.value = x; binding.isLongData = true; binding.bindLength = this.useStreamLengthsInPrepStmts.getValue() ? x.length() : -1; } catch (Throwable t) { throw ExceptionFactory.createException(t.getMessage(), t); } } }
Example 2
Source File: ServerPreparedStatement.java From r-course with MIT License | 6 votes |
/** * @see java.sql.PreparedStatement#setBlob(int, java.sql.Blob) */ @Override public void setBlob(int parameterIndex, Blob x) throws SQLException { synchronized (checkClosed().getConnectionMutex()) { if (x == null) { setNull(parameterIndex, java.sql.Types.BINARY); } else { BindValue binding = getBinding(parameterIndex, true); resetToType(binding, MysqlDefs.FIELD_TYPE_BLOB); binding.value = x; binding.isLongData = true; if (this.connection.getUseStreamLengthsInPrepStmts()) { binding.bindLength = x.length(); } else { binding.bindLength = -1; } } } }
Example 3
Source File: StdJDBCDelegate.java From lams with GNU General Public License v2.0 | 6 votes |
/** * <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); if (blobLocator != null && blobLocator.length() != 0) { InputStream binaryInput = blobLocator.getBinaryStream(); if (null != binaryInput) { if (binaryInput instanceof ByteArrayInputStream && ((ByteArrayInputStream) binaryInput).available() == 0 ) { //do nothing } else { ObjectInputStream in = new ObjectInputStream(binaryInput); try { obj = in.readObject(); } finally { in.close(); } } } } return obj; }
Example 4
Source File: LobHelper.java From netbeans with Apache License 2.0 | 6 votes |
public static String blobToString(Blob blob) { try { Long size = blob.length(); StringBuilder stringValue = new StringBuilder(); stringValue.append("<BLOB "); if (size < 1000) { stringValue.append(String.format("%1$d bytes", size)); } else if (size < 1000000) { stringValue.append(String.format("%1$d kB", size / 1000)); } else { stringValue.append(String.format("%1$d MB", size / 1000000)); } stringValue.append(">"); return stringValue.toString(); } catch (SQLException ex) { return "<BLOB of unkown size>"; } }
Example 5
Source File: MailTest.java From scada with MIT License | 6 votes |
@Test public void testMail() throws Exception{ ResultSet rs = MailDBOperation.getAll(); if(rs.next()){ rs.next(); Blob blob = rs.getBlob("message_attributes"); int bolblen = (int) blob.length(); byte[] data = blob.getBytes(1, bolblen); String content = new String(data); // MimeMessage msg = (MimeMessage) blob; // Part part = msg; // Multipart multipart = (Multipart) part.getContent(); // System.out.println(multipart.getBodyPart(1).getContent()); System.out.println(content); } }
Example 6
Source File: JDBCResourceStore.java From kylin-on-parquet-v2 with Apache License 2.0 | 5 votes |
private InputStream getInputStream(String resPath, ResultSet rs) throws SQLException, IOException { if (rs == null) { return null; } Blob blob = rs.getBlob(META_TABLE_CONTENT); if (blob == null || blob.length() == 0) { return openPushdown(resPath); // empty bytes is pushdown indicator } else { return blob.getBinaryStream(); } }
Example 7
Source File: BlobStreamingProcess.java From ameba with MIT License | 5 votes |
/** {@inheritDoc} */ @Override public long length(Blob entity) throws IOException { try { return entity.length(); } catch (SQLException e) { throw new IOException(e); } }
Example 8
Source File: ParameterMappingTest.java From gemfirexd-oss with Apache License 2.0 | 5 votes |
private void compareBlobs( Blob left, Blob right ) throws Exception { long leftLength = left.length(); long rightLength = right.length(); println( "Left blob has " + leftLength + " bytes and right blob has " + rightLength + " bytes." ); assertEquals( leftLength, rightLength ); if ( leftLength == rightLength ); { byte[] leftBytes = left.getBytes( 1L, (int) leftLength ); byte[] rightBytes = right.getBytes( 1L, (int) rightLength ); for ( int i = 0; i < leftLength; i++ ) { int leftIdx = (int) i; int rightIdx = (int) ((leftLength - leftIdx) - 1); byte leftC = leftBytes[ leftIdx ]; byte rightC = rightBytes[ rightIdx ]; if ( leftC != rightC ) { println( "left[ " + leftIdx+ " ] = " + leftC + " but right[ " + rightIdx + " ] = " + rightC ); return; } assertEquals( leftC, rightC ); } } }
Example 9
Source File: CacheDelegate.java From lams with GNU General Public License v2.0 | 5 votes |
/** * {@inheritDoc} * <p> * Caché requires {@code java.sql.Blob} instances to be explicitly freed. */ @Override protected Object getObjectFromBlob(ResultSet rs, String colName) throws ClassNotFoundException, IOException, SQLException { Blob blob = rs.getBlob(colName); if (blob == null) { return null; } else { try { if (blob.length() == 0) { return null; } else { InputStream binaryInput = blob.getBinaryStream(); if (binaryInput == null) { return null; } else if (binaryInput instanceof ByteArrayInputStream && ((ByteArrayInputStream) binaryInput).available() == 0 ) { return null; } else { ObjectInputStream in = new ObjectInputStream(binaryInput); try { return in.readObject(); } finally { in.close(); } } } } finally { blob.free(); } } }
Example 10
Source File: LOBLocatorReleaseTest.java From gemfirexd-oss with Apache License 2.0 | 5 votes |
/** * Tests that the LOB objects are not closed when closing the result set. * * @throws SQLException if something causes the test to fail */ public void testBlobClobStateAfterCloseOnScrollable() throws SQLException { getConnection().setAutoCommit(false); Statement stmt = createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); ResultSet rs = stmt.executeQuery( "select dBlob, dClob from LOBLOC_NO_NULLS"); rs.next(); rs.relative(5); Blob b = rs.getBlob(1); final long blobLength = b.length(); rs.next(); Clob c = rs.getClob(2); final long clobLength = c.length(); rs.first(); rs.close(); // The LOB objects should still be usable. assertEquals(blobLength, b.length()); assertEquals(clobLength, c.length()); commit(); try { // This should fail because the locator has been released. c.getSubString(1, 9); fail("Locator should have been released, causing the call to fail"); } catch (SQLException sqle) { assertSQLState("XJ215", sqle); } }
Example 11
Source File: EmpEmployeesDMLStmt.java From gemfirexd-oss with Apache License 2.0 | 5 votes |
protected int insertToTable(PreparedStatement stmt, int eid, String emp_name, int deptid, Date since, String addr, Blob picture, String ssn, int tid, boolean isPut) throws SQLException { String blob = null; if (picture != null) { if (picture.length() == 0) blob = "empty picture"; else blob = ResultSetHelper.convertByteArrayToString(picture.getBytes(1, (int)picture.length())); } String database = SQLHelper.isDerbyConn(stmt.getConnection())?"Derby - " :"gemfirexd - "; Log.getLogWriter().info(database + (isPut ? "putting" : "inserting") + " into emp.employees with EID:" + eid + ",EMPNAME:" + emp_name + ",DEPTID:" + deptid + ",SINCE:" + since + ",ADDR:" + addr + ",PICTURE:" + blob + ",SSN:" + ssn + ",TID:" + tid); stmt.setInt(1, eid); stmt.setString(2, emp_name); stmt.setInt(3, deptid); stmt.setDate(4, since); stmt.setString(5, addr); if (picture == null) stmt.setNull(6, Types.BLOB); else stmt.setBlob(6, picture); stmt.setString(7, ssn); stmt.setInt(8, tid); int rowCount = stmt.executeUpdate(); SQLWarning warning = stmt.getWarnings(); //test to see there is a warning if (warning != null) { SQLHelper.printSQLWarning(warning); } Log.getLogWriter().info(database + (isPut ? "put " : "inserted ") + rowCount + " rows into emp.employees EID:" + eid + ",EMPNAME:" + emp_name + ",DEPTID:" + deptid + ",SINCE:" + since + ",ADDR:" + addr + ",PICTURE:" + blob + ",SSN:" + ssn + ",TID:" + tid); return rowCount; }
Example 12
Source File: GFXDServiceImpl.java From gemfirexd-oss with Apache License 2.0 | 5 votes |
private BlobChunk handleBlob(Blob blob, ConnectionHolder connHolder, StatementAttrs attrs) throws SQLException { final long length = blob.length(); if (length > Integer.MAX_VALUE) { throw Util.generateCsSQLException(SQLState.BLOB_TOO_LARGE_FOR_CLIENT, Long.toString(length), Long.toString(Integer.MAX_VALUE)); } BlobChunk chunk = new BlobChunk().setOffset(0).setTotalLength(length); final int chunkSize; if (attrs != null && attrs.isSetLobChunkSize()) { chunkSize = attrs.lobChunkSize; } else { chunkSize = gfxdConstants.DEFAULT_LOB_CHUNKSIZE; } if (chunkSize > 0 && chunkSize < length) { chunk.setChunk(blob.getBytes(1, chunkSize)).setLast(false); // need to add explicit mapping for the LOB in this case int lobId; if (blob instanceof EngineLOB) { lobId = ((EngineLOB)blob).getLocator(); } else { lobId = connHolder.getConnection().addLOBMapping(blob); } chunk.setLobId(lobId); } else { chunk.setChunk(blob.getBytes(1, (int)length)).setLast(true); } return chunk; }
Example 13
Source File: JDBCBlob.java From evosql with Apache License 2.0 | 5 votes |
/** * Retrieves the byte position in the <code>BLOB</code> value * designated by this <code>Blob</code> object at which * <code>pattern</code> begins. The search begins at position * <code>start</code>. * * @param pattern the <code>Blob</code> object designating * the <code>BLOB</code> value for which to search * @param start the position in the <code>BLOB</code> value * at which to begin searching; the first position is 1 * @return the position at which the pattern begins, else -1 * @exception SQLException if there is an error accessing the * <code>BLOB</code> value or if start is less than 1 * @exception SQLFeatureNotSupportedException if the JDBC driver does not support * this method * @since JDK 1.2, HSQLDB 1.7.2 */ public long position(final Blob pattern, long start) throws SQLException { final byte[] data = getData(); final int dlen = data.length; if (start < MIN_POS) { throw JDBCUtil.outOfRangeArgument("start: " + start); } else if (start > dlen || pattern == null) { return -1L; } // by now, we know start <= Integer.MAX_VALUE; final int startIndex = (int) start - 1; final long plen = pattern.length(); if (plen == 0 || startIndex > ((long) dlen) - plen) { return -1L; } // by now, we know plen <= Integer.MAX_VALUE final int iplen = (int) plen; byte[] bytePattern; if (pattern instanceof JDBCBlob) { bytePattern = ((JDBCBlob) pattern).data(); } else { bytePattern = pattern.getBytes(1L, iplen); } final int result = KMPSearchAlgorithm.search(data, bytePattern, KMPSearchAlgorithm.computeTable(bytePattern), startIndex); return (result == -1) ? -1 : result + 1; }
Example 14
Source File: JDBCResourceStore.java From kylin with Apache License 2.0 | 5 votes |
private InputStream getInputStream(String resPath, ResultSet rs) throws SQLException, IOException { if (rs == null) { return null; } Blob blob = rs.getBlob(META_TABLE_CONTENT); if (blob == null || blob.length() == 0) { return openPushdown(resPath); // empty bytes is pushdown indicator } else { return blob.getBinaryStream(); } }
Example 15
Source File: BlobToByteConverter.java From SimpleFlatMapper with MIT License | 5 votes |
@Override public byte[] convert(Blob in, Context context) throws Exception { if (in != null) { long length = in.length(); if (length > Integer.MAX_VALUE) { throw new SQLException("Blob is too big to fit in an byte array length " + in.length()); } return in.getBytes(0, (int) length); } return null; }
Example 16
Source File: JDBCSequentialFileFactoryDriver.java From activemq-artemis with Apache License 2.0 | 5 votes |
/** * Reads data from the file (at file.readPosition) into the byteBuffer. * * @param file * @param bytes * @return * @throws SQLException */ public int readFromFile(JDBCSequentialFile file, ByteBuffer bytes) throws SQLException { synchronized (connection) { connection.setAutoCommit(false); readLargeObject.setLong(1, file.getId()); int readLength = 0; try (ResultSet rs = readLargeObject.executeQuery()) { if (rs.next()) { final Blob blob = rs.getBlob(1); if (blob != null) { final long blobLength = blob.length(); final int bytesRemaining = bytes.remaining(); final long filePosition = file.position(); readLength = (int) calculateReadLength(blobLength, bytesRemaining, filePosition); if (logger.isDebugEnabled()) { logger.debugf("trying read %d bytes: blobLength = %d bytesRemaining = %d filePosition = %d", readLength, blobLength, bytesRemaining, filePosition); } if (readLength < 0) { readLength = -1; } else if (readLength > 0) { byte[] data = blob.getBytes(file.position() + 1, readLength); bytes.put(data); } } } connection.commit(); return readLength; } catch (SQLException e) { connection.rollback(); throw e; } } }
Example 17
Source File: ParameterMappingTest.java From gemfirexd-oss with Apache License 2.0 | 5 votes |
private void compareBlobs( Blob left, Blob right ) throws Exception { long leftLength = left.length(); long rightLength = right.length(); println( "Left blob has " + leftLength + " bytes and right blob has " + rightLength + " bytes." ); assertEquals( leftLength, rightLength ); if ( leftLength == rightLength ); { byte[] leftBytes = left.getBytes( 1L, (int) leftLength ); byte[] rightBytes = right.getBytes( 1L, (int) rightLength ); for ( int i = 0; i < leftLength; i++ ) { int leftIdx = (int) i; int rightIdx = (int) ((leftLength - leftIdx) - 1); byte leftC = leftBytes[ leftIdx ]; byte rightC = rightBytes[ rightIdx ]; if ( leftC != rightC ) { println( "left[ " + leftIdx+ " ] = " + leftC + " but right[ " + rightIdx + " ] = " + rightC ); return; } assertEquals( leftC, rightC ); } } }
Example 18
Source File: LobLimitsTest.java From spliceengine with GNU Affero General Public License v3.0 | 4 votes |
/** * Basically this test will do an update using setBlob api - select row from * blobtbl and then update a row in blobtbl and verify updated data in * blobtbl * * @param ps select statement from which blob is retrieved * @param bloblen updating value is of length bloblen * @param id id of the row retrieved, for the update * @param updateId id of the row that is updated */ private void selectUpdateBlob(String testId, PreparedStatement ps, int bloblen, int id, int updateId) throws Exception { println("========================================"); println("START " + testId + " - select and then update blob of size= " + bloblen + " - Uses getBlob api"); ps.setInt(1, id); ResultSet rs = ps.executeQuery(); rs.next(); Blob value = rs.getBlob(1); long l = value.length(); long dlen = rs.getLong(2); assertEquals("FAIL - MISMATCH LENGTHS GOT " + l + " expected " + dlen + " for row in BLOBTBL with ID=" + id, dlen, l); PreparedStatement psUpd = prepareStatement("update BLOBTBL set content=?,dlen =?" + "where id = ?"); psUpd.setBlob(1, value); psUpd.setLong(2, l); psUpd.setInt(3, updateId); println("Rows Updated = " + psUpd.executeUpdate()); commit(); // now select and verify that update went through ok. ps.setInt(1, updateId); ResultSet rs2 = ps.executeQuery(); rs2.next(); Blob updatedValue = rs2.getBlob(1); assertEquals( "FAIL - Retrieving the updated blob length does not match " + "expected length = " + l + " found = " + updatedValue.length(), l, updatedValue.length()); commit(); // close resultsets rs.close(); rs2.close(); println("========================================"); }
Example 19
Source File: ConnectionMethodsTest.java From gemfirexd-oss with Apache License 2.0 | 4 votes |
/** * Test the createBlob method implementation in the Connection interface * * @exception SQLException, FileNotFoundException, Exception if error occurs */ public void testCreateBlob() throws SQLException, FileNotFoundException, IOException, Exception{ Connection conn = getConnection(); int b, c; Blob blob; Statement s = createStatement(); PreparedStatement ps = prepareStatement("insert into blobtable2 (n, blobcol)" + " values(?,?)"); ps.setInt(1,1000); blob = conn.createBlob(); try { is = (FileInputStream) AccessController.doPrivileged( new PrivilegedExceptionAction() { public Object run() throws FileNotFoundException { return new FileInputStream("extin/short.txt"); } }); } catch (PrivilegedActionException e) { // e.getException() should be an instance of FileNotFoundException, // as only "checked" exceptions will be "wrapped" in a // PrivilegedActionException. throw (FileNotFoundException) e.getException(); } OutputStream os = blob.setBinaryStream(1); ArrayList beforeUpdateList = new ArrayList(); int actualLength = 0; c = is.read(); while(c>0) { os.write(c); beforeUpdateList.add(c); c = is.read(); actualLength ++; } ps.setBlob(2, blob); ps.executeUpdate(); Statement stmt = createStatement(); ResultSet rs = stmt.executeQuery("select blobcol from blobtable2 where n = 1000"); assertTrue(rs.next()); blob = rs.getBlob(1); assertEquals(beforeUpdateList.size(), blob.length()); //Get the InputStream from this Blob. InputStream in = blob.getBinaryStream(); ArrayList afterUpdateList = new ArrayList(); b = in.read(); while (b > -1) { afterUpdateList.add(b); b = in.read(); } assertEquals(beforeUpdateList.size(), afterUpdateList.size()); //Now check if the two InputStreams //match for (int i = 0; i < blob.length(); i++) { assertEquals(beforeUpdateList.get(i), afterUpdateList.get(i)); } os.close(); is.close(); }
Example 20
Source File: TradePortfolioV1DMLStmt.java From gemfirexd-oss with Apache License 2.0 | 4 votes |
protected int insertToTable(PreparedStatement stmt, int cid, int sid, int qty, BigDecimal sub, Blob data, int tid, boolean isPut) throws SQLException { String blob = null; if (data != null) { if (data.length() == 0) blob = "empty data"; else if (useMD5Checksum) blob = ResultSetHelper.convertByteArrayToChecksum(data.getBytes(1, (int)data.length()), data.length()); else blob = ResultSetHelper.convertByteArrayToString(data.getBytes(1, (int)data.length())); } Log.getLogWriter().info((isPut ? "putting" : "inserting") + " into table trade.portfoliov1 cid is " + cid + " sid is "+ sid + " qty is " + qty + " availQty is " + qty + " subTotal is " + sub + " data is " + blob); String driverName = stmt.getConnection().getMetaData().getDriverName(); stmt.setInt(1, cid); stmt.setInt(2, sid); stmt.setInt(3, qty); stmt.setInt(4, qty); //availQty is the same as qty during insert stmt.setBigDecimal(5, sub); stmt.setInt(6, tid); stmt.setBlob(7, data); int rowCount = stmt.executeUpdate(); SQLWarning warning = stmt.getWarnings(); //test to see there is a warning if (warning != null) { SQLHelper.printSQLWarning(warning); } //doing second put that may or may not successfull. if ( driverName.toLowerCase().contains("gemfirexd") && isPut) { Log.getLogWriter().info((isPut ? "putting" : "inserting") + " into table trade.portfoliov1 cid is " + cid + " sid is "+ sid + " qty is " + qty + " availQty is " + qty + " subTotal is " + sub + " data is " + blob + " stmt " + stmt.toString()); rowCount = stmt.executeUpdate(); warning = stmt.getWarnings(); //test to see there is a warning if (warning != null) { SQLHelper.printSQLWarning(warning); } } return rowCount; }