List of usage examples for java.sql Blob getBinaryStream
java.io.InputStream getBinaryStream() throws SQLException;
From source file:org.wso2.carbon.apimgt.hybrid.gateway.usage.publisher.dao.UploadedUsageFileInfoDAO.java
/** * Get the content of the file based on the file information * * @param dto Processed file represented by {@link UploadedFileInfoDTO} * @return InputStream with the content of the file of null if there is no content * @throws UsagePublisherException/*from ww w .j a v a 2 s .co m*/ */ public static InputStream getFileContent(UploadedFileInfoDTO dto) throws UsagePublisherException { Connection connection = null; PreparedStatement statement = null; ResultSet resultSet = null; InputStream fileContentInputStream = null; try { connection = APIMgtDBUtil.getConnection(); statement = connection.prepareStatement(MicroGatewayAPIUsageConstants.GET_UPLOADED_FILE_CONTENT_QUERY); statement.setString(1, dto.getTenantDomain()); statement.setString(2, dto.getFileName()); resultSet = statement.executeQuery(); while (resultSet.next()) { //Postgres bytea data doesn't support getBlob operation if (connection.getMetaData().getDriverName().contains("PostgreSQL")) { fileContentInputStream = resultSet .getBinaryStream(MicroGatewayAPIUsageConstants.API_USAGE_FILE_CONTENT); } else { Blob content = resultSet.getBlob(MicroGatewayAPIUsageConstants.API_USAGE_FILE_CONTENT); fileContentInputStream = content.getBinaryStream(); } if (log.isDebugEnabled()) { log.debug("Added File to list : " + dto.toString()); } } if (log.isDebugEnabled()) { log.debug("Retrieved content of file : " + dto.toString()); } } catch (SQLException e) { throw new UsagePublisherException( "Error occurred while retrieving the content of the file: " + dto.toString(), e); } finally { APIMgtDBUtil.closeAllConnections(statement, connection, resultSet); } return fileContentInputStream; }
From source file:org.wso2.carbon.dataservices.core.description.query.SQLQuery.java
private DataEntry getDataEntryFromRS(ResultSet rs) throws SQLException { DataEntry dataEntry = new DataEntry(); ResultSetMetaData metaData = rs.getMetaData(); int columnCount = metaData.getColumnCount(); int columnType; String value;//from www. j a va 2s. co m ParamValue paramValue; Time sqlTime; Date sqlDate; Timestamp sqlTimestamp; Blob sqlBlob; BigDecimal bigDecimal; InputStream binInStream; boolean useColumnNumbers = this.isUsingColumnNumbers(); for (int i = 1; i <= columnCount; i++) { /* retrieve values according to the column type */ columnType = metaData.getColumnType(i); switch (columnType) { /* handle string types */ case Types.VARCHAR: /* fall through */ case Types.LONGVARCHAR: /* fall through */ case Types.CHAR: /* fall through */ case Types.CLOB: /* fall through */ case Types.NCHAR: /* fall through */ case Types.NCLOB: /* fall through */ case Types.NVARCHAR: /* fall through */ case Types.LONGNVARCHAR: value = rs.getString(i); paramValue = new ParamValue(value); break; /* handle numbers */ case Types.INTEGER: /* fall through */ case Types.TINYINT: /* fall through */ case Types.SMALLINT: value = ConverterUtil.convertToString(rs.getInt(i)); paramValue = new ParamValue(rs.wasNull() ? null : value); break; case Types.DOUBLE: value = ConverterUtil.convertToString(rs.getDouble(i)); paramValue = new ParamValue(rs.wasNull() ? null : value); break; case Types.FLOAT: value = ConverterUtil.convertToString(rs.getFloat(i)); paramValue = new ParamValue(rs.wasNull() ? null : value); break; case Types.BOOLEAN: /* fall through */ case Types.BIT: value = ConverterUtil.convertToString(rs.getBoolean(i)); paramValue = new ParamValue(rs.wasNull() ? null : value); break; case Types.DECIMAL: bigDecimal = rs.getBigDecimal(i); if (bigDecimal != null) { value = ConverterUtil.convertToString(bigDecimal); } else { value = null; } paramValue = new ParamValue(value); break; /* handle data/time values */ case Types.TIME: /* handle time data type */ sqlTime = rs.getTime(i); if (sqlTime != null) { value = this.convertToTimeString(sqlTime); } else { value = null; } paramValue = new ParamValue(value); break; case Types.DATE: /* handle date data type */ sqlDate = rs.getDate(i); if (sqlDate != null) { value = ConverterUtil.convertToString(sqlDate); } else { value = null; } paramValue = new ParamValue(value); break; case Types.TIMESTAMP: sqlTimestamp = rs.getTimestamp(i, calendar); if (sqlTimestamp != null) { value = this.convertToTimestampString(sqlTimestamp); } else { value = null; } paramValue = new ParamValue(value); break; /* handle binary types */ case Types.BLOB: sqlBlob = rs.getBlob(i); if (sqlBlob != null) { value = this.getBase64StringFromInputStream(sqlBlob.getBinaryStream()); } else { value = null; } paramValue = new ParamValue(value); break; case Types.BINARY: /* fall through */ case Types.LONGVARBINARY: /* fall through */ case Types.VARBINARY: binInStream = rs.getBinaryStream(i); if (binInStream != null) { value = this.getBase64StringFromInputStream(binInStream); } else { value = null; } paramValue = new ParamValue(value); break; /* handling User Defined Types */ case Types.STRUCT: Struct udt = (Struct) rs.getObject(i); paramValue = new ParamValue(udt); break; case Types.ARRAY: paramValue = new ParamValue(ParamValue.PARAM_VALUE_ARRAY); Array dataArray = (Array) rs.getObject(i); if (dataArray == null) { break; } paramValue = this.processSQLArray(dataArray, paramValue); break; case Types.NUMERIC: bigDecimal = rs.getBigDecimal(i); if (bigDecimal != null) { value = ConverterUtil.convertToString(bigDecimal); } else { value = null; } paramValue = new ParamValue(value); break; case Types.BIGINT: value = ConverterUtil.convertToString(rs.getLong(i)); paramValue = new ParamValue(rs.wasNull() ? null : value); break; /* handle all other types as strings */ default: value = rs.getString(i); paramValue = new ParamValue(value); break; } dataEntry.addValue(useColumnNumbers ? Integer.toString(i) : metaData.getColumnLabel(i), paramValue); } return dataEntry; }
From source file:org.wso2.carbon.dataservices.core.odata.RDBMSDataHandler.java
private String getValueFromResultSet(int columnType, String column, ResultSet resultSet) throws SQLException { String paramValue;/* w w w .j a v a2s .c om*/ switch (columnType) { case Types.INTEGER: /* fall through */ case Types.TINYINT: /* fall through */ case Types.SMALLINT: paramValue = ConverterUtil.convertToString(resultSet.getInt(column)); paramValue = resultSet.wasNull() ? null : paramValue; break; case Types.DOUBLE: paramValue = ConverterUtil.convertToString(resultSet.getDouble(column)); paramValue = resultSet.wasNull() ? null : paramValue; break; case Types.VARCHAR: /* fall through */ case Types.CHAR: /* fall through */ case Types.CLOB: /* fall through */ case Types.LONGVARCHAR: paramValue = resultSet.getString(column); break; case Types.BOOLEAN: /* fall through */ case Types.BIT: paramValue = ConverterUtil.convertToString(resultSet.getBoolean(column)); paramValue = resultSet.wasNull() ? null : paramValue; break; case Types.BLOB: Blob sqlBlob = resultSet.getBlob(column); if (sqlBlob != null) { paramValue = this.getBase64StringFromInputStream(sqlBlob.getBinaryStream()); } else { paramValue = null; } paramValue = resultSet.wasNull() ? null : paramValue; break; case Types.BINARY: /* fall through */ case Types.LONGVARBINARY: /* fall through */ case Types.VARBINARY: InputStream binInStream = resultSet.getBinaryStream(column); if (binInStream != null) { paramValue = this.getBase64StringFromInputStream(binInStream); } else { paramValue = null; } break; case Types.DATE: Date sqlDate = resultSet.getDate(column); if (sqlDate != null) { paramValue = ConverterUtil.convertToString(sqlDate); } else { paramValue = null; } break; case Types.DECIMAL: /* fall through */ case Types.NUMERIC: BigDecimal bigDecimal = resultSet.getBigDecimal(column); if (bigDecimal != null) { paramValue = ConverterUtil.convertToString(bigDecimal); } else { paramValue = null; } paramValue = resultSet.wasNull() ? null : paramValue; break; case Types.FLOAT: paramValue = ConverterUtil.convertToString(resultSet.getFloat(column)); paramValue = resultSet.wasNull() ? null : paramValue; break; case Types.TIME: Time sqlTime = resultSet.getTime(column); if (sqlTime != null) { paramValue = this.convertToTimeString(sqlTime); } else { paramValue = null; } break; case Types.LONGNVARCHAR: /* fall through */ case Types.NCHAR: /* fall through */ case Types.NCLOB: /* fall through */ case Types.NVARCHAR: paramValue = resultSet.getNString(column); break; case Types.BIGINT: paramValue = ConverterUtil.convertToString(resultSet.getLong(column)); paramValue = resultSet.wasNull() ? null : paramValue; break; case Types.TIMESTAMP: Timestamp sqlTimestamp = resultSet.getTimestamp(column); if (sqlTimestamp != null) { paramValue = this.convertToTimestampString(sqlTimestamp); } else { paramValue = null; } paramValue = resultSet.wasNull() ? null : paramValue; break; /* handle all other types as strings */ default: paramValue = resultSet.getString(column); paramValue = resultSet.wasNull() ? null : paramValue; break; } return paramValue; }
From source file:org.wso2.carbon.identity.certificateauthority.dao.CertificateDAO.java
/** * convert result set to an array of publicCertificates * * @param resultSet resultSet/* ww w . jav a2s. c o m*/ * @return an Array of PublicCertificates */ private Certificate[] getCertificateArray(ResultSet resultSet) { ArrayList<Certificate> pcList = new ArrayList<Certificate>(); int count = 0; try { while (resultSet.next()) { Certificate cert = null; String serialNo = resultSet.getString(Constants.SERIAL_NO_LABEL); String status = resultSet.getString(Constants.PC_STATUS_LABEL); Date expiryDate = resultSet.getTimestamp(Constants.PC_EXPIRY_DATE); Blob pcBlob = resultSet.getBlob(Constants.PC_CONTENT_LABEL); CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); X509Certificate certificate = (X509Certificate) certificateFactory .generateCertificate(pcBlob.getBinaryStream()); Date issuedDate = resultSet.getTimestamp(Constants.PC_ISSUDED_DATE); String username = resultSet.getString(Constants.PC_ISSUER_LABEL); int tenantID = resultSet.getInt(Constants.TENANT_ID_LABEL); String userStoreDomain = resultSet.getString(Constants.USER_STORE_DOMAIN_LABEL); cert = new Certificate(serialNo, certificate, status, tenantID, username, issuedDate, expiryDate, userStoreDomain); pcList.add(cert); } } catch (SQLException e) { e.printStackTrace(); } catch (CertificateException e) { e.printStackTrace(); } Certificate[] pcFiles = new Certificate[pcList.size()]; pcFiles = pcList.toArray(pcFiles); return pcFiles; }
From source file:org.xenei.bloomgraph.bloom.sql.DBIO.java
/** * copy the blob to a byte buffer./* ww w . j a v a 2 s . c o m*/ * * @param blob * The blob to read * @return A bytebuffer with the blob contents. * @throws IOException * on copy error * @throws SQLException * on db error */ public static ByteBuffer toByteBuffer(final Blob blob) throws IOException, SQLException { ByteArrayOutputStream baos = null; try { baos = new ByteArrayOutputStream(); IOUtils.copy(blob.getBinaryStream(), baos); return ByteBuffer.wrap(baos.toByteArray()).order(ByteOrder.LITTLE_ENDIAN); } finally { IOUtils.closeQuietly(baos); } }
From source file:org.xsystem.sql2.dml.DmlCommand.java
byte[] getBlob(Blob myBlob) throws SQLException { InputStream is = myBlob.getBinaryStream(); try {/*from w w w . j a v a2 s .c om*/ byte[] ret = IOUtils.toByteArray(is); return ret; } catch (IOException ex) { throw new SQLException(ex); } finally { Auxilary.close(is); } }
From source file:org.zanata.liquibase.custom.MigrateRawDocumentsToFileSystem.java
private void writeBlobToFile(Blob content, String fileName) throws SQLException, IOException { File outputFile = createFileInConfiguredDirectory(fileName); writeStreamToFile(content.getBinaryStream(), outputFile); // releasing blob resources may not be necessary, but makes me feel // better and shouldn't cause problems content.free();//from w w w.j a v a 2 s. co m content = null; }
From source file:sd_conexion_bd.Servicios.java
public boolean validar_userName(String userName, String password, usuario u) throws IOException { try {//from w w w . j ava 2 s . co m this.conectar("localhost:3306", "mensajeria", "mensajeria", "1234"); ////this.conectar("192.168.43.21:3306", "mensajeria","mensajeria","1234"); //System.out.println("\n" + userName+ " " + password + "\n"); this.consulta = this.conexion .prepareStatement("call buscar_por_user(\"" + userName + "\",\"" + password + "\");"); this.datos = this.consulta.executeQuery(); while (this.datos.next()) { u.setID(datos.getInt("id")); u.setNombre(datos.getString("nombre")); u.setApellido(datos.getString("apellido")); u.setUser(userName); Blob imagen = datos.getBlob("foto"); Image im = javax.imageio.ImageIO.read(imagen.getBinaryStream()); if (im != null) { ImageIcon i = new ImageIcon(im.getScaledInstance(100, 120, 0)); u.setFoto(i); } this.desconectar(); return true; } this.desconectar(); return false; } catch (ClassNotFoundException | SQLException ex) { Logger.getLogger(Servicios.class.getName()).log(Level.SEVERE, null, ex); JOptionPane.showMessageDialog(null, "--No se pudo conectar correctamente a la base de datos"); System.exit(0); } return false; }
From source file:sd_conexion_bd.Servicios.java
/** * funcion para obtener los datos del contacto del usuario del chat *///from w w w . j av a 2s. c om public boolean dato_contacto(String nombre, String apellido, usuario u) throws IOException { try { this.conectar("localhost:3306", "mensajeria", "mensajeria", "1234"); //this.conectar("192.168.43.21:3306", "mensajeria","mensajeria","1234"); this.consulta = this.conexion .prepareStatement("call obtener_info_contacto(\"" + nombre + "\",\"" + apellido + "\");"); this.datos = this.consulta.executeQuery(); while (this.datos.next()) { u.setID(datos.getInt("id")); u.setNombre(nombre); u.setApellido(apellido); u.setUser(datos.getString("user")); u.setEst_conexion(datos.getString("estado_conexion").charAt(0)); u.setFecha_ult_conexion(datos.getTimestamp("fecha_ult_conexion")); Blob imagen = datos.getBlob("foto"); if (imagen != null) { Image im = javax.imageio.ImageIO.read(imagen.getBinaryStream()); ImageIcon i = new ImageIcon(im.getScaledInstance(100, 120, 0)); u.setFoto(i); } return true; } return false; } catch (ClassNotFoundException | SQLException ex) { Logger.getLogger(Servicios.class.getName()).log(Level.SEVERE, null, ex); JOptionPane.showMessageDialog(null, "No se pudo conectar correctamente a la base de datos"); System.exit(0); } return false; }
From source file:se.unlogic.hierarchy.foregroundmodules.imagegallery.GalleryModule.java
public static void writePicture(Picture picture, boolean mediumThumb, HttpServletResponse res) throws SQLException, IOException { // send thumb to user Blob blob = null; if (mediumThumb) { blob = picture.getMediumThumb(); } else {//from ww w. j a v a 2 s. c o m blob = picture.getSmallThumb(); } HTTPUtils.setContentLength(blob.length(), res); res.setContentType("image/jpeg"); res.setHeader("Content-Disposition", "inline; filename=\"" + FileUtils.toValidHttpFilename(picture.getFilename()) + "\""); InputStream in = null; OutputStream out = null; try { in = blob.getBinaryStream(); out = res.getOutputStream(); StreamUtils.transfer(in, out); } finally { StreamUtils.closeStream(in); StreamUtils.closeStream(out); } }