List of usage examples for java.sql ResultSet getBlob
Blob getBlob(String columnLabel) throws SQLException;
ResultSet
object as a Blob
object in the Java programming language. From source file:edu.umass.cs.gigapaxos.SQLPaxosLogger.java
/** * Gets the list of logged messages for the paxosID. The static method * PaxosLogger.rollForward(.) can be directly invoked to replay these * messages without explicitly invoking this method. * /*from w w w. ja v a2s.c o m*/ * @param paxosID * @param fieldConstraints * @return A list of logged messages for {@code paxosID} meeting * {@code fieldConstraints}. */ private synchronized ArrayList<PaxosPacket> getLoggedMessages(String paxosID, String fieldConstraints) { long t = System.currentTimeMillis(); if (ENABLE_JOURNALING && LOG_INDEX_FREQUENCY > 0) this.syncLogMessagesIndex(paxosID); ArrayList<PaxosPacket> messages = new ArrayList<PaxosPacket>(); if (DISABLE_GET_LOGGED_MESSAGES) return messages; PreparedStatement pstmt = null; ResultSet messagesRS = null; Connection conn = null; try { conn = this.getDefaultConn(); pstmt = this.getPreparedStatement(conn, getMTable(), paxosID, "packet_type, message" + (ENABLE_JOURNALING ? ", logfile, foffset, length" : ""), fieldConstraints); messagesRS = pstmt.executeQuery(); assert (!messagesRS.isClosed()); while (messagesRS.next()) { assert (!ENABLE_JOURNALING || messagesRS.getString("logfile") != null); String logMsgStr = null; byte[] logMsgBytes = null; try { logMsgBytes = (!ENABLE_JOURNALING ? (!getLogMessageBlobOption() ? messagesRS.getString("message").getBytes(CHARSET) : lobToBytes(messagesRS.getBlob("message"))) : this.getJournaledMessage(messagesRS.getString("logfile"), messagesRS.getLong("foffset"), messagesRS.getInt("length"), null)); logMsgStr = new String(logMsgBytes, CHARSET); } catch (SQLException | IOException e) { /* It is possible that a journal file gets garbage collected * while getJournaledMessage is trying to get logged * messages from it, so IOExceptions here are not fatal. */ log.severe(this + ":" + e.getClass().getSimpleName() + " while getting logged messages for " + paxosID + ":" + messagesRS.getString("packet_type") + ":" + messagesRS.getString("logfile") + ":" + messagesRS.getLong("foffset") + ":" + messagesRS.getInt("length")); e.printStackTrace(); } if (logMsgBytes == null) continue; PaxosPacket packet = this.getPacketizer() != null ? getPacketizer().stringToPaxosPacket(logMsgBytes) : PaxosPacket.getPaxosPacket(logMsgStr); if (packet == null) { log.severe(this + " retrieved null packet from logMsgStr"); continue; } assert (packet == null || !(packet instanceof AcceptPacket) || ((AcceptPacket) packet).hasRequestValue()) : packet; // sanity check for DB-journal consistency assert (packet == null || packet.getType().getInt() == messagesRS.getInt("packet_type")); messages.add(packet); } } catch (SQLException | JSONException e) { log.severe(e.getClass().getSimpleName() + " while getting slot for " + paxosID); e.printStackTrace(); } finally { cleanup(pstmt, messagesRS); cleanup(conn); } if (ENABLE_INSTRUMENTATION && Util.oneIn(Integer.MAX_VALUE)) DelayProfiler.updateDelay("getLoggedMessages", t); return messages; }
From source file:org.apache.ddlutils.platform.PlatformImplBase.java
/** * This is the core method to retrieve a value for a column from a result set. Its primary * purpose is to call the appropriate method on the result set, and to provide an extension * point where database-specific implementations can change this behavior. * // w w w . ja v a 2 s . c o m * @param resultSet The result set to extract the value from * @param columnName The name of the column; can be <code>null</code> in which case the * <code>columnIdx</code> will be used instead * @param columnIdx The index of the column's value in the result set; is only used if * <code>columnName</code> is <code>null</code> * @param jdbcType The jdbc type to extract * @return The value * @throws SQLException If an error occurred while accessing the result set */ protected Object extractColumnValue(ResultSet resultSet, String columnName, int columnIdx, int jdbcType) throws SQLException { boolean useIdx = (columnName == null); Object value; switch (jdbcType) { case Types.CHAR: case Types.VARCHAR: case Types.LONGVARCHAR: value = useIdx ? resultSet.getString(columnIdx) : resultSet.getString(columnName); break; case Types.NUMERIC: case Types.DECIMAL: value = useIdx ? resultSet.getBigDecimal(columnIdx) : resultSet.getBigDecimal(columnName); break; case Types.BIT: case Types.BOOLEAN: value = new Boolean(useIdx ? resultSet.getBoolean(columnIdx) : resultSet.getBoolean(columnName)); break; case Types.TINYINT: case Types.SMALLINT: case Types.INTEGER: value = new Integer(useIdx ? resultSet.getInt(columnIdx) : resultSet.getInt(columnName)); break; case Types.BIGINT: value = new Long(useIdx ? resultSet.getLong(columnIdx) : resultSet.getLong(columnName)); break; case Types.REAL: value = new Float(useIdx ? resultSet.getFloat(columnIdx) : resultSet.getFloat(columnName)); break; case Types.FLOAT: case Types.DOUBLE: value = new Double(useIdx ? resultSet.getDouble(columnIdx) : resultSet.getDouble(columnName)); break; case Types.BINARY: case Types.VARBINARY: case Types.LONGVARBINARY: value = useIdx ? resultSet.getBytes(columnIdx) : resultSet.getBytes(columnName); break; case Types.DATE: value = useIdx ? resultSet.getDate(columnIdx) : resultSet.getDate(columnName); break; case Types.TIME: value = useIdx ? resultSet.getTime(columnIdx) : resultSet.getTime(columnName); break; case Types.TIMESTAMP: value = useIdx ? resultSet.getTimestamp(columnIdx) : resultSet.getTimestamp(columnName); break; case Types.CLOB: Clob clob = useIdx ? resultSet.getClob(columnIdx) : resultSet.getClob(columnName); if (clob == null) { value = null; } else { long length = clob.length(); if (length > Integer.MAX_VALUE) { value = clob; } else if (length == 0) { // the javadoc is not clear about whether Clob.getSubString // can be used with a substring length of 0 // thus we do the safe thing and handle it ourselves value = ""; } else { value = clob.getSubString(1l, (int) length); } } break; case Types.BLOB: Blob blob = useIdx ? resultSet.getBlob(columnIdx) : resultSet.getBlob(columnName); if (blob == null) { value = null; } else { long length = blob.length(); if (length > Integer.MAX_VALUE) { value = blob; } else if (length == 0) { // the javadoc is not clear about whether Blob.getBytes // can be used with for 0 bytes to be copied // thus we do the safe thing and handle it ourselves value = new byte[0]; } else { value = blob.getBytes(1l, (int) length); } } break; case Types.ARRAY: value = useIdx ? resultSet.getArray(columnIdx) : resultSet.getArray(columnName); break; case Types.REF: value = useIdx ? resultSet.getRef(columnIdx) : resultSet.getRef(columnName); break; default: value = useIdx ? resultSet.getObject(columnIdx) : resultSet.getObject(columnName); break; } return resultSet.wasNull() ? null : value; }
From source file:org.globus.workspace.persistence.PersistenceAdapterImpl.java
/** * @param id id/*from w ww .j ava 2 s . c o m*/ * @param resource resource * @throws DoesNotExistException * @throws WorkspaceDatabaseException */ public void load(int id, InstanceResource resource) throws DoesNotExistException, WorkspaceDatabaseException { if (this.dbTrace) { logger.trace("load(): " + Lager.id(id) + ", WorkspaceResource = " + resource); } if (id < 0) { throw new DoesNotExistException("id is less than zero"); } Connection c = null; PreparedStatement pstmt = null; PreparedStatement[] pstmts = null; ResultSet rs = null; try { c = getConnection(); pstmt = c.prepareStatement(SQL_LOAD_RESOURCE); pstmt.setInt(1, id); rs = pstmt.executeQuery(); if (rs == null || !rs.next()) { final String err = "resource with id = " + id + " not found"; logger.debug(err); throw new DoesNotExistException(err); } else { final String name = rs.getString(1); resource.setName(name); final int state = rs.getInt(2); final int targetState = rs.getInt(3); resource.setInitialTargetState(targetState); final long t = rs.getLong(4); if (t == 0) { resource.setTerminationTime(null); } else { final Calendar term = Calendar.getInstance(); term.setTimeInMillis(t); resource.setTerminationTime(term); } final boolean opsEnabled = rs.getBoolean(5); resource.setInitialOpsEnabled(opsEnabled); final String dn = rs.getString(6); resource.setCreatorID(dn); final long s = rs.getLong(7); if (s == 0) { resource.setStartTime(null); } else { final Calendar start = Calendar.getInstance(); start.setTimeInMillis(s); resource.setStartTime(start); } final boolean vmmAccessOK = rs.getBoolean(8); resource.setInitialVMMaccessOK(vmmAccessOK); final String ensembleid = rs.getString(9); resource.setEnsembleId(ensembleid); final String groupid = rs.getString(10); resource.setGroupId(groupid); final int groupsize = rs.getInt(11); resource.setGroupSize(groupsize); final boolean isLastInGroup = rs.getBoolean(12); resource.setLastInGroup(isLastInGroup); final int launchIndex = rs.getInt(13); resource.setLaunchIndex(launchIndex); final Blob errBlob = rs.getBlob(14); if (errBlob != null) { // getBytes requires int, cast from long final int length = (int) errBlob.length(); final Throwable err = ErrorUtil.getThrowable(errBlob.getBytes(1, length)); resource.setInitialState(state, err); } else { resource.setInitialState(state, null); } final String clientToken = rs.getString(15); resource.setClientToken(clientToken); final double chargeRatio = rs.getDouble(16); resource.setChargeRatio(chargeRatio); if (this.dbTrace) { logger.trace("found " + Lager.id(id) + ": name = " + name + ", state = " + state + ", targetState = " + targetState + ", termination time = " + t + ", opsEnabled = " + opsEnabled + ", creator ID = " + dn + ", start time = " + s + ", vmmAccessOK = " + vmmAccessOK + ", ensembleid = " + ensembleid + ", groupid = " + groupid + ", groupsize = " + groupsize + ", isLastInGroup = " + isLastInGroup + ", launchIndex = " + launchIndex + ", clientToken = " + clientToken + ", chargeRatio = " + chargeRatio + ", error present = " + (errBlob != null)); } rs.close(); if (resource instanceof VMPersistence) { if (this.dbTrace) { logger.trace(Lager.id(id) + ": load virtual machine"); } pstmts = VirtualMachinePersistenceUtil.getVMQuery(id, c); rs = pstmts[0].executeQuery(); if (rs == null || !rs.next()) { logger.error("resource with id=" + id + " not found"); throw new DoesNotExistException(); } final VirtualMachine vm = VirtualMachinePersistenceUtil.newVM(id, rs); if (this.dbTrace) { logger.trace(Lager.id(id) + ", created vm:\n" + vm.toString()); } rs.close(); rs = pstmts[1].executeQuery(); if (rs == null || !rs.next()) { logger.debug("resource with id=" + id + " has no" + " deployment information"); } else { VirtualMachinePersistenceUtil.addDeployment(vm, rs); if (this.dbTrace) { logger.trace("added deployment info to vm object"); } rs.close(); } rs = pstmts[2].executeQuery(); if (rs == null || !rs.next()) { logger.warn("resource with id=" + id + " has no" + " partitions"); } else { final ArrayList partitions = new ArrayList(8); do { partitions.add(VirtualMachinePersistenceUtil.getPartition(rs)); } while (rs.next()); final VirtualMachinePartition[] parts = (VirtualMachinePartition[]) partitions .toArray(new VirtualMachinePartition[partitions.size()]); vm.setPartitions(parts); } rs = pstmts[3].executeQuery(); if (rs == null || !rs.next()) { if (this.lager.dbLog) { logger.debug("resource with id=" + id + " has no" + " customization needs"); } } else { do { vm.addFileCopyNeed(VirtualMachinePersistenceUtil.getNeed(rs)); } while (rs.next()); } ((VMPersistence) resource).setWorkspace(vm); } } } catch (SQLException e) { logger.error("", e); throw new WorkspaceDatabaseException(e); } catch (DoesNotExistException e) { throw e; } catch (IOException e) { logger.error("", e); throw new WorkspaceDatabaseException(e); } catch (ClassNotFoundException e) { logger.error("", e); throw new WorkspaceDatabaseException(e); } finally { try { if (pstmt != null) { pstmt.close(); } if (pstmts != null) { for (int i = 0; i < pstmts.length; i++) { pstmts[i].close(); } } if (rs != null) { rs.close(); } if (c != null) { returnConnection(c); } } catch (SQLException sql) { logger.error("SQLException in finally cleanup", sql); } } }
From source file:edu.umass.cs.gigapaxos.SQLPaxosLogger.java
/** * Methods to get slot, ballotnum, coordinator, state, and version of * checkpoint//from w w w .jav a 2 s . c o m * * @param table * * @param paxosID * @param version * @param matchVersion * @return Returns SlotBallotState object retrieved for * {@code paxosID:version}. */ public SlotBallotState getSlotBallotState(String table, String paxosID, int version, boolean matchVersion) { if (isClosed()) return null; SlotBallotState sb = null; ResultSet stateRS = null; PreparedStatement cpStmt = null; Connection conn = null; boolean versionMismatch = false; try { conn = this.getDefaultConn(); assert (conn != null); cpStmt = this.getPreparedStatement(conn, table, paxosID, "slot, ballotnum, coordinator, state, version, create_time, members"); cpStmt.setString(1, paxosID); stateRS = cpStmt.executeQuery(); while (stateRS.next()) { assert (sb == null); // single result versionMismatch = (matchVersion && version != stateRS.getInt(5)); if (versionMismatch) log.log(Level.INFO, "{0} asked for {1}:{2} but got version {3}", new Object[] { this, paxosID, version, stateRS.getInt(5) }); assert (table.equals(getCTable()) || table.equals(getPCTable())); if (!versionMismatch) sb = new SlotBallotState(stateRS.getInt(1), stateRS.getInt(2), stateRS.getInt(3), (!getCheckpointBlobOption() ? stateRS.getString(4) : lobToString(stateRS.getBlob(4))), stateRS.getInt(5), stateRS.getLong(6), Util.stringToStringSet(stateRS.getString(7))); } } catch (SQLException | IOException | JSONException e) { log.severe(e.getClass().getSimpleName() + " while getting slot " + " : " + e); e.printStackTrace(); } finally { cleanup(stateRS); cleanup(cpStmt); cleanup(conn); } return versionMismatch ? null : sb; }
From source file:org.apache.openjpa.jdbc.sql.DBDictionary.java
public void updateBlob(Select sel, JDBCStore store, InputStream is) throws SQLException { SQLBuffer sql = sel.toSelect(true, store.getFetchConfiguration()); ResultSet res = null; Connection conn = store.getConnection(); PreparedStatement stmnt = null; try {//from w w w . j a va 2 s . co m stmnt = sql.prepareStatement(conn, store.getFetchConfiguration(), ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); setTimeouts(stmnt, store.getFetchConfiguration(), true); res = stmnt.executeQuery(); if (!res.next()) { throw new InternalException(_loc.get("stream-exception")); } Blob blob = res.getBlob(1); OutputStream os = blob.setBinaryStream(1); copy(is, os); os.close(); res.updateBlob(1, blob); res.updateRow(); } catch (IOException ioe) { throw new StoreException(ioe); } finally { if (res != null) try { res.close(); } catch (SQLException e) { } if (stmnt != null) try { stmnt.close(); } catch (SQLException e) { } if (conn != null) try { conn.close(); } catch (SQLException e) { } } }
From source file:org.openmrs.module.sync.api.db.hibernate.HibernateSyncDAO.java
public void exportChildDB(String uuidForChild, OutputStream os) throws DAOException { PrintStream out = new PrintStream(os); Set<String> tablesToSkip = new HashSet<String>(); {//from ww w .j a v a2 s . c o m tablesToSkip.add("hl7_in_archive"); tablesToSkip.add("hl7_in_queue"); tablesToSkip.add("hl7_in_error"); tablesToSkip.add("formentry_archive"); tablesToSkip.add("formentry_queue"); tablesToSkip.add("formentry_error"); tablesToSkip.add("sync_class"); tablesToSkip.add("sync_import"); tablesToSkip.add("sync_record"); tablesToSkip.add("sync_server"); tablesToSkip.add("sync_server_class"); tablesToSkip.add("sync_server_record"); // TODO: figure out which other tables to skip // tablesToSkip.add("obs"); // tablesToSkip.add("concept"); // tablesToSkip.add("patient"); } List<String> tablesToDump = new ArrayList<String>(); Session session = sessionFactory.getCurrentSession(); String schema = (String) session.createSQLQuery("SELECT schema()").uniqueResult(); log.warn("schema: " + schema); // Get all tables that we'll need to dump { Query query = session.createSQLQuery( "SELECT tabs.table_name FROM INFORMATION_SCHEMA.TABLES tabs WHERE tabs.table_schema = '" + schema + "'"); for (Object tn : query.list()) { String tableName = (String) tn; if (!tablesToSkip.contains(tableName.toLowerCase())) tablesToDump.add(tableName); } } log.warn("tables to dump: " + tablesToDump); String thisServerGuid = getGlobalProperty(SyncConstants.PROPERTY_SERVER_UUID); // Write the DDL Header as mysqldump does { out.println("-- ------------------------------------------------------"); out.println("-- Database dump to create an openmrs child server"); out.println("-- Schema: " + schema); out.println("-- Parent GUID: " + thisServerGuid); out.println("-- Parent version: " + OpenmrsConstants.OPENMRS_VERSION); out.println("-- ------------------------------------------------------"); out.println(""); out.println("/*!40101 SET CHARACTER_SET_CLIENT=utf8 */;"); out.println("/*!40101 SET NAMES utf8 */;"); out.println("/*!40103 SET TIME_ZONE='+00:00' */;"); out.println("/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;"); out.println("/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;"); out.println("/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;"); out.println("/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;"); out.println("/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;"); out.println("/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;"); out.println("/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;"); out.println("/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;"); out.println(""); } try { // JDBC way of doing this // Connection conn = // DriverManager.getConnection("jdbc:mysql://localhost/" + schema, // "test", "test"); Connection conn = sessionFactory.getCurrentSession().connection(); try { Statement st = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY); // Get the create database statement ResultSet rs = st.executeQuery("SHOW CREATE DATABASE " + schema); for (String tableName : tablesToDump) { out.println(); out.println("--"); out.println("-- Table structure for table `" + tableName + "`"); out.println("--"); out.println("DROP TABLE IF EXISTS `" + tableName + "`;"); out.println("SET @saved_cs_client = @@character_set_client;"); out.println("SET character_set_client = utf8;"); rs = st.executeQuery("SHOW CREATE TABLE " + tableName); while (rs.next()) { out.println(rs.getString("Create Table") + ";"); } out.println("SET character_set_client = @saved_cs_client;"); out.println(); { out.println("-- Dumping data for table `" + tableName + "`"); out.println("LOCK TABLES `" + tableName + "` WRITE;"); out.println("/*!40000 ALTER TABLE `" + tableName + "` DISABLE KEYS */;"); boolean first = true; rs = st.executeQuery("select * from " + tableName); ResultSetMetaData md = rs.getMetaData(); int numColumns = md.getColumnCount(); int rowNum = 0; boolean insert = false; while (rs.next()) { if (rowNum == 0) { insert = true; out.print("INSERT INTO `" + tableName + "` VALUES "); } ++rowNum; if (first) { first = false; } else { out.print(", "); } if (rowNum % 20 == 0) { out.println(); } out.print("("); for (int i = 1; i <= numColumns; ++i) { if (i != 1) { out.print(","); } if (rs.getObject(i) == null) { out.print("NULL"); } else { switch (md.getColumnType(i)) { case Types.VARCHAR: case Types.CHAR: case Types.LONGVARCHAR: out.print("'"); out.print( rs.getString(i).replaceAll("\n", "\\\\n").replaceAll("'", "\\\\'")); out.print("'"); break; case Types.BIGINT: case Types.DECIMAL: case Types.NUMERIC: out.print(rs.getBigDecimal(i)); break; case Types.BIT: out.print(rs.getBoolean(i)); break; case Types.INTEGER: case Types.SMALLINT: case Types.TINYINT: out.print(rs.getInt(i)); break; case Types.REAL: case Types.FLOAT: case Types.DOUBLE: out.print(rs.getDouble(i)); break; case Types.BLOB: case Types.VARBINARY: case Types.LONGVARBINARY: Blob blob = rs.getBlob(i); out.print("'"); InputStream in = blob.getBinaryStream(); while (true) { int b = in.read(); if (b < 0) { break; } char c = (char) b; if (c == '\'') { out.print("\'"); } else { out.print(c); } } out.print("'"); break; case Types.CLOB: out.print("'"); out.print( rs.getString(i).replaceAll("\n", "\\\\n").replaceAll("'", "\\\\'")); out.print("'"); break; case Types.DATE: out.print("'" + rs.getDate(i) + "'"); break; case Types.TIMESTAMP: out.print("'" + rs.getTimestamp(i) + "'"); break; default: throw new RuntimeException("TODO: handle type code " + md.getColumnType(i) + " (name " + md.getColumnTypeName(i) + ")"); } } } out.print(")"); } if (insert) { out.println(";"); insert = false; } out.println("/*!40000 ALTER TABLE `" + tableName + "` ENABLE KEYS */;"); out.println("UNLOCK TABLES;"); out.println(); } } } finally { conn.close(); } // Now we mark this as a child out.println("-- Now mark this as a child database"); if (uuidForChild == null) uuidForChild = SyncUtil.generateUuid(); out.println("update global_property set property_value = '" + uuidForChild + "' where property = '" + SyncConstants.PROPERTY_SERVER_UUID + "';"); // Write the footer of the DDL script { out.println("/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;"); out.println("/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;"); out.println("/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;"); out.println("/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;"); out.println("/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;"); out.println("/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;"); out.println("/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;"); out.println("/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;"); } out.flush(); out.close(); } catch (IOException ex) { log.error("IOException", ex); } catch (SQLException ex) { log.error("SQLException", ex); } }
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 w ww . j ava 2 s . c om 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:net.sourceforge.msscodefactory.v1_10.MSSBamPg8.MSSBamPg8TableBlobTable.java
protected MSSBamTableBlobBuff unpackTableBlobResultSetToBuff(ResultSet resultSet) throws SQLException { final String S_ProcName = "unpackTableBlobResultSetToBuff"; int idxcol = 1; String classCode = resultSet.getString(idxcol); idxcol++;//from w w w .j a v a2 s .co m MSSBamTableBlobBuff buff; if (classCode.equals("TBLB")) { buff = schema.getFactoryTableBlob().newBuff(); } else { throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(), S_ProcName, "Unrecognized class code \"" + classCode + "\""); } buff.setRequiredId(resultSet.getLong(idxcol)); idxcol++; buff.setRequiredTenantId(resultSet.getLong(idxcol)); idxcol++; { long colVal = resultSet.getLong(idxcol); if (resultSet.wasNull()) { buff.setOptionalScopeId(null); } else { buff.setOptionalScopeId(colVal); } } idxcol++; buff.setRequiredName(resultSet.getString(idxcol)); idxcol++; { String colVal = resultSet.getString(idxcol); if (resultSet.wasNull()) { buff.setOptionalShortName(null); } else { buff.setOptionalShortName(colVal); } } idxcol++; { String colVal = resultSet.getString(idxcol); if (resultSet.wasNull()) { buff.setOptionalLabel(null); } else { buff.setOptionalLabel(colVal); } } idxcol++; { String colVal = resultSet.getString(idxcol); if (resultSet.wasNull()) { buff.setOptionalShortDescription(null); } else { buff.setOptionalShortDescription(colVal); } } idxcol++; { String colVal = resultSet.getString(idxcol); if (resultSet.wasNull()) { buff.setOptionalDescription(null); } else { buff.setOptionalDescription(colVal); } } idxcol++; { long colVal = resultSet.getLong(idxcol); if (resultSet.wasNull()) { buff.setOptionalAuthorId(null); } else { buff.setOptionalAuthorId(colVal); } } idxcol++; buff.setRequiredValueContainerId(resultSet.getLong(idxcol)); idxcol++; buff.setRequiredIsNullable(resultSet.getBoolean(idxcol)); idxcol++; { boolean colVal = resultSet.getBoolean(idxcol); if (resultSet.wasNull()) { buff.setOptionalGenerateId(null); } else { buff.setOptionalGenerateId(colVal); } } idxcol++; { short colVal = resultSet.getShort(idxcol); if (resultSet.wasNull()) { buff.setOptionalDataScopeId(null); } else { buff.setOptionalDataScopeId(colVal); } } idxcol++; { short colVal = resultSet.getShort(idxcol); if (resultSet.wasNull()) { buff.setOptionalViewAccessSecurityId(null); } else { buff.setOptionalViewAccessSecurityId(colVal); } } idxcol++; { short colVal = resultSet.getShort(idxcol); if (resultSet.wasNull()) { buff.setOptionalEditAccessSecurityId(null); } else { buff.setOptionalEditAccessSecurityId(colVal); } } idxcol++; { short colVal = resultSet.getShort(idxcol); if (resultSet.wasNull()) { buff.setOptionalViewAccessFrequencyId(null); } else { buff.setOptionalViewAccessFrequencyId(colVal); } } idxcol++; { short colVal = resultSet.getShort(idxcol); if (resultSet.wasNull()) { buff.setOptionalEditAccessFrequencyId(null); } else { buff.setOptionalEditAccessFrequencyId(colVal); } } idxcol++; { long colVal = resultSet.getLong(idxcol); if (resultSet.wasNull()) { buff.setOptionalPrevId(null); } else { buff.setOptionalPrevId(colVal); } } idxcol++; { long colVal = resultSet.getLong(idxcol); if (resultSet.wasNull()) { buff.setOptionalNextId(null); } else { buff.setOptionalNextId(colVal); } } idxcol++; { String colVal = resultSet.getString(idxcol); if (resultSet.wasNull()) { buff.setOptionalDbName(null); } else { buff.setOptionalDbName(colVal); } } idxcol++; buff.setRequiredMaxLen(resultSet.getInt(idxcol)); idxcol++; { Blob binding = resultSet.getBlob(idxcol); if (resultSet.wasNull()) { buff.setOptionalInitValue(null); } else { long bindLen = binding.length(); if (bindLen > Integer.MAX_VALUE) { throw CFLib.getDefaultExceptionFactory().newArgumentOverflowException(getClass(), S_ProcName, idxcol, "InitValue", bindLen, (long) (Integer.MAX_VALUE)); } byte[] colVal = binding.getBytes(0, (int) bindLen); buff.setOptionalInitValue(colVal); } } idxcol++; { Blob binding = resultSet.getBlob(idxcol); if (resultSet.wasNull()) { buff.setOptionalDefaultValue(null); } else { long bindLen = binding.length(); if (bindLen > Integer.MAX_VALUE) { throw CFLib.getDefaultExceptionFactory().newArgumentOverflowException(getClass(), S_ProcName, idxcol, "DefaultValue", bindLen, (long) (Integer.MAX_VALUE)); } byte[] colVal = binding.getBytes(0, (int) bindLen); buff.setOptionalDefaultValue(colVal); } } idxcol++; { Blob binding = resultSet.getBlob(idxcol); if (resultSet.wasNull()) { buff.setOptionalNullValue(null); } else { long bindLen = binding.length(); if (bindLen > Integer.MAX_VALUE) { throw CFLib.getDefaultExceptionFactory().newArgumentOverflowException(getClass(), S_ProcName, idxcol, "NullValue", bindLen, (long) (Integer.MAX_VALUE)); } byte[] colVal = binding.getBytes(0, (int) bindLen); buff.setOptionalNullValue(colVal); } } idxcol++; { Blob binding = resultSet.getBlob(idxcol); if (resultSet.wasNull()) { buff.setOptionalUnknownValue(null); } else { long bindLen = binding.length(); if (bindLen > Integer.MAX_VALUE) { throw CFLib.getDefaultExceptionFactory().newArgumentOverflowException(getClass(), S_ProcName, idxcol, "UnknownValue", bindLen, (long) (Integer.MAX_VALUE)); } byte[] colVal = binding.getBytes(0, (int) bindLen); buff.setOptionalUnknownValue(colVal); } } idxcol++; buff.setRequiredContainerId(resultSet.getLong(idxcol)); idxcol++; buff.setRequiredRevision(resultSet.getInt(idxcol)); return (buff); }
From source file:net.sourceforge.msscodefactory.v1_10.MSSBamPg8.MSSBamPg8SchemaBlobTable.java
protected MSSBamSchemaBlobBuff unpackSchemaBlobResultSetToBuff(ResultSet resultSet) throws SQLException { final String S_ProcName = "unpackSchemaBlobResultSetToBuff"; int idxcol = 1; String classCode = resultSet.getString(idxcol); idxcol++;/*w ww . j av a 2 s .com*/ MSSBamSchemaBlobBuff buff; if (classCode.equals("SBLB")) { buff = schema.getFactorySchemaBlob().newBuff(); } else { throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(), S_ProcName, "Unrecognized class code \"" + classCode + "\""); } buff.setRequiredId(resultSet.getLong(idxcol)); idxcol++; buff.setRequiredTenantId(resultSet.getLong(idxcol)); idxcol++; { long colVal = resultSet.getLong(idxcol); if (resultSet.wasNull()) { buff.setOptionalScopeId(null); } else { buff.setOptionalScopeId(colVal); } } idxcol++; buff.setRequiredName(resultSet.getString(idxcol)); idxcol++; { String colVal = resultSet.getString(idxcol); if (resultSet.wasNull()) { buff.setOptionalShortName(null); } else { buff.setOptionalShortName(colVal); } } idxcol++; { String colVal = resultSet.getString(idxcol); if (resultSet.wasNull()) { buff.setOptionalLabel(null); } else { buff.setOptionalLabel(colVal); } } idxcol++; { String colVal = resultSet.getString(idxcol); if (resultSet.wasNull()) { buff.setOptionalShortDescription(null); } else { buff.setOptionalShortDescription(colVal); } } idxcol++; { String colVal = resultSet.getString(idxcol); if (resultSet.wasNull()) { buff.setOptionalDescription(null); } else { buff.setOptionalDescription(colVal); } } idxcol++; { long colVal = resultSet.getLong(idxcol); if (resultSet.wasNull()) { buff.setOptionalAuthorId(null); } else { buff.setOptionalAuthorId(colVal); } } idxcol++; buff.setRequiredValueContainerId(resultSet.getLong(idxcol)); idxcol++; buff.setRequiredIsNullable(resultSet.getBoolean(idxcol)); idxcol++; { boolean colVal = resultSet.getBoolean(idxcol); if (resultSet.wasNull()) { buff.setOptionalGenerateId(null); } else { buff.setOptionalGenerateId(colVal); } } idxcol++; { short colVal = resultSet.getShort(idxcol); if (resultSet.wasNull()) { buff.setOptionalDataScopeId(null); } else { buff.setOptionalDataScopeId(colVal); } } idxcol++; { short colVal = resultSet.getShort(idxcol); if (resultSet.wasNull()) { buff.setOptionalViewAccessSecurityId(null); } else { buff.setOptionalViewAccessSecurityId(colVal); } } idxcol++; { short colVal = resultSet.getShort(idxcol); if (resultSet.wasNull()) { buff.setOptionalEditAccessSecurityId(null); } else { buff.setOptionalEditAccessSecurityId(colVal); } } idxcol++; { short colVal = resultSet.getShort(idxcol); if (resultSet.wasNull()) { buff.setOptionalViewAccessFrequencyId(null); } else { buff.setOptionalViewAccessFrequencyId(colVal); } } idxcol++; { short colVal = resultSet.getShort(idxcol); if (resultSet.wasNull()) { buff.setOptionalEditAccessFrequencyId(null); } else { buff.setOptionalEditAccessFrequencyId(colVal); } } idxcol++; { long colVal = resultSet.getLong(idxcol); if (resultSet.wasNull()) { buff.setOptionalPrevId(null); } else { buff.setOptionalPrevId(colVal); } } idxcol++; { long colVal = resultSet.getLong(idxcol); if (resultSet.wasNull()) { buff.setOptionalNextId(null); } else { buff.setOptionalNextId(colVal); } } idxcol++; { String colVal = resultSet.getString(idxcol); if (resultSet.wasNull()) { buff.setOptionalDbName(null); } else { buff.setOptionalDbName(colVal); } } idxcol++; buff.setRequiredMaxLen(resultSet.getInt(idxcol)); idxcol++; { Blob binding = resultSet.getBlob(idxcol); if (resultSet.wasNull()) { buff.setOptionalInitValue(null); } else { long bindLen = binding.length(); if (bindLen > Integer.MAX_VALUE) { throw CFLib.getDefaultExceptionFactory().newArgumentOverflowException(getClass(), S_ProcName, idxcol, "InitValue", bindLen, (long) (Integer.MAX_VALUE)); } byte[] colVal = binding.getBytes(0, (int) bindLen); buff.setOptionalInitValue(colVal); } } idxcol++; { Blob binding = resultSet.getBlob(idxcol); if (resultSet.wasNull()) { buff.setOptionalDefaultValue(null); } else { long bindLen = binding.length(); if (bindLen > Integer.MAX_VALUE) { throw CFLib.getDefaultExceptionFactory().newArgumentOverflowException(getClass(), S_ProcName, idxcol, "DefaultValue", bindLen, (long) (Integer.MAX_VALUE)); } byte[] colVal = binding.getBytes(0, (int) bindLen); buff.setOptionalDefaultValue(colVal); } } idxcol++; { Blob binding = resultSet.getBlob(idxcol); if (resultSet.wasNull()) { buff.setOptionalNullValue(null); } else { long bindLen = binding.length(); if (bindLen > Integer.MAX_VALUE) { throw CFLib.getDefaultExceptionFactory().newArgumentOverflowException(getClass(), S_ProcName, idxcol, "NullValue", bindLen, (long) (Integer.MAX_VALUE)); } byte[] colVal = binding.getBytes(0, (int) bindLen); buff.setOptionalNullValue(colVal); } } idxcol++; { Blob binding = resultSet.getBlob(idxcol); if (resultSet.wasNull()) { buff.setOptionalUnknownValue(null); } else { long bindLen = binding.length(); if (bindLen > Integer.MAX_VALUE) { throw CFLib.getDefaultExceptionFactory().newArgumentOverflowException(getClass(), S_ProcName, idxcol, "UnknownValue", bindLen, (long) (Integer.MAX_VALUE)); } byte[] colVal = binding.getBytes(0, (int) bindLen); buff.setOptionalUnknownValue(colVal); } } idxcol++; buff.setRequiredContainerId(resultSet.getLong(idxcol)); idxcol++; buff.setRequiredRevision(resultSet.getInt(idxcol)); return (buff); }
From source file:org.moqui.impl.entity.EntityJavaUtil.java
public static Object getResultSetValue(ResultSet rs, int index, FieldInfo fi, EntityFacade efi) throws EntityException { if (fi.typeValue == -1) throw new EntityException("No typeValue found for " + fi.entityName + "." + fi.name); Object value = null;/*w ww.j a v a2 s . c om*/ try { switch (fi.typeValue) { case 1: // getMetaData and the column type are somewhat slow (based on profiling), and String values are VERY // common, so only do for text-very-long if (fi.isTextVeryLong) { ResultSetMetaData rsmd = rs.getMetaData(); if (Types.CLOB == rsmd.getColumnType(index)) { // if the String is empty, try to get a text input stream, this is required for some databases // for larger fields, like CLOBs Clob valueClob = rs.getClob(index); Reader valueReader = null; if (valueClob != null) valueReader = valueClob.getCharacterStream(); if (valueReader != null) { // read up to 4096 at a time char[] inCharBuffer = new char[4096]; StringBuilder strBuf = new StringBuilder(); try { int charsRead; while ((charsRead = valueReader.read(inCharBuffer, 0, 4096)) > 0) { strBuf.append(inCharBuffer, 0, charsRead); } valueReader.close(); } catch (IOException e) { throw new EntityException("Error reading long character stream for field [" + fi.name + "] of entity [" + fi.entityName + "]", e); } value = strBuf.toString(); } } else { value = rs.getString(index); } } else { value = rs.getString(index); } break; case 2: try { value = rs.getTimestamp(index, efi.getCalendarForTzLc()); } catch (SQLException e) { if (logger.isTraceEnabled()) logger.trace( "Ignoring SQLException for getTimestamp(), leaving null (found this in MySQL with a date/time value of [0000-00-00 00:00:00]): " + e.toString()); } break; case 3: value = rs.getTime(index, efi.getCalendarForTzLc()); break; case 4: value = rs.getDate(index, efi.getCalendarForTzLc()); break; case 5: int intValue = rs.getInt(index); if (!rs.wasNull()) value = intValue; break; case 6: long longValue = rs.getLong(index); if (!rs.wasNull()) value = longValue; break; case 7: float floatValue = rs.getFloat(index); if (!rs.wasNull()) value = floatValue; break; case 8: double doubleValue = rs.getDouble(index); if (!rs.wasNull()) value = doubleValue; break; case 9: BigDecimal bigDecimalValue = rs.getBigDecimal(index); if (!rs.wasNull()) value = bigDecimalValue != null ? bigDecimalValue.stripTrailingZeros() : null; break; case 10: boolean booleanValue = rs.getBoolean(index); if (!rs.wasNull()) value = booleanValue; break; case 11: Object obj = null; byte[] originalBytes = rs.getBytes(index); InputStream binaryInput = null; if (originalBytes != null && originalBytes.length > 0) { binaryInput = new ByteArrayInputStream(originalBytes); } if (originalBytes != null && originalBytes.length <= 0) { logger.warn("Got byte array back empty for serialized Object with length [" + originalBytes.length + "] for field [" + fi.name + "] (" + index + ")"); } if (binaryInput != null) { ObjectInputStream inStream = null; try { inStream = new ObjectInputStream(binaryInput); obj = inStream.readObject(); } catch (IOException ex) { if (logger.isTraceEnabled()) logger.trace("Unable to read BLOB from input stream for field [" + fi.name + "] (" + index + "): " + ex.toString()); } catch (ClassNotFoundException ex) { if (logger.isTraceEnabled()) logger.trace("Class not found: Unable to cast BLOB data to an Java object for field [" + fi.name + "] (" + index + "); most likely because it is a straight byte[], so just using the raw bytes: " + ex.toString()); } finally { if (inStream != null) { try { inStream.close(); } catch (IOException e) { throw new EntityException("Unable to close binary input stream for field [" + fi.name + "] (" + index + "): " + e.toString(), e); } } } } if (obj != null) { value = obj; } else { value = originalBytes; } break; case 12: SerialBlob sblob = null; try { // NOTE: changed to try getBytes first because Derby blows up on getBlob and on then calling getBytes for the same field, complains about getting value twice byte[] fieldBytes = rs.getBytes(index); if (!rs.wasNull()) sblob = new SerialBlob(fieldBytes); // fieldBytes = theBlob != null ? theBlob.getBytes(1, (int) theBlob.length()) : null } catch (SQLException e) { if (logger.isTraceEnabled()) logger.trace("Ignoring exception trying getBytes(), trying getBlob(): " + e.toString()); Blob theBlob = rs.getBlob(index); if (!rs.wasNull()) sblob = new SerialBlob(theBlob); } value = sblob; break; case 13: value = new SerialClob(rs.getClob(index)); break; case 14: case 15: value = rs.getObject(index); break; } } catch (SQLException sqle) { logger.error("SQL Exception while getting value for field: [" + fi.name + "] (" + index + ")", sqle); throw new EntityException( "SQL Exception while getting value for field: [" + fi.name + "] (" + index + ")", sqle); } return value; }