List of usage examples for java.sql PreparedStatement setBoolean
void setBoolean(int parameterIndex, boolean x) throws SQLException;
boolean
value. From source file:com.flexive.core.storage.genericSQL.GenericTreeStorage.java
/** * {@inheritDoc}/*from w w w. j a va2 s . c om*/ */ @Override public List<String> getLabels(Connection con, FxTreeMode mode, long labelPropertyId, FxLanguage language, boolean stripNodeInfos, long... nodeIds) throws FxApplicationException { List<String> ret = new ArrayList<String>(nodeIds.length); if (nodeIds.length == 0) return ret; PreparedStatement ps = null; ResultSet rs; try { ps = con.prepareStatement("SELECT tree_FTEXT1024_Chain(?,?,?,?)" + StorageManager.getFromDual()); ps.setInt(2, (int) language.getId()); ps.setLong(3, labelPropertyId); ps.setBoolean(4, mode == FxTreeMode.Live); for (long id : nodeIds) { ps.setLong(1, id); rs = ps.executeQuery(); if (rs != null && rs.next()) { final String path = rs.getString(1); if (!StringUtils.isEmpty(path)) ret.add(stripNodeInfos ? stripNodeInfos(path) : path); else addUnknownNodeId(ret, id); } else addUnknownNodeId(ret, id); } return ret; } catch (SQLException e) { throw new FxLoadException(LOG, e, "ex.db.sqlError", e.getMessage()); } finally { try { if (ps != null) ps.close(); } catch (Exception e) { //ignore } } }
From source file:com.flexive.core.storage.genericSQL.GenericTreeStorage.java
/** * {@inheritDoc}/*from ww w .java2s . c o m*/ */ @Override public void updateReference(Connection con, FxTreeMode mode, long nodeId, long referenceId) throws FxApplicationException { PreparedStatement ps = null; try { // 1 2 3 ps = con.prepareStatement("UPDATE " + getTable(mode) + " SET REF=?, DIRTY=? WHERE ID=?"); ps.setLong(1, referenceId); ps.setBoolean(2, mode != FxTreeMode.Live); //live tree is never dirty ps.setLong(3, nodeId); ps.executeUpdate(); FxContext.get().setTreeWasModified(); } catch (SQLException e) { throw new FxUpdateException(LOG, e, "ex.tree.update.failed", mode.name(), e.getMessage()); } finally { try { if (ps != null) ps.close(); } catch (SQLException e) { //ignore } } }
From source file:com.flexive.core.storage.genericSQL.GenericTreeStorage.java
/** * {@inheritDoc}/*from w w w . j a v a2 s .c om*/ */ @Override public void updateName(Connection con, FxTreeMode mode, ContentEngine ce, long nodeId, String name) throws FxApplicationException { FxTreeNode node = getNode(con, mode, nodeId); name = FxFormatUtils.escapeTreePath(name); if (node.getName().equals(name)) return; FxContent co = ce.load(node.getReference()); FxType type = CacheAdmin.getEnvironment().getType(co.getTypeId()); List<FxPropertyAssignment> fqns = type.getAssignmentsForProperty( EJBLookup.getConfigurationEngine().get(SystemParameters.TREE_FQN_PROPERTY)); if (fqns.size() > 0) { co.setValue(fqns.get(0).getXPath(), new FxString(fqns.get(0).isMultiLang(), name)); ce.save(co); //we're done here since the content engine itself will trigger the tree table update return; } //no fqn - update the name column PreparedStatement ps = null; try { // 1 2 3 ps = con.prepareStatement("UPDATE " + getTable(mode) + " SET NAME=?, DIRTY=? WHERE ID=?"); ps.setString(1, name); ps.setBoolean(2, mode != FxTreeMode.Live); ps.setLong(3, nodeId); ps.executeUpdate(); } catch (SQLException e) { throw new FxUpdateException(LOG, e, "ex.tree.update.failed", mode.name(), e.getMessage()); } finally { try { if (ps != null) ps.close(); } catch (SQLException e) { //ignore } } }
From source file:com.flexive.core.storage.genericSQL.GenericTreeStorage.java
/** * {@inheritDoc}// w w w . ja v a 2 s. c om */ @Override public FxTreeNode getNode(Connection con, FxTreeMode mode, long nodeId) throws FxApplicationException { PreparedStatement ps = null; final FxEnvironment env = CacheAdmin.getEnvironment(); try { ps = con.prepareStatement( prepareSql(mode, mode == FxTreeMode.Live ? TREE_LIVE_GETNODE : TREE_EDIT_GETNODE)); ps.setBoolean(1, mode == FxTreeMode.Live); ps.setBoolean(2, mode == FxTreeMode.Live); ps.setLong(3, nodeId); ps.setBoolean(4, true); ResultSet rs = ps.executeQuery(); if (rs.next()) { long _id = rs.getLong(1); FxPK _ref = new FxPK(rs.getLong(2), rs.getInt(14)); int _depth = rs.getInt(3); //int _totalChilds = rs.getInt(4); int _directChilds = rs.getInt(5); String _name = rs.getString(6); long _parent = rs.getLong(7); boolean _dirty = rs.getBoolean(8); String _data = rs.getString(9); if (rs.wasNull()) _data = null; long _modified = rs.getLong(10); int _pos = rs.getInt(11); long _acl = rs.getLong(12); FxType _type = env.getType(rs.getLong(13)); long _stepACL = env.getStep(rs.getLong(15)).getAclId(); long _createdBy = rs.getLong(16); long _mandator = rs.getLong(17); UserTicket ticket = FxContext.getUserTicket(); boolean _edit; boolean _create; boolean _delete; boolean _export; boolean _relate; final boolean _system = FxContext.get().getRunAsSystem() || ticket.isGlobalSupervisor(); final List<Long> acls = fetchACLs(con, _ref, _acl); FxPermissionUtils.checkPermission(ticket, _createdBy, ACLPermission.READ, _type, _stepACL, acls, true); FxPermissionUtils.checkMandatorExistance(_mandator); FxPermissionUtils.checkTypeAvailable(_type.getId(), true); if (_system || ticket.isMandatorSupervisor() && _mandator == ticket.getMandatorId() || !_type.isUsePermissions() || ticket.isInGroup((int) UserGroup.GROUP_OWNER) && _createdBy == ticket.getUserId()) { _edit = _create = _delete = _export = _relate = true; } else { //throw exception if read is forbidden FxPermissionUtils.checkPermission(ticket, _createdBy, ACLPermission.READ, _type, _stepACL, acls, true); _edit = FxPermissionUtils.checkPermission(ticket, _createdBy, ACLPermission.EDIT, _type, _stepACL, acls, false); _relate = FxPermissionUtils.checkPermission(ticket, _createdBy, ACLPermission.RELATE, _type, _stepACL, acls, false); _delete = FxPermissionUtils.checkPermission(ticket, _createdBy, ACLPermission.DELETE, _type, _stepACL, acls, false); _export = FxPermissionUtils.checkPermission(ticket, _createdBy, ACLPermission.EXPORT, _type, _stepACL, acls, false); _create = FxPermissionUtils.checkPermission(ticket, _createdBy, ACLPermission.CREATE, _type, _stepACL, acls, false); } final String TRUE = StorageManager.getBooleanTrueExpression(); FxString label = Database.loadContentDataFxString(con, "FTEXT1024", "ID=" + _ref.getId() + " AND " + (mode == FxTreeMode.Live ? "ISMAX_VER=" + TRUE : "ISLIVE_VER=" + TRUE) + " AND TPROP=" + EJBLookup.getConfigurationEngine().get(SystemParameters.TREE_CAPTION_PROPERTY)); final FxLock lock; final long lockUser = rs.getLong(18); if (rs.wasNull()) lock = FxLock.noLockPK(); else lock = new FxLock(FxLockType.getById(rs.getInt(19)), rs.getLong(20), rs.getLong(21), lockUser, _ref); return new FxTreeNode(mode, lock, _id, _parent, _ref, LifeCycleInfoImpl.load(rs, 16, 22, 23, 24), _type.getId(), acls, _name, rs.getString(25), label, _pos, new ArrayList<FxTreeNode>(0), new ArrayList<Long>(0), _depth, _directChilds, _directChilds == 0, _dirty, _modified, _data, _edit, _create, _delete, _relate, _export); } else throw new FxLoadException("ex.tree.node.notFound", nodeId, mode); } catch (SQLException exc) { throw new FxLoadException(LOG, "ex.tree.load.failed.node", nodeId, mode, exc.getMessage()); } finally { Database.closeObjects(GenericTreeStorage.class, null, ps); } }
From source file:com.flexive.core.storage.genericSQL.GenericTreeStorage.java
/** * Update all nodes that reference the given id and set the name * * @param con an open and valid connection * @param mode tree mode// w ww.jav a 2s . c om * @param referenceId id of the referenced content * @param name the new name * @throws FxApplicationException on errors */ private void updateName(Connection con, FxTreeMode mode, long referenceId, String name) throws FxApplicationException { PreparedStatement ps = null; try { // 1 2 3 ps = con.prepareStatement("UPDATE " + getTable(mode) + " SET NAME=?, DIRTY=? WHERE REF=?"); ps.setString(1, FxFormatUtils.escapeTreePath(name)); ps.setBoolean(2, mode != FxTreeMode.Live); //live tree is never dirty ps.setLong(3, referenceId); ps.executeUpdate(); FxContext.get().setTreeWasModified(); } catch (SQLException e) { throw new FxUpdateException(LOG, e, "ex.tree.update.failed", mode.name(), e.getMessage()); } finally { try { if (ps != null) ps.close(); } catch (SQLException e) { //ignore } } }
From source file:fll.db.Queries.java
/** * Update a row in the playoff table. Assign the specified team and printed * flags for the row found by (event_division, Tournament, PlayoffRound, * LineNumber).//from www. j av a 2s .co m */ private static void updatePlayoffTable(final Connection connection, final int teamNumber, final String division, final int currentTournament, final int runNumber, final int lineNumber) throws SQLException { PreparedStatement prep = null; try { prep = connection.prepareStatement("UPDATE PlayoffData" // + " SET Team = ?" // + ", Printed = ?" // + " WHERE event_division = ?" // + " AND Tournament = ?" // + " AND run_number = ?" // + " AND LineNumber = ?"); prep.setInt(1, teamNumber); prep.setBoolean(2, false); prep.setString(3, division); prep.setInt(4, currentTournament); prep.setInt(5, runNumber); prep.setInt(6, lineNumber); prep.executeUpdate(); } finally { SQLFunctions.close(prep); } }
From source file:com.flexive.core.storage.genericSQL.GenericTreeStorage.java
/** * {@inheritDoc}//from w w w. j av a 2s . c o m */ @Override public long getIdByFQNPath(Connection con, FxTreeMode mode, long startNode, String path) throws FxApplicationException { path = path.replaceAll("/+", "/"); if ("/".equals(path)) return FxTreeNode.ROOT_NODE; PreparedStatement ps = null; try { final DBStorage storage = StorageManager.getStorageImpl(); ps = con.prepareStatement("SELECT tree_pathToID(?,?,?) " + storage.getFromDual()); ps.setLong(1, startNode); ps.setString(2, FxFormatUtils.escapeTreePath(path)); ps.setBoolean(3, mode == FxTreeMode.Live); final ResultSet rs = ps.executeQuery(); long result = -1; if (rs.next()) { result = rs.getLong(1); if (rs.wasNull()) { result = -1; } } return result; } catch (SQLException e) { throw new FxLoadException(LOG, e, "ex.db.sqlError", e.getMessage()); } finally { try { if (ps != null) ps.close(); } catch (Exception e) { //ignore } } }
From source file:com.concursive.connect.web.modules.documents.dao.FileItem.java
/** * Description of the Method//ww w . j ava2 s .co m * * @param db Description of Parameter * @return Description of the Returned Value * @throws SQLException Description of Exception */ public boolean insert(Connection db) throws SQLException { if (!isValid()) { LOG.debug("Object validation failed"); return false; } boolean result = false; boolean doCommit = false; try { if (doCommit = db.getAutoCommit()) { db.setAutoCommit(false); } StringBuffer sql = new StringBuffer(); sql.append("INSERT INTO project_files " + "(folder_id, subject, client_filename, filename, version, size, "); sql.append("enabled, downloads, "); if (entered != null) { sql.append("entered, "); } if (modified != null) { sql.append("modified, "); } sql.append(" link_module_id, link_item_id, " + " enteredby, modifiedby, default_file, image_width, image_height, comment, featured_file) " + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, "); if (entered != null) { sql.append("?, "); } if (modified != null) { sql.append("?, "); } sql.append("?, ?, ?, ?, ?, ?, ?, ?, ?) "); int i = 0; PreparedStatement pst = db.prepareStatement(sql.toString()); if (folderId > 0) { pst.setInt(++i, folderId); } else { pst.setNull(++i, java.sql.Types.INTEGER); } pst.setString(++i, subject); pst.setString(++i, clientFilename); pst.setString(++i, filename); pst.setDouble(++i, version); pst.setInt(++i, size); pst.setBoolean(++i, enabled); pst.setInt(++i, downloads); if (entered != null) { pst.setTimestamp(++i, entered); } if (modified != null) { pst.setTimestamp(++i, modified); } pst.setInt(++i, linkModuleId); pst.setInt(++i, linkItemId); pst.setInt(++i, enteredBy); pst.setInt(++i, modifiedBy); pst.setBoolean(++i, defaultFile); pst.setInt(++i, imageWidth); pst.setInt(++i, imageHeight); pst.setString(++i, comment); pst.setBoolean(++i, featuredFile); pst.execute(); pst.close(); id = DatabaseUtils.getCurrVal(db, "project_files_item_id_seq", -1); // New default item if (defaultFile) { updateDefaultRecord(db, linkModuleId, linkItemId, id); } // Insert the version information if (doVersionInsert) { FileItemVersion thisVersion = new FileItemVersion(); thisVersion.setId(this.getId()); thisVersion.setSubject(subject); thisVersion.setClientFilename(clientFilename); thisVersion.setFilename(filename); thisVersion.setVersion(version); thisVersion.setSize(size); thisVersion.setEnteredBy(enteredBy); thisVersion.setModifiedBy(modifiedBy); thisVersion.setImageWidth(imageWidth); thisVersion.setImageHeight(imageHeight); thisVersion.setComment(comment); thisVersion.insert(db); } logUpload(db); if (doCommit) { db.commit(); } result = true; } catch (Exception e) { e.printStackTrace(System.out); if (doCommit) { db.rollback(); } throw new SQLException(e.getMessage()); } finally { if (doCommit) { db.setAutoCommit(true); } } return result; }
From source file:com.draagon.meta.manager.db.driver.GenericSQLDriver.java
/** * Sets a specific value on a prepared statement *//*www . j a va2 s.c o m*/ protected void setStatementValue(PreparedStatement s, MetaField f, int index, Object value) throws SQLException { int j = index; switch (f.getType()) { case MetaField.BOOLEAN: { if (value == null) { s.setNull(j, Types.BIT); } else if (value instanceof Boolean) { s.setBoolean(j, ((Boolean) value).booleanValue()); } else { s.setBoolean(j, Boolean.valueOf(value.toString()).booleanValue()); } } break; case MetaField.BYTE: { if (value == null) { s.setNull(j, Types.TINYINT); } else if (value instanceof Byte) { s.setByte(j, ((Byte) value).byteValue()); } else { s.setByte(j, Byte.valueOf(value.toString()).byteValue()); } } break; case MetaField.SHORT: { if (value == null) { s.setNull(j, Types.SMALLINT); } else if (value instanceof Short) { s.setShort(j, ((Short) value).shortValue()); } else { s.setShort(j, Short.valueOf(value.toString()).shortValue()); } } break; case MetaField.INT: { if (value == null) { s.setNull(j, Types.INTEGER); } else if (value instanceof Integer) { s.setInt(j, ((Integer) value).intValue()); } else { s.setInt(j, Integer.valueOf(value.toString()).intValue()); } } break; case MetaField.DATE: // NOTE DATE IS TREATED AS LONG! { if (value == null) { s.setNull(j, Types.TIMESTAMP); } else if (value instanceof java.util.Date) { s.setTimestamp(j, new Timestamp(((java.util.Date) value).getTime())); } else { s.setTimestamp(j, new Timestamp(Long.valueOf(value.toString()).longValue())); } } break; case MetaField.LONG: { if (value == null) { s.setNull(j, Types.BIGINT); } else if (value instanceof Long) { s.setLong(j, ((Long) value).longValue()); } else { s.setLong(j, Long.valueOf(value.toString()).longValue()); } } break; // WARNING: This should not be a valid key case MetaField.FLOAT: { if (value == null) { s.setNull(j, Types.FLOAT); } else if (value instanceof Float) { s.setFloat(j, ((Float) value).floatValue()); } else { s.setFloat(j, Float.valueOf(value.toString()).floatValue()); } } break; // WARNING: This should not be a valid key case MetaField.DOUBLE: { if (value == null) { s.setNull(j, Types.DOUBLE); } else if (value instanceof Double) { s.setDouble(j, ((Double) value).doubleValue()); } else { s.setDouble(j, Double.valueOf(value.toString()).doubleValue()); } } break; case MetaField.STRING: if (value == null) { s.setNull(j, Types.VARCHAR); } else { s.setString(j, value.toString()); } break; case MetaField.OBJECT: //if ( value == null ) // s.setNull( j, Types.BLOB ); //else s.setObject(j, value); break; } }
From source file:org.eclipse.smila.connectivity.framework.crawler.jdbc.test.AbstractDataEnabledJdbcCrawlerTestCase.java
/** * {@inheritDoc} Called by the JUnit-Runner before execution of a testMethod of inheriting classes. Sets up a Database * fixture by performing the following steps: * <ol>/*from ww w . j a v a 2 s . co m*/ * <li>Shutdown a (potentially) running Derby engine by calling {@link DriverManager#getConnection(String)} with the * Shutdown-URL (see {@link #SHUTDOWN_URL}).</li> * <li>Delete all database files (potentially) remaining from prior test cases.</li> * <li>Configure Derby engine to log all executed SQL in the log file and to rather append to an existing logfile than * to overwrite it.</li> * <li>Get a {@link Connection} to the Derby DB and insert 100 rows of data (see source code for details). This * includes BLOB (from image file) and CLOB (from text file) fields.</li> * <li>Release allocated JDBC-resources (Statement, Connection).</li> * <li>Shutdown Derby Engine via Shutdown-URL (so the Crawler can start it up as it would normally)</li> * <li>Instantiates a {@link JdbcCrawler}.</li> * </ol> * * @see junit.framework.TestCase#setUp() */ @Override protected void setUp() throws Exception { super.setUp(); Class.forName(DRIVER_NAME).newInstance(); // shutdown embedded Derby engine (if running) // using SHUTDOWN_URL *always* results in SQLException, so we catch and ignore ... try { DriverManager.getConnection(SHUTDOWN_URL); } catch (final SQLException e) { _log.info("Testcase Setup: Shutting down Derby Engine"); } // delete existing db files final File dbDirectory = new File(DB_NAME); if (FileUtils.deleteQuietly(dbDirectory)) { _log.info("Deleted DB files of [" + DB_NAME + "] database"); } else { _log.warn("Could not delete DB files of [" + DB_NAME + "] database"); } Class.forName(DRIVER_NAME).newInstance(); final Properties p = System.getProperties(); // we want to see all sql in the db log file p.put("derby.language.logStatementText", "true"); // we don't want the logfile to be recreated each time the engine starts ... p.put("derby.infolog.append", "true"); Connection connection = DriverManager.getConnection(CONNECTION_URL); final ArrayList<Statement> statements = new ArrayList<Statement>(); // list of Statements, // PreparedStatements PreparedStatement psInsert = null; Statement createStatement = null; createStatement = connection.createStatement(); statements.add(createStatement); // create a person table... createStatement .execute("CREATE TABLE person(id int, vorname varchar(40), name varchar(40), strasse varchar(40), " + "plz varchar(5), ort varchar(40), festnetz varchar(20), body_mass_index double, vacationdays " + "integer, birthday date, scheduled_for_downsizing smallint, downsized timestamp, photo blob, cv clob)"); _log.info("Created TABLE [person]"); // insert 100 records ... psInsert = connection .prepareStatement("INSERT INTO person VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,?,?)"); statements.add(psInsert); // prepare resource files for blob / clob insertion... final File resDir = new File(RES_FOLDER_PATH); final File photoFile = new File(resDir, PHOTO_FILE_NAME); final File cvFile = new File(resDir, CV_FILE_NAME); for (int i = 1; i <= RECORDS_TO_INSERT; i++) { psInsert.setInt(COLUMN_ID, i); psInsert.setString(COLUMN_FIRSTNAME, "Mustervorname" + i); psInsert.setString(COLUMN_SURNAME, "Mustername" + i); psInsert.setString(COLUMN_STREET, "Musterstrasse " + i); psInsert.setString(COLUMN_PLZ, String.valueOf(getRandomInteger(DIGITS_IN_PLZ))); psInsert.setString(COLUMN_CITY, "Musterstadt" + i); psInsert.setString(COLUMN_PHONE, "0" + getRandomInteger(DIGITS_IN_AREA_CODE) + "-" + getRandomInteger(DIGITS_IN_EXTENSION)); psInsert.setDouble(COLUMN_BMI, (Math.random() / Math.random())); psInsert.setLong(COLUMN_VACATIONDAYS, getRandomInteger(MAX_VACATIONDAYS)); psInsert.setDate(COLUMN_BIRTHDAY, new Date(new java.util.Date().getTime())); psInsert.setBoolean(COLUMN_SCHEDULED_FOR_DOWNSIZING, ((getRandomInteger(1) % 2) == 0)); psInsert.setDate(COLUMN_DOWNSIZED, new Date(new java.util.Date().getTime())); psInsert.setBytes(COLUMN_PHOTO, FileUtils.readFileToByteArray(photoFile)); psInsert.setString(COLUMN_CV, FileUtils.readFileToString(cvFile)); psInsert.execute(); } // release all open resources to avoid unnecessary memory usage for (final Statement st : statements) { try { st.close(); } catch (final SQLException sqle) { _log.error("Could not release Statement", sqle); } } statements.clear(); // Connection try { if (connection != null) { connection.close(); connection = null; } } catch (final SQLException sqle) { _log.error("Could not release Connection", sqle); } // shutdown Derby engine AGAIN, so the Crawler can start it up as it would normally try { DriverManager.getConnection(SHUTDOWN_URL); } catch (final SQLException e) { _log.info("Testcase Setup: Shutting down Derby Engine"); } _crawler = new JdbcCrawler(); }