List of usage examples for java.sql Blob length
long length() throws SQLException;
From source file:com.playright.servlet.DataController.java
private static CoverageData getCoverageDateFromRequest(HttpServletRequest request) throws ServletException { CoverageData cd = new CoverageData(); try {// w w w. ja v a2 s . c o m if (!"".equalsIgnoreCase(request.getParameter("id")) && request.getParameter("id") != null) { cd.setId(Integer.parseInt(request.getParameter("id"))); } SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); java.util.Date ud = sdf.parse(request.getParameter("newsDate")); cd.setNewsDate(new java.sql.Date(ud.getTime())); cd.setNewspaper(request.getParameter("newspaper")); cd.setHeadline(request.getParameter("headline")); cd.setLanguage(request.getParameter("language")); cd.setEdition(request.getParameter("edition")); cd.setSupplement(request.getParameter("supplement")); cd.setSource(request.getParameter("source")); if (!"".equalsIgnoreCase(request.getParameter("pageNo")) && request.getParameter("pageNo") != null) { cd.setPageNo(Integer.parseInt(request.getParameter("pageNo"))); } if (!"".equalsIgnoreCase(request.getParameter("height")) && request.getParameter("height") != null) { cd.setHeight(Integer.parseInt(request.getParameter("height"))); } if (!"".equalsIgnoreCase(request.getParameter("width")) && request.getParameter("width") != null) { cd.setWidth(Integer.parseInt(request.getParameter("width"))); } if (!"".equalsIgnoreCase(request.getParameter("totalArticleSize")) && request.getParameter("totalArticleSize") != null) { cd.setTotalArticleSize(Integer.parseInt(request.getParameter("totalArticleSize"))); } if (!"".equalsIgnoreCase(request.getParameter("circulationFigure")) && request.getParameter("circulationFigure") != null) { cd.setCirculationFigure(Integer.parseInt(request.getParameter("circulationFigure"))); } if (!"".equalsIgnoreCase(request.getParameter("journalistFactor")) && request.getParameter("journalistFactor") != null) { cd.setJournalistFactor(Integer.parseInt(request.getParameter("journalistFactor"))); } if (!"".equalsIgnoreCase(request.getParameter("quantitativeAve")) && request.getParameter("quantitativeAve") != null) { cd.setQuantitativeAve(new BigDecimal(request.getParameter("quantitativeAve"))); } if (!"".equalsIgnoreCase(request.getParameter("imageExists")) && request.getParameter("imageExists") != null) { cd.setImageExists(request.getParameter("imageExists")); } Blob b = null; String fileName = ""; String contentType = ""; try { Part filePart = request.getPart("image"); InputStream fileContent = filePart.getInputStream(); byte[] bytes = IOUtils.toByteArray(fileContent); b = new SerialBlob(bytes); fileName = filePart.getSubmittedFileName(); contentType = filePart.getContentType(); } catch (IOException ex) { Logger.getLogger(DataController.class.getName()).log(Level.SEVERE, null, ex); } if (b != null && b.length() != 0) { cd.setImageBlob(b); cd.setImageFileName(fileName); cd.setImageType(contentType); } } catch (ParseException ex) { Logger.getLogger(DataController.class.getName()).log(Level.SEVERE, null, ex); } catch (SQLException ex) { Logger.getLogger(DataController.class.getName()).log(Level.SEVERE, null, ex); } return cd; }
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//from w ww. j ava2s . 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:eionet.cr.dao.readers.StagingDatabaseDTOReader.java
@Override public void readRow(ResultSet rs) throws SQLException, ResultSetReaderException { StagingDatabaseDTO databaseDTO = new StagingDatabaseDTO(); databaseDTO.setId(rs.getInt("DATABASE_ID")); databaseDTO.setName(rs.getString("NAME")); databaseDTO.setCreator(rs.getString("CREATOR")); databaseDTO.setCreated(rs.getTimestamp("CREATED")); databaseDTO.setDescription(rs.getString("DESCRIPTION")); databaseDTO.setImportStatus(Enum.valueOf(ImportStatus.class, rs.getString("IMPORT_STATUS"))); databaseDTO.setImportLog(rs.getString("IMPORT_LOG")); try {// ww w .j a v a 2s.co m Blob blob = rs.getBlob("DEFAULT_QUERY"); String query = blob == null ? null : blob.length() == 0 ? "" : IOUtils.toString(blob.getBinaryStream()); databaseDTO.setDefaultQuery(query); } catch (Exception e) { LOGGER.warn("Failed to read column: DEFAULT_QUERY", e); } resultList.add(databaseDTO); }
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 {/* ww w . j av a 2s. com*/ 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 {//from w ww. j av a2s . c om // 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:com.butler.service.ProductDao.java
public InputStream getImage(String product) { String sql = "select pic from product where name='" + product + "'"; return (InputStream) this.getJdbcTemplate().query(sql, new ResultSetExtractor() { public Object extractData(ResultSet rs) throws SQLException, DataAccessException { rs.next();/*w w w . j a v a2 s.c om*/ Blob imageBlob = rs.getBlob("pic"); InputStream binaryStream = imageBlob.getBinaryStream(1, imageBlob.length()); return binaryStream; } }); }
From source file:org.opencms.db.oracle.CmsSqlManager.java
/** * @see org.opencms.db.generic.CmsSqlManager#getBytes(java.sql.ResultSet, java.lang.String) *//* ww w .j av a 2 s .c om*/ @Override public byte[] getBytes(ResultSet res, String attributeName) throws SQLException { Blob blob = res.getBlob(attributeName); return blob.getBytes(1, (int) blob.length()); }
From source file:org.pentaho.di.jdbc.Support.java
/** * Embed the data object as a string literal in the buffer supplied. * * @param buf The buffer in which the data will be embeded. * @param value The data object.//from w ww . j av a2 s . co m * @param isUnicode Set to <code>true</code> if Unicode strings should be used, else <code>false</code>. * @param connection The {@link ConnectionJDBC3} object. */ static void embedData(StringBuffer buf, Object value, boolean isUnicode, ConnectionJDBC3 connection) throws SQLException { buf.append(' '); if (value == null) { buf.append("NULL "); return; } if (value instanceof Blob) { Blob blob = (Blob) value; value = blob.getBytes(1, (int) blob.length()); } else if (value instanceof Clob) { Clob clob = (Clob) value; value = clob.getSubString(1, (int) clob.length()); } if (value instanceof DateTime) { buf.append('\''); buf.append(value); buf.append('\''); } else if (value instanceof byte[]) { byte[] bytes = (byte[]) value; int len = bytes.length; if (len >= 0) { buf.append('0').append('x'); if (len == 0) { // Zero length binary values are not allowed buf.append('0').append('0'); } else { for (int i = 0; i < len; i++) { int b1 = bytes[i] & 0xFF; buf.append(hex[b1 >> 4]); buf.append(hex[b1 & 0x0F]); } } } } else if (value instanceof String) { String tmp = (String) value; int len = tmp.length(); if (isUnicode) { buf.append('N'); } buf.append('\''); for (int i = 0; i < len; i++) { char c = tmp.charAt(i); if (c == '\'') { buf.append('\''); } buf.append(c); } buf.append('\''); } else if (value instanceof java.sql.Date) { DateTime dt = new DateTime((java.sql.Date) value); buf.append('\''); buf.append(dt); buf.append('\''); } else if (value instanceof java.sql.Time) { DateTime dt = new DateTime((java.sql.Time) value); buf.append('\''); buf.append(dt); buf.append('\''); } else if (value instanceof java.sql.Timestamp) { DateTime dt = new DateTime((java.sql.Timestamp) value); buf.append('\''); buf.append(dt); buf.append('\''); } else if (value instanceof Boolean) { buf.append(((Boolean) value).booleanValue() ? '1' : '0'); } else if (value instanceof BigDecimal) { // // Ensure large decimal number does not overflow the // maximum precision of the server. // Main problem is with small numbers e.g. BigDecimal(1.0).toString() = // 0.1000000000000000055511151231.... // String tmp = value.toString(); int maxlen = connection.getMaxPrecision(); if (tmp.charAt(0) == '-') { maxlen++; } if (tmp.indexOf('.') >= 0) { maxlen++; } if (tmp.length() > maxlen) { buf.append(tmp.substring(0, maxlen)); } else { buf.append(tmp); } } else { buf.append(value.toString()); } buf.append(' '); }
From source file:com.ebay.pulsar.analytics.dao.mapper.BaseDBMapper.java
@SuppressWarnings("unchecked") @Override/* w ww. jav a 2 s.c o m*/ public T mapRow(ResultSet r, int index) throws SQLException { try { T obj = (T) clazz.newInstance(); if (obj == null) { return null; } try { BeanInfo beanInfo = Introspector.getBeanInfo(clazz); PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); for (PropertyDescriptor property : propertyDescriptors) { String key = property.getName(); if (!key.equals("class")) { Object value = null; try { Method setter = property.getWriteMethod(); value = r.getObject(key.toLowerCase()); if (value != null && value instanceof Number) { @SuppressWarnings("rawtypes") Class[] types = setter.getParameterTypes(); value = NumberUtils.convertNumberToTargetClass((Number) value, types[0]); } if (value != null) { if (value.getClass().equals(BigInteger.class)) { setter.invoke(obj, ((BigInteger) value).longValue()); } else if (value.getClass().equals(byte[].class)) { setter.invoke(obj, new String((byte[]) value)); } else if (Blob.class.isAssignableFrom(value.getClass())) { Blob bv = (Blob) value; byte[] b = new byte[(int) bv.length()]; InputStream stream = bv.getBinaryStream(); stream.read(b); stream.close(); String v = new String(b); setter.invoke(obj, v); } else { setter.invoke(obj, value); } } } catch (Exception e) { logger.error("transBean2Map Error " + e); logger.error("name[" + key + "]=" + (value == null ? "NULL" : value.toString()) + ", class:" + (value == null ? "NULL" : value.getClass()) + ", err:" + e.getMessage()); } } } } catch (Exception e) { logger.error("transBean2Map Error " + e); } return obj; } catch (Exception e) { logger.error("Exception:" + e); } return null; }