List of usage examples for java.sql Clob length
long length() throws SQLException;
From source file:dk.netarkivet.harvester.datamodel.JobDBDAO.java
/** Try to extract an orderxmldoc from a given Clob. * This method is used by the read() method, which catches the * thrown DocumentException./*from ww w .java2 s . c om*/ * @param clob a given Clob returned from the database * @return a Document object based on the data in the Clob * @throws SQLException If data from the clob cannot be fetched. * @throws DocumentException If unable to create a Document object based on * the data in the Clob */ private Document getOrderXMLdocFromClob(Clob clob) throws SQLException, DocumentException { Document doc; try { SAXReader reader = new SAXReader(); doc = reader.read(clob.getCharacterStream()); } catch (DocumentException e) { log.warn("Failed to read the contents of the clob as XML:" + clob.getSubString(1, (int) clob.length())); throw e; } return doc; }
From source file:dk.netarkivet.harvester.datamodel.JobDBDAO.java
/** Read a single job from the job database. * * @param jobID ID of the job./*from w w w .j av a 2 s. co m*/ * @param connection an open connection to the harvestDatabase * @return A Job object * @throws UnknownID if the job id does not exist. * @throws IOFailure if there was some problem talking to the database. */ private synchronized Job read(Connection connection, Long jobID) { if (!exists(connection, jobID)) { throw new UnknownID("Job id " + jobID + " is not known in persistent storage"); } PreparedStatement statement = null; try { statement = connection.prepareStatement("SELECT " + "harvest_id, status, channel, " + "forcemaxcount, forcemaxbytes, " + "forcemaxrunningtime, orderxml, " + "orderxmldoc, seedlist, harvest_num," + "harvest_errors, harvest_error_details, " + "upload_errors, upload_error_details, " + "startdate, enddate, submitteddate, creationdate, " + "edition, resubmitted_as_job, continuationof, harvestname_prefix, snapshot " + "FROM jobs WHERE job_id = ?"); statement.setLong(1, jobID); ResultSet result = statement.executeQuery(); result.next(); long harvestID = result.getLong(1); JobStatus status = JobStatus.fromOrdinal(result.getInt(2)); String channel = result.getString(3); long forceMaxCount = result.getLong(4); long forceMaxBytes = result.getLong(5); long forceMaxRunningTime = result.getLong(6); String orderxml = result.getString(7); Document orderXMLdoc = null; boolean useClobs = DBSpecifics.getInstance().supportsClob(); if (useClobs) { Clob clob = result.getClob(8); orderXMLdoc = getOrderXMLdocFromClob(clob); } else { orderXMLdoc = XmlUtils.documentFromString(result.getString(8)); } String seedlist = ""; if (useClobs) { Clob clob = result.getClob(9); seedlist = clob.getSubString(1, (int) clob.length()); } else { seedlist = result.getString(9); } int harvestNum = result.getInt(10); String harvestErrors = result.getString(11); String harvestErrorDetails = result.getString(12); String uploadErrors = result.getString(13); String uploadErrorDetails = result.getString(14); Date startdate = DBUtils.getDateMaybeNull(result, 15); Date stopdate = DBUtils.getDateMaybeNull(result, 16); Date submittedDate = DBUtils.getDateMaybeNull(result, 17); Date creationDate = DBUtils.getDateMaybeNull(result, 18); Long edition = result.getLong(19); Long resubmittedAsJob = DBUtils.getLongMaybeNull(result, 20); Long continuationOfJob = DBUtils.getLongMaybeNull(result, 21); String harvestnamePrefix = result.getString(22); boolean snapshot = result.getBoolean(23); statement.close(); // IDs should match up in a natural join // The following if-block is an attempt to fix Bug 1856, an // unexplained derby deadlock, by making this statement a dirty // read. String domainStatement = "SELECT domains.name, configurations.name " + "FROM domains, configurations, job_configs " + "WHERE job_configs.job_id = ?" + " AND job_configs.config_id = configurations.config_id" + " AND domains.domain_id = configurations.domain_id"; if (Settings.get(CommonSettings.DB_SPECIFICS_CLASS).contains(CommonSettings.DB_IS_DERBY_IF_CONTAINS)) { statement = connection.prepareStatement(domainStatement + " WITH UR"); } else { statement = connection.prepareStatement(domainStatement); } statement.setLong(1, jobID); result = statement.executeQuery(); Map<String, String> configurationMap = new HashMap<String, String>(); while (result.next()) { String domainName = result.getString(1); String configName = result.getString(2); configurationMap.put(domainName, configName); } final Job job = new Job(harvestID, configurationMap, channel, snapshot, forceMaxCount, forceMaxBytes, forceMaxRunningTime, status, orderxml, orderXMLdoc, seedlist, harvestNum, continuationOfJob); job.appendHarvestErrors(harvestErrors); job.appendHarvestErrorDetails(harvestErrorDetails); job.appendUploadErrors(uploadErrors); job.appendUploadErrorDetails(uploadErrorDetails); if (startdate != null) { job.setActualStart(startdate); } if (stopdate != null) { job.setActualStop(stopdate); } if (submittedDate != null) { job.setSubmittedDate(submittedDate); } if (creationDate != null) { job.setCreationDate(creationDate); } job.configsChanged = false; job.setJobID(jobID); job.setEdition(edition); if (resubmittedAsJob != null) { job.setResubmittedAsJob(resubmittedAsJob); } if (harvestnamePrefix == null) { job.setDefaultHarvestNamePrefix(); } else { job.setHarvestFilenamePrefix(harvestnamePrefix); } return job; } catch (SQLException e) { String message = "SQL error reading job " + jobID + " in database" + "\n" + ExceptionUtils.getSQLExceptionCause(e); log.warn(message, e); throw new IOFailure(message, e); } catch (DocumentException e) { String message = "XML error reading job " + jobID + " in database"; log.warn(message, e); throw new IOFailure(message, e); } }
From source file:dk.netarkivet.harvester.datamodel.DomainDBDAO.java
/** * Make SeedList based on entry from seedlists * (id, name, comments, seeds)./*from www .ja v a 2 s . c om*/ * @param res a Resultset * @return a SeedList based on ResultSet entry. * @throws SQLException if unable to get data from database */ private SeedList getSeedListFromResultset(ResultSet res) throws SQLException { final long seedlistId = res.getLong(1); final String seedlistName = res.getString(2); String seedlistComments = res.getString(3); String seedlistContents = ""; if (DBSpecifics.getInstance().supportsClob()) { Clob clob = res.getClob(4); seedlistContents = clob.getSubString(1, (int) clob.length()); } else { seedlistContents = res.getString(4); } final SeedList seedlist = new SeedList(seedlistName, seedlistContents); seedlist.setComments(seedlistComments); seedlist.setID(seedlistId); return seedlist; }
From source file:net.sf.jasperreports.engine.JRResultSetDataSource.java
@Override public Object getFieldValue(JRField field) throws JRException { Object objValue = null;/*from w w w. j a va2 s. c o m*/ if (field != null && resultSet != null) { Integer columnIndex = getColumnIndex(field); Class<?> clazz = field.getValueClass(); try { if (clazz.equals(java.lang.Boolean.class)) { objValue = resultSet.getBoolean(columnIndex); if (resultSet.wasNull()) { objValue = null; } } else if (clazz.equals(java.lang.Byte.class)) { objValue = resultSet.getByte(columnIndex); if (resultSet.wasNull()) { objValue = null; } } else if (clazz.equals(java.util.Date.class) || clazz.equals(java.sql.Date.class)) { objValue = readDate(columnIndex, field); } else if (clazz.equals(java.sql.Timestamp.class)) { objValue = readTimestamp(columnIndex, field); } else if (clazz.equals(java.sql.Time.class)) { objValue = readTime(columnIndex, field); } else if (clazz.equals(java.lang.Double.class)) { objValue = resultSet.getDouble(columnIndex); if (resultSet.wasNull()) { objValue = null; } } else if (clazz.equals(java.lang.Float.class)) { objValue = resultSet.getFloat(columnIndex); if (resultSet.wasNull()) { objValue = null; } } else if (clazz.equals(java.lang.Integer.class)) { objValue = resultSet.getInt(columnIndex); if (resultSet.wasNull()) { objValue = null; } } else if (clazz.equals(java.io.InputStream.class)) { byte[] bytes = readBytes(columnIndex); if (bytes == null) { objValue = null; } else { objValue = new ByteArrayInputStream(bytes); } } else if (clazz.equals(java.lang.Long.class)) { objValue = resultSet.getLong(columnIndex); if (resultSet.wasNull()) { objValue = null; } } else if (clazz.equals(java.lang.Short.class)) { objValue = resultSet.getShort(columnIndex); if (resultSet.wasNull()) { objValue = null; } } else if (clazz.equals(java.math.BigDecimal.class)) { objValue = resultSet.getBigDecimal(columnIndex); if (resultSet.wasNull()) { objValue = null; } } else if (clazz.equals(java.lang.String.class)) { int columnType = resultSet.getMetaData().getColumnType(columnIndex); switch (columnType) { case Types.CLOB: Clob clob = resultSet.getClob(columnIndex); if (resultSet.wasNull()) { objValue = null; } else { objValue = clobToString(clob); } break; default: objValue = resultSet.getString(columnIndex); if (resultSet.wasNull()) { objValue = null; } break; } } else if (clazz.equals(Clob.class)) { objValue = resultSet.getClob(columnIndex); if (resultSet.wasNull()) { objValue = null; } } else if (clazz.equals(Reader.class)) { Reader reader = null; long size = -1; int columnType = resultSet.getMetaData().getColumnType(columnIndex); switch (columnType) { case Types.CLOB: Clob clob = resultSet.getClob(columnIndex); if (!resultSet.wasNull()) { reader = clob.getCharacterStream(); size = clob.length(); } break; default: reader = resultSet.getCharacterStream(columnIndex); if (resultSet.wasNull()) { reader = null; } } if (reader == null) { objValue = null; } else { objValue = getArrayReader(reader, size); } } else if (clazz.equals(Blob.class)) { objValue = resultSet.getBlob(columnIndex); if (resultSet.wasNull()) { objValue = null; } } else if (clazz.equals(Image.class)) { byte[] bytes = readBytes(columnIndex); if (bytes == null) { objValue = null; } else { objValue = JRImageLoader.getInstance(jasperReportsContext).loadAwtImageFromBytes(bytes); } } else if (clazz.equals(byte[].class)) { objValue = readBytes(columnIndex); } else { objValue = resultSet.getObject(columnIndex); } } catch (Exception e) { throw new JRException(EXCEPTION_MESSAGE_KEY_RESULT_SET_FIELD_VALUE_NOT_RETRIEVED, new Object[] { field.getName(), clazz.getName() }, e); } } return objValue; }
From source file:helma.objectmodel.db.NodeManager.java
/** * Create a new Node from a ResultSet.//from w w w . ja v a 2 s. com */ public Node createNode(DbMapping dbm, ResultSet rs, DbColumn[] columns, int offset) throws SQLException, IOException, ClassNotFoundException { HashMap propBuffer = new HashMap(); String id = null; String name = null; String protoName = dbm.getTypeName(); DbMapping dbmap = dbm; Node node = new Node(safe); for (int i = 0; i < columns.length; i++) { int columnNumber = i + 1 + offset; // set prototype? if (columns[i].isPrototypeField()) { String protoId = rs.getString(columnNumber); protoName = dbm.getPrototypeName(protoId); if (protoName != null) { dbmap = getDbMapping(protoName); if (dbmap == null) { // invalid prototype name! app.logError("No prototype defined for prototype mapping \"" + protoName + "\" - Using default prototype \"" + dbm.getTypeName() + "\"."); dbmap = dbm; protoName = dbmap.getTypeName(); } } } // set id? if (columns[i].isIdField()) { id = rs.getString(columnNumber); // if id == null, the object doesn't actually exist - return null if (id == null) { return null; } } // set name? if (columns[i].isNameField()) { name = rs.getString(columnNumber); } Property newprop = new Property(node); switch (columns[i].getType()) { case Types.BIT: case Types.BOOLEAN: newprop.setBooleanValue(rs.getBoolean(columnNumber)); break; case Types.TINYINT: case Types.BIGINT: case Types.SMALLINT: case Types.INTEGER: newprop.setIntegerValue(rs.getLong(columnNumber)); break; case Types.REAL: case Types.FLOAT: case Types.DOUBLE: newprop.setFloatValue(rs.getDouble(columnNumber)); break; case Types.DECIMAL: case Types.NUMERIC: BigDecimal num = rs.getBigDecimal(columnNumber); if (num == null) { break; } if (num.scale() > 0) { newprop.setFloatValue(num.doubleValue()); } else { newprop.setIntegerValue(num.longValue()); } break; case Types.VARBINARY: case Types.BINARY: newprop.setJavaObjectValue(rs.getBytes(columnNumber)); break; case Types.BLOB: case Types.LONGVARBINARY: { InputStream in = rs.getBinaryStream(columnNumber); if (in == null) { break; } ByteArrayOutputStream bout = new ByteArrayOutputStream(); byte[] buffer = new byte[2048]; int read; while ((read = in.read(buffer)) > -1) { bout.write(buffer, 0, read); } newprop.setJavaObjectValue(bout.toByteArray()); } break; case Types.LONGVARCHAR: try { newprop.setStringValue(rs.getString(columnNumber)); } catch (SQLException x) { Reader in = rs.getCharacterStream(columnNumber); if (in == null) { newprop.setStringValue(null); break; } StringBuffer out = new StringBuffer(); char[] buffer = new char[2048]; int read; while ((read = in.read(buffer)) > -1) { out.append(buffer, 0, read); } newprop.setStringValue(out.toString()); } break; case Types.CHAR: case Types.VARCHAR: case Types.OTHER: newprop.setStringValue(rs.getString(columnNumber)); break; case Types.DATE: case Types.TIME: case Types.TIMESTAMP: newprop.setDateValue(rs.getTimestamp(columnNumber)); break; case Types.NULL: newprop.setStringValue(null); break; case Types.CLOB: Clob cl = rs.getClob(columnNumber); if (cl == null) { newprop.setStringValue(null); break; } char[] c = new char[(int) cl.length()]; Reader isr = cl.getCharacterStream(); isr.read(c); newprop.setStringValue(String.copyValueOf(c)); break; default: newprop.setStringValue(rs.getString(columnNumber)); break; } if (rs.wasNull()) { newprop.setStringValue(null); } propBuffer.put(columns[i].getName(), newprop); // mark property as clean, since it's fresh from the db newprop.dirty = false; } if (id == null) { return null; } else { Transactor tx = Transactor.getInstance(); if (tx != null) { // Check if the node is already registered with the transactor - // it may be in the process of being DELETED, but do return the // new node if the old one has been marked as INVALID. DbKey key = new DbKey(dbmap, id); Node dirtyNode = tx.getDirtyNode(key); if (dirtyNode != null && dirtyNode.getState() != Node.INVALID) { return dirtyNode; } } } Hashtable propMap = new Hashtable(); DbColumn[] columns2 = dbmap.getColumns(); for (int i = 0; i < columns2.length; i++) { Relation rel = columns2[i].getRelation(); if (rel != null && rel.isPrimitiveOrReference()) { Property prop = (Property) propBuffer.get(columns2[i].getName()); if (prop == null) { continue; } prop.setName(rel.propName); // if the property is a pointer to another node, change the property type to NODE if (rel.isReference() && rel.usesPrimaryKey()) { // FIXME: References to anything other than the primary key are not supported prop.convertToNodeReference(rel); } propMap.put(rel.propName, prop); } } node.init(dbmap, id, name, protoName, propMap); return node; }
From source file:axiom.objectmodel.db.NodeManager.java
/** * Create a new Node from a ResultSet.//from ww w .j a va 2 s . c om */ public Node createNode(DbMapping dbm, ResultSet rs, DbColumn[] columns, int offset) throws SQLException, IOException, ClassNotFoundException { HashMap propBuffer = new HashMap(); String id = null; String name = null; String protoName = dbm.getTypeName(); DbMapping dbmap = dbm; Node node = new Node(); for (int i = 0; i < columns.length; i++) { // set prototype? if (columns[i].isPrototypeField()) { protoName = rs.getString(i + 1 + offset); if (protoName != null) { dbmap = getDbMapping(protoName); if (dbmap == null) { // invalid prototype name! app.logError(ErrorReporter.errorMsg(this.getClass(), "createNode") + "Invalid prototype name: " + protoName + " - using default"); dbmap = dbm; protoName = dbmap.getTypeName(); } } } // set id? if (columns[i].isIdField()) { id = rs.getString(i + 1 + offset); // if id == null, the object doesn't actually exist - return null if (id == null) { return null; } } // set name? if (columns[i].isNameField()) { name = rs.getString(i + 1 + offset); } Property newprop = new Property(node); switch (columns[i].getType()) { case Types.BIT: newprop.setBooleanValue(rs.getBoolean(i + 1 + offset)); break; case Types.TINYINT: case Types.BIGINT: case Types.SMALLINT: case Types.INTEGER: newprop.setIntegerValue(rs.getLong(i + 1 + offset)); break; case Types.REAL: case Types.FLOAT: case Types.DOUBLE: newprop.setFloatValue(rs.getDouble(i + 1 + offset)); break; case Types.DECIMAL: case Types.NUMERIC: BigDecimal num = rs.getBigDecimal(i + 1 + offset); if (num == null) { break; } if (num.scale() > 0) { newprop.setFloatValue(num.doubleValue()); } else { newprop.setIntegerValue(num.longValue()); } break; case Types.VARBINARY: case Types.BINARY: // newprop.setStringValue(rs.getString(i+1+offset)); newprop.setJavaObjectValue(rs.getBytes(i + 1 + offset)); break; case Types.LONGVARBINARY: { InputStream in = rs.getBinaryStream(i + 1 + offset); if (in == null) { break; } ByteArrayOutputStream bout = new ByteArrayOutputStream(); byte[] buffer = new byte[2048]; int read; while ((read = in.read(buffer)) > -1) { bout.write(buffer, 0, read); } newprop.setJavaObjectValue(bout.toByteArray()); } break; case Types.LONGVARCHAR: try { newprop.setStringValue(rs.getString(i + 1 + offset)); } catch (SQLException x) { Reader in = rs.getCharacterStream(i + 1 + offset); char[] buffer = new char[2048]; int read = 0; int r; while ((r = in.read(buffer, read, buffer.length - read)) > -1) { read += r; if (read == buffer.length) { // grow input buffer char[] newBuffer = new char[buffer.length * 2]; System.arraycopy(buffer, 0, newBuffer, 0, buffer.length); buffer = newBuffer; } } newprop.setStringValue(new String(buffer, 0, read)); } break; case Types.CHAR: case Types.VARCHAR: case Types.OTHER: newprop.setStringValue(rs.getString(i + 1 + offset)); break; case Types.DATE: case Types.TIME: case Types.TIMESTAMP: newprop.setDateValue(rs.getTimestamp(i + 1 + offset)); break; case Types.NULL: newprop.setStringValue(null); break; case Types.CLOB: Clob cl = rs.getClob(i + 1 + offset); if (cl == null) { newprop.setStringValue(null); break; } char[] c = new char[(int) cl.length()]; Reader isr = cl.getCharacterStream(); isr.read(c); newprop.setStringValue(String.copyValueOf(c)); break; default: newprop.setStringValue(rs.getString(i + 1 + offset)); break; } if (rs.wasNull()) { newprop.setStringValue(null); } propBuffer.put(columns[i].getName(), newprop); // mark property as clean, since it's fresh from the db newprop.dirty = false; } if (id == null) { return null; } Hashtable propMap = new Hashtable(); DbColumn[] columns2 = dbmap.getColumns(); for (int i = 0; i < columns2.length; i++) { Relation rel = columns2[i].getRelation(); if (rel != null && (rel.reftype == Relation.PRIMITIVE || rel.reftype == Relation.REFERENCE)) { Property prop = (Property) propBuffer.get(columns2[i].getName()); if (prop == null) { continue; } prop.setName(rel.propName); // if the property is a pointer to another node, change the property type to NODE if ((rel.reftype == Relation.REFERENCE) && rel.usesPrimaryKey()) { // FIXME: References to anything other than the primary key are not supported prop.convertToNodeReference(rel.otherType, this.app.getCurrentRequestEvaluator().getLayer()); } propMap.put(rel.propName.toLowerCase(), prop); } } node.init(dbmap, id, name, protoName, propMap, safe); return node; }
From source file:nl.b3p.viewer.util.ApplicationDetailsValueTransformer.java
/** * create a CaseInsensitiveMap with key/values. * * Tuples are the elements making up each "row" of the query result. The * contract here is to transform these elements into the final row. * * @param tuple The result elements//from w ww.j av a 2s . co m * @param aliases The result aliases ("parallel" array to tuple) * @return The transformed row. */ @Override public Object transformTuple(Object[] tuple, String[] aliases) { Map<String, Object> map = new CaseInsensitiveMap(); for (int i = 0; i < aliases.length; i++) { Object t = tuple[i]; if (t != null && t instanceof Clob) { Clob c = (Clob) tuple[i]; try { t = c.getSubString(1, (int) c.length()); } catch (SQLException e) { LOG.error("Error transforming data tuple of " + aliases[i], e); } } map.put(aliases[i], t); } return map; }
From source file:org.agnitas.backend.DBase.java
public String asClob(Object o) { if (o == null) { return null; } else if (o.getClass() == String.class) { return (String) o; } else {/*from w w w. j a v a2 s .c o m*/ Clob clob = (Clob) o; try { return clob == null ? null : clob.getSubString(1, (int) clob.length()); } catch (SQLException e) { failure("clob parse", e); } return null; } }
From source file:org.agnitas.backend.StringOps.java
/** * Converts a DB clob into a string// w w w.j a v a 2s .co m * * @param clob * the source * @return the extracted string */ public static String clob2string(Clob clob) throws SQLException { return clob == null ? "" : clob.getSubString(1, (int) clob.length()); }
From source file:org.apache.cocoon.util.JDBCTypeConversions.java
/** * Get the Statement column so that the results are mapped correctly. * (this has been copied from AbstractDatabaseAction and modified slightly) */// w w w . ja v a 2s .c om public static Object getColumn(ResultSet set, Configuration column) throws Exception { Integer type = (Integer) JDBCTypeConversions.typeConstants.get(column.getAttribute("type")); String dbcol = column.getAttribute("name"); Object value = null; switch (type.intValue()) { case Types.CLOB: case Types.CHAR: Clob dbClob = set.getClob(dbcol); int length = (int) dbClob.length(); InputStream asciiStream = new BufferedInputStream(dbClob.getAsciiStream()); byte[] buffer = new byte[length]; asciiStream.read(buffer); String str = new String(buffer); asciiStream.close(); value = str; break; case Types.BIGINT: value = set.getBigDecimal(dbcol); break; case Types.TINYINT: value = new Byte(set.getByte(dbcol)); break; case Types.VARCHAR: value = set.getString(dbcol); break; case Types.DATE: value = set.getDate(dbcol); break; case Types.DOUBLE: value = new Double(set.getDouble(dbcol)); break; case Types.FLOAT: value = new Float(set.getFloat(dbcol)); break; case Types.INTEGER: value = new Integer(set.getInt(dbcol)); break; case Types.NUMERIC: value = new Long(set.getLong(dbcol)); break; case Types.SMALLINT: value = new Short(set.getShort(dbcol)); break; case Types.TIME: value = set.getTime(dbcol); break; case Types.TIMESTAMP: value = set.getTimestamp(dbcol); break; case Types.ARRAY: value = set.getArray(dbcol); // new Integer(set.getInt(dbcol)); break; case Types.BIT: value = BooleanUtils.toBooleanObject(set.getBoolean(dbcol)); break; case Types.STRUCT: value = (Struct) set.getObject(dbcol); break; case Types.OTHER: value = set.getObject(dbcol); break; default: // The blob types have to be requested separately, via a Reader. value = ""; break; } return value; }