List of usage examples for java.sql ResultSet getBinaryStream
java.io.InputStream getBinaryStream(String columnLabel) throws SQLException;
ResultSet
object as a stream of uninterpreted byte
s. From source file:org.wso2.carbon.dataservices.core.odata.RDBMSDataHandler.java
private String getValueFromResultSet(int columnType, String column, ResultSet resultSet) throws SQLException { String paramValue;/*from www . j av a2s .co m*/ 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.sakaiproject.db.impl.BasicSqlService.java
/** * Read a single field / record from the db, returning a stream on the result record / field. The stream holds the conection open - so it must be * closed or finalized quickly!/*www . j a v a 2 s. c o m*/ * * @param sql * The sql statement. * @param fields * The array of fields for parameters. * @param big * If true, the read is expected to be potentially large. * @throws ServerOverloadException * if the read cannot complete due to lack of a free connection (if wait is false) */ public InputStream dbReadBinary(String sql, Object[] fields, boolean big) throws ServerOverloadException { // Note: does not support TRANSACTION_CONNECTION -ggolden if (LOG.isDebugEnabled()) { LOG.debug("dbReadBinary(String " + sql + ", Object[] " + Arrays.toString(fields) + ", boolean " + big + ")"); } InputStream rv = null; // for DEBUG long start = 0; long connectionTime = 0; int lenRead = 0; if (LOG.isDebugEnabled()) { String userId = usageSessionService().getSessionId(); LOG.debug("Sql.dbReadBinary(): " + userId + "\n" + sql); } Connection conn = null; PreparedStatement pstmt = null; ResultSet result = null; try { if (m_showSql) { start = System.currentTimeMillis(); } if (!big) { conn = borrowConnection(); } else { // get a connection if it's available, else throw conn = borrowConnection(); if (conn == null) { throw new ServerOverloadException(null); } } if (m_showSql) { connectionTime = System.currentTimeMillis() - start; } if (m_showSql) { start = System.currentTimeMillis(); } pstmt = conn.prepareStatement(sql); // put in all the fields prepareStatement(pstmt, fields); result = pstmt.executeQuery(); if (result.next()) { InputStream stream = result.getBinaryStream(1); rv = new StreamWithConnection(stream, result, pstmt, conn); } } catch (ServerOverloadException e) { throw e; } catch (SQLException e) { LOG.warn("Sql.dbReadBinary(): " + e); } catch (UnsupportedEncodingException e) { LOG.warn("Sql.dbReadBinary(): " + e); } finally { // ONLY if we didn't make the rv - else let the rv hold these OPEN! if (rv == null) { if (null != result) { try { result.close(); } catch (SQLException e) { LOG.warn("Sql.dbReadBinary(): " + e); } } if (null != pstmt) { try { pstmt.close(); } catch (SQLException e) { LOG.warn("Sql.dbReadBinary(): " + e); } } if (null != conn) { // if we commit on read if (m_commitAfterRead) { try { conn.commit(); } catch (SQLException e) { LOG.warn("Sql.dbReadBinary(): " + e); } } returnConnection(conn); } } // LOG.warn("Sql.dbReadBinary(): " + e); } if (m_showSql) { debug("sql read binary: len: " + lenRead + " time: " + connectionTime + " / " + (System.currentTimeMillis() - start), sql, fields); } return rv; }
From source file:org.wso2.carbon.ml.database.internal.MLDatabaseService.java
/** * Retrieve the SamplePoints object for a given value-set. * * @param tenantId Tenant id//from w w w.ja va 2s .c o m * @param user Tenant user name * @param versionsetId Unique Identifier of the dataset version * @return SamplePoints object of the value-set * @throws DatabaseHandlerException */ public SamplePoints getVersionsetSample(int tenantId, String user, long versionsetId) throws DatabaseHandlerException { Connection connection = null; PreparedStatement updateStatement = null; ResultSet result = null; SamplePoints samplePoints = null; try { connection = dbh.getDataSource().getConnection(); connection.setAutoCommit(true); updateStatement = connection.prepareStatement(SQLQueries.GET_SAMPLE_POINTS); updateStatement.setLong(1, versionsetId); updateStatement.setInt(2, tenantId); updateStatement.setString(3, user); result = updateStatement.executeQuery(); if (result.first() && result.getBinaryStream(1) != null) { samplePoints = MLDBUtil.getSamplePointsFromInputStream(result.getBinaryStream(1)); } return samplePoints; } catch (Exception e) { // Roll-back the changes. MLDatabaseUtils.rollBack(connection); throw new DatabaseHandlerException("An error occurred while retrieving the sample of " + " dataset version " + versionsetId + ": " + e.getMessage(), e); } finally { // Close the database resources. MLDatabaseUtils.closeDatabaseResources(connection, updateStatement, result); } }
From source file:org.wso2.carbon.apimgt.core.dao.impl.ApiDAOImpl.java
private Endpoint constructEndPointDetails(ResultSet resultSet) throws SQLException, IOException { Endpoint.Builder endpointBuilder = new Endpoint.Builder(); endpointBuilder.id(resultSet.getString("UUID")); endpointBuilder.name(resultSet.getString("NAME")); endpointBuilder.endpointConfig(IOUtils.toString(resultSet.getBinaryStream("ENDPOINT_CONFIGURATION"))); endpointBuilder.maxTps(resultSet.getLong("TPS")); endpointBuilder.type(resultSet.getString("TYPE")); endpointBuilder.security(IOUtils.toString(resultSet.getBinaryStream("SECURITY_CONFIGURATION"))); endpointBuilder.applicableLevel(resultSet.getString("APPLICABLE_LEVEL")); return endpointBuilder.build(); }
From source file:org.wso2.carbon.ml.database.internal.MLDatabaseService.java
/** * Retrieve a Versionset from its ID/*from ww w .j a v a2 s .c o m*/ */ @Override public MLDatasetVersion getVersionset(int tenantId, String userName, long datasetVersionId) throws DatabaseHandlerException { Connection connection = null; ResultSet result = null; PreparedStatement statement = null; try { connection = dbh.getDataSource().getConnection(); statement = connection.prepareStatement(SQLQueries.GET_VERSIONSET_USING_ID); statement.setLong(1, datasetVersionId); statement.setInt(2, tenantId); statement.setString(3, userName); result = statement.executeQuery(); if (result.next()) { MLDatasetVersion versionset = new MLDatasetVersion(); versionset.setId(result.getLong(1)); versionset.setName(result.getString(2)); versionset.setTargetPath(result.getString(3)); if (result.getBinaryStream(4) != null) { versionset.setSamplePoints(MLDBUtil.getSamplePointsFromInputStream(result.getBinaryStream(4))); } versionset.setTenantId(tenantId); versionset.setUserName(userName); return versionset; } else { return null; } } catch (Exception e) { throw new DatabaseHandlerException( "An error has occurred while extracting dataset-version of id: " + datasetVersionId, e); } finally { // Close the database resources. MLDatabaseUtils.closeDatabaseResources(connection, statement, result); } }
From source file:org.wso2.carbon.ml.database.internal.MLDatabaseService.java
@Override public MLDatasetVersion getVersionSetWithVersion(long datasetId, String version, int tenantId, String userName) throws DatabaseHandlerException { Connection connection = null; ResultSet result = null; PreparedStatement statement = null; try {/* ww w. j a va 2 s. co m*/ connection = dbh.getDataSource().getConnection(); statement = connection.prepareStatement(SQLQueries.GET_DATASETVERSION_ID); statement.setLong(1, datasetId); statement.setInt(2, tenantId); statement.setString(3, userName); statement.setString(4, version); result = statement.executeQuery(); if (result.first()) { MLDatasetVersion versionset = new MLDatasetVersion(); versionset.setId(result.getLong(1)); versionset.setName(result.getString(2)); versionset.setTargetPath(result.getString(3) == null ? null : result.getString(3)); if (result.getBinaryStream(4) != null) { versionset.setSamplePoints(MLDBUtil.getSamplePointsFromInputStream(result.getBinaryStream(4))); } versionset.setTenantId(tenantId); versionset.setUserName(userName); versionset.setVersion(version); return versionset; } else { return null; } } catch (Exception e) { throw new DatabaseHandlerException(String.format( " An error has occurred while extracting dataset version id of [dataset] %s [version] %s", datasetId, version), e); } finally { // Close the database resources. MLDatabaseUtils.closeDatabaseResources(connection, statement, result); } }
From source file:pt.iflow.flows.FlowHolderBean.java
private DBFlow readFlow(UserInfoInterface userInfo, int flowId) { Connection db = null;/*from w w w. java 2s . co m*/ PreparedStatement pst = null; ResultSet rs = null; DBFlow flow = null; try { db = Utils.getDataSource().getConnection(); pst = db.prepareStatement("SELECT * FROM flow WHERE flowid=?"); // 1st read user flow pst.setInt(1, flowId); rs = pst.executeQuery(); if (rs.next()) { // flow exists if (userInfo.isSysAdmin() || rs.getString("organizationid").equals(userInfo.getOrganization()) || BeanFactory.getFlowSettingsBean().isGuestAccessible(userInfo, flowId)) { flow = new DBFlow(); flow.flowid = rs.getInt("flowid"); flow.organizationId = rs.getString("organizationid"); // use db orgid, since sysadmin can perform actions with flows flow.file = rs.getString("flowfile"); flow.name = rs.getString("flowname"); flow.online = rs.getBoolean("enabled"); InputStream is = rs.getBinaryStream("flowdata"); flow.data = getBytes(is); flow.created = rs.getTimestamp("created").getTime(); flow.lastModified = rs.getTimestamp("modified").getTime(); for (int i = 0; i < Const.INDEX_COLUMN_COUNT; i++) flow.indexFields[i] = rs.getString("name_idx" + i); flow.seriesId = rs.getInt("seriesid"); flow.typeCode = rs.getString("type_code"); is.close(); } } rs.close(); } catch (Exception e) { Logger.error(userInfo.getUtilizador(), this, "readFlow", "exception caught", e); e.printStackTrace(); } finally { DatabaseInterface.closeResources(db, pst, rs); } return flow; }
From source file:org.wso2.carbon.ml.database.internal.MLDatabaseService.java
/** * Retrieve all versionset of a dataset/*from w w w.j a v a2s.com*/ */ @Override public List<MLDatasetVersion> getAllVersionsetsOfDataset(int tenantId, String userName, long datasetId) throws DatabaseHandlerException { Connection connection = null; ResultSet result = null; PreparedStatement statement = null; List<MLDatasetVersion> versionsets = new ArrayList<MLDatasetVersion>(); try { connection = dbh.getDataSource().getConnection(); statement = connection.prepareStatement(SQLQueries.GET_ALL_VERSIONSETS_OF_DATASET); statement.setLong(1, datasetId); statement.setInt(2, tenantId); statement.setString(3, userName); result = statement.executeQuery(); while (result.next()) { MLDatasetVersion versionset = new MLDatasetVersion(); versionset.setId(result.getLong(1)); versionset.setName(result.getString(2)); versionset.setVersion(result.getString(3)); versionset.setTargetPath(result.getString(4)); if (result.getBinaryStream(5) != null) { SamplePoints samplePoints = MLDBUtil.getSamplePointsFromInputStream(result.getBinaryStream(5)); if (samplePoints.isGenerated() == true) { versionset.setSamplePoints( MLDBUtil.getSamplePointsFromInputStream(result.getBinaryStream(5))); versionset.setStatus(MLConstants.DatasetVersionStatus.COMPLETE.getValue()); } else { versionset.setStatus(MLConstants.DatasetVersionStatus.FAILED.getValue()); } } else { versionset.setStatus(MLConstants.DatasetVersionStatus.IN_PROGRESS.getValue()); } versionset.setTenantId(tenantId); versionset.setUserName(userName); versionsets.add(versionset); } return versionsets; } catch (Exception e) { throw new DatabaseHandlerException( "An error has occurred while extracting version sets for dataset id: " + datasetId, e); } finally { // Close the database resources. MLDatabaseUtils.closeDatabaseResources(connection, statement, result); } }
From source file:org.wso2.carbon.ml.database.internal.MLDatabaseService.java
/** * Get all models of a given project/* ww w. j ava 2 s .co m*/ * @param tenantId tenant ID * @param userName username * @param projectId Project ID * @return List of {@link org.wso2.carbon.ml.commons.domain.MLModelData} objects * @throws DatabaseHandlerException */ @Override public List<MLModelData> getProjectModels(int tenantId, String userName, long projectId) throws DatabaseHandlerException { Connection connection = null; ResultSet result = null; PreparedStatement statement = null; List<MLModelData> models = new ArrayList<MLModelData>(); try { connection = dbh.getDataSource().getConnection(); statement = connection.prepareStatement(SQLQueries.GET_PROJECT_MODELS); statement.setLong(1, projectId); statement.setInt(2, tenantId); statement.setString(3, userName); result = statement.executeQuery(); while (result.next()) { MLModelData model = new MLModelData(); model.setId(result.getLong(1)); model.setName(result.getString(2)); model.setAnalysisId(result.getLong(3)); model.setVersionSetId(result.getLong(4)); model.setCreatedTime(result.getString(5)); ModelSummary modelSummary = null; if (result.getBinaryStream(6) != null) { modelSummary = MLDBUtil.getModelSummaryFromInputStream(result.getBinaryStream(6)); } model.setModelSummary(modelSummary); model.setStorageType(result.getString(7)); model.setStorageDirectory(result.getString(8)); model.setTenantId(tenantId); model.setUserName(userName); model.setStatus(result.getString(9)); model.setError(result.getString(10)); models.add(model); } return models; } catch (Exception e) { throw new DatabaseHandlerException( " An error has occurred while extracting all models of" + "project ID:" + projectId, e); } finally { // Close the database resources. MLDatabaseUtils.closeDatabaseResources(connection, statement, result); } }
From source file:pt.iflow.flows.FlowHolderBean.java
private synchronized byte[] readData(UserInfoInterface userInfo, String name, boolean isFlow, int version) { String query = null;//from ww w .jav a 2 s . c om Connection db = null; PreparedStatement st = null; ResultSet rs = null; byte[] data = null; String sub = isFlow ? "" : "sub_"; try { db = Utils.getDataSource().getConnection(); if (version < 0) { query = "select flowdata from " + sub + "flow where flowfile=? and organizationid=?"; } else { query = "select h.data as flowdata from " + sub + "flow f, " + sub + "flow_history h where f.flowfile=? and f.organizationid=? and f.flowid=h.flowid and h.flowversion=?"; } Logger.debug(userInfo.getUtilizador(), this, "readData", "Executing query: " + query); Logger.debug(userInfo.getUtilizador(), this, "readData", "Query params: name=" + name + "; organizationid=" + userInfo.getOrganization() + "; version=" + version); st = db.prepareStatement(query); st.setString(1, name); st.setString(2, userInfo.getOrganization()); if (version >= 0) st.setInt(3, version); rs = st.executeQuery(); boolean flowFound = false; if (rs.next()) { flowFound = true; InputStream is = rs.getBinaryStream(1); data = getBytes(is); Logger.debug(userInfo.getUtilizador(), this, "readData", "Flow found. Bytes: " + data.length); } rs.close(); st.close(); if (!flowFound && version < 0) { Logger.debug(userInfo.getUtilizador(), this, "readData", "Flow not found. Searching templates."); // copy from template query = "select data FROM " + sub + "flow_template where name=?"; Logger.debug(userInfo.getUtilizador(), this, "readData", "Executing query: " + query); Logger.debug(userInfo.getUtilizador(), this, "readData", "Query params: name=" + name); st = db.prepareStatement(query); st.setString(1, name); rs = st.executeQuery(); if (rs.next()) { InputStream is = rs.getBinaryStream(1); data = getBytes(is); Logger.debug(userInfo.getUtilizador(), this, "readData", "Template found. Bytes: " + data.length); } } } catch (Exception e) { Logger.error(userInfo.getUtilizador(), this, "readData", "Exception occured reading flow data.", e); } finally { DatabaseInterface.closeResources(db, st, rs); } return data; }