Java Sql Blob Inputstream Example

Java Code Examples for java.sql.Blob

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project Arecibo, under directory /util/src/main/java/com/ning/arecibo/util/jdbi/.

Source file: EfficientBlobMapper.java

29

vote

public byte[] map(int index,ResultSet rs,StatementContext ctx) throws SQLException {   Blob blob=null;   try {     blob=rs.getBlob(columnName);     return getBytes(blob);   }   finally {     if (blob != null) {       blob.free();     }   } }            

Example 2

From project Bifrost, under directory /src/main/java/com/craftfire/bifrost/scripts/forum/.

Source file: XenForo.java

28

vote

@Override public boolean authenticate(String username,String password){   Blob hashBlob=this.getDataManager().getBlobField("user_authenticate","data","`user_id` = '" + getUserID(username) + "'");   String hash="", salt="";   if (hashBlob != null) {     int offset=-1;     int chunkSize=1024;     StringBuilder stringBuffer=new StringBuilder();     try {       long blobLength=hashBlob.length();       if (chunkSize > blobLength) {         chunkSize=(int)blobLength;       }       char buffer[]=new char[chunkSize];       Reader reader=new InputStreamReader(hashBlob.getBinaryStream());       while ((offset=reader.read(buffer)) != -1) {         stringBuffer.append(buffer,0,offset);       }     }  catch (    IOException e) {       this.getLoggingManager().stackTrace(e);     } catch (    SQLException e) {       this.getLoggingManager().stackTrace(e);     }     String cache=stringBuffer.toString();     hash=CraftCommons.forumCacheValue(cache,"hash");     salt=CraftCommons.forumCacheValue(cache,"salt");   }   return hashPassword(salt,password).equals(hash); }            

Example 3

From project Openbravo-POS-iPhone-App, under directory /OpenbravoPOS_PDA/src-pda/com/openbravo/pos/pda/dao/.

Source file: ProductDAO.java

28

vote

@Override protected ProductInfo map2VO(ResultSet rs) throws SQLException {   ProductInfo product=new ProductInfo();   product.setId(rs.getString("id"));   product.setRef(rs.getString("reference"));   product.setCode(rs.getString("code"));   product.setName(rs.getString("name"));   product.setPriceBuy(rs.getDouble("pricebuy"));   product.setPriceSell(rs.getDouble("pricesell"));   product.setCategoryId(rs.getString("category"));   product.setTaxcat(rs.getString("taxcat"));   product.setCom(rs.getBoolean("iscom"));   product.setScale(rs.getBoolean("isscale"));   Blob blob=rs.getBlob("attributes");   if (blob != null) {     InputStreamReader reader=new InputStreamReader(blob.getBinaryStream());     Properties p=new Properties();     try {       p.load(reader);       product.setAttributes(p);     }  catch (    IOException ex) {       Logger.getLogger(ProductDAO.class.getName()).log(Level.SEVERE,null,ex);     }   }   return product; }            

Example 4

From project bonecp, under directory /bonecp/src/main/java/com/jolbox/bonecp/.

Source file: ConnectionHandle.java

27

vote

@Override public Blob createBlob() throws SQLException {   Blob result=null;   checkClosed();   try {     result=this.connection.createBlob();   }  catch (  SQLException e) {     throw markPossiblyBroken(e);   }   return result; }            

Example 5

From project core_5, under directory /exo.core.component.database/src/main/java/org/exoplatform/services/database/.

Source file: ReflectionMapper.java

27

vote

private synchronized byte[] loadBlob(ResultSet resultSet,String name) throws Exception {   Blob clob=resultSet.getBlob(name);   if (clob == null)   return null;   ByteArrayOutputStream output=loadInputStream(clob.getBinaryStream());   return output.toByteArray(); }            

Example 6

From project CraftCommons, under directory /src/test/java/com/craftfire/commons/.

Source file: DbTest_H2.java

27

vote

public static void runTest2(String field){   boolean b=datamanager.getBooleanField("typetest",field,"1");   printResult("getBooleanField",b,b);   String s=datamanager.getBinaryField("typetest",field,"1");   printResult("getBinaryField",s);   Blob blob=datamanager.getBlobField("typetest",field,"1");   printResult("getBlobField",blob);   Date date=datamanager.getDateField("typetest",field,"1");   printResult("getDateField",date);   double d=datamanager.getDoubleField("typetest",field,"1");   printResult("getDoubleField",d != 0,d);   int i=datamanager.getIntegerField("typetest",field,"1");   printResult("getIntegerField",i != 0,i);   s=datamanager.getStringField("typetest",field,"1");   printResult("getStringField",s); }            

Example 7

From project servicemix-utils, under directory /src/main/java/org/apache/servicemix/jdbc/adapter/.

Source file: OracleJDBCAdapter.java

27

vote

protected byte[] getBinaryData(ResultSet rs,int index) throws SQLException {   Blob aBlob=rs.getBlob(index);   if (aBlob == null) {     return null;   }   return aBlob.getBytes(1,(int)aBlob.length()); }            

Example 8

From project zanata, under directory /zanata-war/src/main/java/org/zanata/rest/service/.

Source file: FileService.java

27

vote

private void saveUploadPart(DocumentFileUploadForm uploadForm,HDocumentUpload upload) throws IOException {   Blob partContent;   partContent=Hibernate.createBlob(uploadForm.getFileStream());   HDocumentUploadPart newPart=new HDocumentUploadPart();   newPart.setContent(partContent);   upload.getParts().add(newPart);   session.saveOrUpdate(upload);   session.flush(); }            

Example 9

From project guj.com.br, under directory /src/net/jforum/dao/oracle/.

Source file: OracleUtils.java

26

vote

public static String readBlobUTF16BinaryStream(ResultSet rs,String fieldName) throws SQLException {   try {     Blob clob=rs.getBlob(fieldName);     InputStream is=clob.getBinaryStream();     StringBuffer sb=new StringBuffer();     int readedBytes;     int bufferSize=4096;     do {       byte[] bytes=new byte[bufferSize];       readedBytes=is.read(bytes);       if (readedBytes > 0) {         String readed=new String(bytes,0,readedBytes,"UTF-16");         sb.append(readed);       }     }  while (readedBytes == bufferSize);     is.close();     return sb.toString();   }  catch (  IOException e) {     throw new DatabaseException(e);   } }            

Example 10

From project jforum2, under directory /src/net/jforum/dao/oracle/.

Source file: OracleUtils.java

26

vote

public static String readBlobUTF16BinaryStream(ResultSet rs,String fieldName) throws SQLException {   try {     Blob clob=rs.getBlob(fieldName);     InputStream is=clob.getBinaryStream();     StringBuffer sb=new StringBuffer();     int readedBytes;     int bufferSize=4096;     do {       byte[] bytes=new byte[bufferSize];       readedBytes=is.read(bytes);       if (readedBytes > 0) {         String readed=new String(bytes,0,readedBytes,"UTF-16");         sb.append(readed);       }     }  while (readedBytes == bufferSize);     is.close();     return sb.toString();   }  catch (  IOException e) {     throw new DatabaseException(e);   } }            

Example 11

@Override protected List<GrantedAuthority> loadUserAuthorities(String username){   return ((List<GrantedAuthority>)getJdbcTemplate().query(getAuthoritiesByUsernameQuery(),new String[]{username},new ResultSetExtractor<List<GrantedAuthority>>(){     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 12

From project nevernote, under directory /src/cx/fbn/nevernote/sql/driver/.

Source file: NSqlQuery.java

26

vote

public byte[] getBlob(int position){   Blob dataBinary;   try {     dataBinary=resultSet.getBlob(position + 1);     byte[] b;     if (dataBinary == null)     return null;     b=dataBinary.getBytes(1,(int)dataBinary.length());     return b;   }  catch (  SQLException e) {     e.printStackTrace();     lastError=e.getMessage();   }   return null; }            

Example 13

From project scooter, under directory /source/src/com/scooterframework/orm/sqldataexpress/vendor/.

Source file: DBAdapter.java

26

vote

public Object getObjectFromResultSetByType(ResultSet rs,String javaClassType,int sqlDataType,int index) throws SQLException {   Object theObj=null;   if ("java.sql.Timestamp".equals(javaClassType) || "java.sql.Date".equals(javaClassType) || sqlDataType == 91 || sqlDataType == 93) {     theObj=rs.getTimestamp(index);   }  else   if (sqlDataType == Types.BLOB) {     try {       Blob blob=rs.getBlob(index);       return getBlobData(blob);     }  catch (    Exception ex) {       throw new SQLException(ex.getMessage());     }   }  else   if (sqlDataType == Types.CLOB) {     try {       Clob clob=rs.getClob(index);       return getClobData(clob);     }  catch (    Exception ex) {       throw new SQLException(ex.getMessage());     }   }  else {     theObj=rs.getObject(index);   }   return theObj; }            

Example 14

From project Solbase-Solr, under directory /contrib/dataimporthandler/src/main/java/org/apache/solr/handler/dataimport/.

Source file: FieldReaderDataSource.java

26

vote

public Reader getData(String query){   Object o=entityProcessor.getVariableResolver().resolve(dataField);   if (o == null) {     throw new DataImportHandlerException(SEVERE,"No field available for name : " + dataField);   }   if (o instanceof String) {     return new StringReader((String)o);   }  else   if (o instanceof Clob) {     Clob clob=(Clob)o;     try {       return readCharStream(clob);     }  catch (    Exception e) {       LOG.info("Unable to get data from CLOB");       return null;     }   }  else   if (o instanceof Blob) {     Blob blob=(Blob)o;     try {       Method m=blob.getClass().getDeclaredMethod("getBinaryStream");       if (Modifier.isPublic(m.getModifiers())) {         return getReader(m,blob);       }  else {         m.setAccessible(true);         return getReader(m,blob);       }     }  catch (    Exception e) {       LOG.info("Unable to get data from BLOB");       return null;     }   }  else {     return new StringReader(o.toString());   } }            

Example 15

/**   * Actually read a BlobRef instance from the ResultSet and materialize the data either inline or to a file.  * @param colNum the column of the ResultSet's current row to read.  * @param r the ResultSet to read from.  * @return a BlobRef encapsulating the data in this field.  * @throws IOException if an error occurs writing to the FileSystem.  * @throws SQLException if an error occurs reading from the database.  */ public com.cloudera.sqoop.lib.BlobRef readBlobRef(int colNum,ResultSet r) throws IOException, InterruptedException, SQLException {   long maxInlineLobLen=conf.getLong(MAX_INLINE_LOB_LEN_KEY,DEFAULT_MAX_LOB_LENGTH);   Blob b=r.getBlob(colNum);   if (null == b) {     return null;   }  else   if (b.length() > maxInlineLobLen) {     long len=b.length();     LobFile.Writer lobWriter=getBlobWriter();     long recordOffset=lobWriter.tell();     InputStream is=null;     OutputStream os=lobWriter.writeBlobRecord(len);     try {       is=b.getBinaryStream();       copyAll(is,os);     }   finally {       if (null != os) {         os.close();       }       if (null != is) {         is.close();       }       lobWriter.finishRecord();     }     return new com.cloudera.sqoop.lib.BlobRef(getRelativePath(curBlobWriter),recordOffset,len);   }  else {     return new com.cloudera.sqoop.lib.BlobRef(b.getBytes(1,(int)b.length()));   } }            

Example 16

From project tempo, under directory /wds-service/src/main/java/org/intalio/tempo/workflow/wds/core/.

Source file: JdbcItemDaoConnection.java

26

vote

public Item retrieveItem(String uri) throws UnavailableItemException {   if (!itemExists(uri)) {     throw new UnavailableItemException("Item with URI '" + uri + "' does not exist.");   }  else {     try {       _retrieveStatement.setString(1,uri);       ResultSet resultSet=_retrieveStatement.executeQuery();       resultSet.next();       int i=1;       String contentType=resultSet.getString(i++);       Blob dataBlob=resultSet.getBlob(i++);       return new Item(uri,contentType,dataBlob.getBytes(1,(int)dataBlob.length()));     }  catch (    SQLException e) {       throw new RuntimeException(e);     }   } }            

Example 17

private Object readBlob(Object o){   try {     Blob b=(Blob)o;     BufferedImage bi=ImageIO.read(b.getBinaryStream());     if (bi == null) {       return o;     }     ImageIcon ii=new ImageIcon(bi);     return ii;   }  catch (  Exception e) {     Uniquery.rti().println(e.getMessage());     return o;   } }            

Example 18

From project Amoeba-for-Aladdin, under directory /src/java/com/meidusa/amoeba/jdbc/.

Source file: ConnectionWrapper.java

24

vote

public Blob createBlob() throws SQLException {   if (JVM.is16()) {     return invoke(conn,Blob.class,"createBlob",(Object[])null,(Class[])null);   }  else {     throw new UnsupportedOperationException();   } }            

Example 19

From project hbase-dsl, under directory /src/main/java/com/nearinfinity/hbase/dsl/types/.

Source file: BlobConverter.java

24

vote

@Override public Blob fromBytes(byte[] t){   try {     return new SerialBlob(t);   }  catch (  SerialException e) {     throw new RuntimeException(e);   } catch (  SQLException e) {     throw new RuntimeException(e);   } }            

Example 20

public void setBlob(int parameterIndex,Blob x){   checkRange(parameterIndex);   try {     values[parameterIndex - 1]=x.getBytes(0,(int)x.length());   }  catch (  SQLException e) {     throw new RuntimeException(e);   } }            

Example 21

From project iciql, under directory /src/com/iciql/.

Source file: Query.java

23

vote

@SuppressWarnings("unchecked") private <X>List<X> selectSimple(X x,boolean distinct){   SQLStatement stat=getSelectStatement(distinct);   appendSQL(stat,null,x);   appendFromWhere(stat);   ResultSet rs=stat.executeQuery();   List<X> result=Utils.newArrayList();   try {     while (rs.next()) {       X value;       Object o=rs.getObject(1);       if (Clob.class.isAssignableFrom(o.getClass())) {         value=(X)Utils.convert(o,String.class);       }  else       if (Blob.class.isAssignableFrom(o.getClass())) {         value=(X)Utils.convert(o,byte[].class);       }  else {         value=(X)o;       }       result.add(value);     }   }  catch (  Exception e) {     throw IciqlException.fromSQL(stat.getSQL(),e);   }  finally {     JdbcUtils.closeSilently(rs,true);   }   return result; }            

Example 22

From project JGit, under directory /org.spearce.egit.ui/src/org/spearce/egit/ui/internal/components/.

Source file: RefContentProposal.java

23

vote

public String getDescription(){   if (objectId == null)   return null;   final Object obj;   try {     obj=db.mapObject(objectId,refName);   }  catch (  IOException e) {     Activator.logError("Unable to read object " + objectId + " for content proposal assistance",e);     return null;   }   final StringBuilder sb=new StringBuilder();   sb.append(refName);   sb.append('\n');   sb.append(objectId.abbreviate(db).name());   sb.append(" - ");   if (obj instanceof Commit) {     final Commit c=((Commit)obj);     appendObjectSummary(sb,"commit",c.getAuthor(),c.getMessage());   }  else   if (obj instanceof Tag) {     final Tag t=((Tag)obj);     appendObjectSummary(sb,"tag",t.getAuthor(),t.getMessage());   }  else   if (obj instanceof Tree) {     sb.append("tree");   }  else   if (obj instanceof Blob) {     sb.append("blob");   }  else   sb.append("locally unknown object");   return sb.toString(); }            

Example 23

From project querydsl, under directory /querydsl-codegen/src/test/java/com/mysema/query/codegen/.

Source file: TypeFactoryTest.java

23

vote

@Test public void Blob(){   Type blob=factory.create(Blob.class);   assertEquals("Blob",blob.getSimpleName());   assertEquals("java.sql.Blob",blob.getFullName());   assertEquals("java.sql",blob.getPackageName()); }            

Example 24

From project saiku-adhoc, under directory /saiku-adhoc-core/src/main/java/org/saiku/adhoc/service/report/.

Source file: SaikuAdhocPreProcessor.java

23

vote

protected ElementType computeElementType(final FieldDefinition fieldDefinition){   final String field=fieldDefinition.getField();   final DataAttributes attributes=flowController.getDataSchema().getAttributes(field);   if (attributes == null) {     log.warn("Field '" + field + "' is declared in the wizard-specification, "+ "but not present in the data. Assuming defaults.");     return new TextFieldType();   }   final Class fieldType=(Class)attributes.getMetaAttribute(MetaAttributeNames.Core.NAMESPACE,MetaAttributeNames.Core.TYPE,Class.class,attributeContext);   if (fieldType == null) {     return new TextFieldType();   }   if (Number.class.isAssignableFrom(fieldType)) {     return new NumberFieldType();   }   if (Date.class.isAssignableFrom(fieldType)) {     return new DateFieldType();   }   if (byte[].class.isAssignableFrom(fieldType) || Blob.class.isAssignableFrom(fieldType) || Image.class.isAssignableFrom(fieldType)) {     return new ContentFieldType();   }   return new TextFieldType(); }            

Example 25

From project tika, under directory /tika-core/src/main/java/org/apache/tika/io/.

Source file: TikaInputStream.java

23

vote

/**   * Creates a TikaInputStream from the given database BLOB. The BLOB length (if available) is stored as input metadata in the given metadata instance. <p> Note that the result set containing the BLOB may need to be kept open until the returned TikaInputStream has been processed and closed. You must also always explicitly close the returned stream as in some cases it may end up writing the blob data to a temporary file.  * @param blob database BLOB  * @param metadata metadata instance  * @return a TikaInputStream instance  * @throws SQLException if BLOB data can not be accessed  */ public static TikaInputStream get(Blob blob,Metadata metadata) throws SQLException {   long length=-1;   try {     length=blob.length();     metadata.set(Metadata.CONTENT_LENGTH,Long.toString(length));   }  catch (  SQLException ignore) {   }   if (0 <= length && length <= BLOB_SIZE_THRESHOLD) {     return get(blob.getBytes(1,(int)length),metadata);   }  else {     return new TikaInputStream(new BufferedInputStream(blob.getBinaryStream()),new TemporaryResources(),length);   } }            

Example 26

From project Weave, under directory /JTDS_SqlServerDriver/src/main/net/sourceforge/jtds/jdbc/.

Source file: BlobImpl.java

23

vote

public long position(Blob pattern,long start) throws SQLException {   if (pattern == null) {     throw new SQLException(Messages.get("error.blob.badpattern"),"HY009");   }   return blobBuffer.position(pattern.getBytes(1,(int)pattern.length()),start); }            

laboyimmill.blogspot.com

Source: http://www.javased.com/?api=java.sql.Blob

0 Response to "Java Sql Blob Inputstream Example"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel