Example usage for java.sql PreparedStatement setBoolean

List of usage examples for java.sql PreparedStatement setBoolean

Introduction

In this page you can find the example usage for java.sql PreparedStatement setBoolean.

Prototype

void setBoolean(int parameterIndex, boolean x) throws SQLException;

Source Link

Document

Sets the designated parameter to the given Java boolean value.

Usage

From source file:org.netkernelroc.gradle.apposite.Package.java

public void install(Connection connection, File nkInstance) throws Exception {
    PackageVersion toInstall = versions.last();
    File packageFile = toInstall.download(nkInstance, connection);

    File expandedPackage = NetKernelConvention.createTempDir();
    NetKernelConvention.expandZip(packageFile, expandedPackage);

    Document manifestDocument = new Builder().build(new File(expandedPackage, "manifest.xml"));
    Nodes modulesNodes = manifestDocument.query("/manifest/module");

    final String setInstalledSql = "UPDATE PACKAGE_VERSIONS SET INSTALLED=TRUE WHERE ID=?;";
    final PreparedStatement setInstalledPS = connection.prepareStatement(setInstalledSql);

    final String addTransactionEventSql = "INSERT INTO PACKAGE_TRANSACTION_EVENTS VALUES (\n" + "    NULL,\n"
            + "    @TRANSACTIONID,\n" + "    1,\n" + "    ?\n" + ");";
    final PreparedStatement addTransactionEventPS = connection.prepareStatement(addTransactionEventSql);

    final String addModuleSql = "MERGE INTO MODULES (\n" + "    PACKAGEVID,\n" + "    IDENTITY,\n"
            + "    VERSION,\n" + "    LOCALSRC,\n" + "    RUNLEVEL,\n" + "    EXPANDED\n" + ")\n"
            + "KEY (IDENTITY, VERSION)\n" + "VALUES (\n" + "    ?,\n" + "    ?,\n" + "    ?,\n" + "    ?,\n"
            + "    ?,\n" + "    ?\n" + ");";
    final PreparedStatement addModulePS = connection.prepareStatement(addModuleSql);

    setInstalledPS.clearParameters();//from ww w  .  ja  v a 2  s .c o m
    setInstalledPS.setLong(1, toInstall.getId());
    setInstalledPS.executeUpdate();

    addTransactionEventPS.clearParameters();
    addTransactionEventPS.setLong(1, id);
    addTransactionEventPS.executeUpdate();

    for (int moduleI = 0; moduleI < modulesNodes.size(); moduleI++) {
        Node moduleNode = modulesNodes.get(moduleI);

        String uri = moduleNode.query("uri").get(0).getValue();
        String version = moduleNode.query("version").get(0).getValue();
        int runLevel = Integer.parseInt(moduleNode.query("runlevel").get(0).getValue());
        String source = moduleNode.query("source").get(0).getValue();
        boolean expand = Boolean.parseBoolean(moduleNode.query("expand").get(0).getValue());

        Integer[] versionArray = RepositorySet.stringArrayToIntArray(version.split("\\."));

        File targetFile;
        if (uri.startsWith("urn:com:ten60:core:")) {
            expand = false;
            targetFile = new File(nkInstance, "lib");
        } else {
            targetFile = new File(nkInstance, "modules");
        }

        File moduleJar = new File(expandedPackage, source);

        String baseName = uri.replaceAll(":", ".") + "-" + version;

        File target;
        File jarTarget = new File(targetFile, baseName + ".jar");
        File expandedTarget = new File(targetFile, baseName);

        if (expand) {
            target = expandedTarget;
        } else {
            target = jarTarget;
        }

        if (target.exists()) {
            System.out.println("Not moving module into place as it already exists");
        } else {
            if (expand) {
                System.out.println("Expanding module " + uri + " to " + expandedTarget.getAbsolutePath());
                NetKernelConvention.expandZip(moduleJar, expandedTarget);
            } else {
                System.out.println("Moving module " + uri + " to " + jarTarget.getAbsolutePath());
                FileUtils.moveFile(moduleJar, jarTarget);
            }
        }

        addModulePS.clearParameters();
        addModulePS.setLong(1, toInstall.getId());
        addModulePS.setString(2, uri);
        addModulePS.setObject(3, versionArray);
        addModulePS.setString(4, nkInstance.toURI().relativize(target.toURI()).getPath());
        addModulePS.setInt(5, runLevel);
        addModulePS.setBoolean(6, expand);
        addModulePS.executeUpdate();
    }
    FileUtils.deleteDirectory(expandedPackage);

    latestInstalledVersion = toInstall;
}

From source file:org.rhq.enterprise.server.installer.ServerInstallUtil.java

/**
 * Persists the storage nodes to the database only if no storage node entities already exist. This method is used
 * to persist storage nodes created from the rhq.storage.nodes server configuration property. The only time those
 * seed nodes should be created is during an initial server installation. After the initial installation storage
 * nodes should be created using <code>rhqctl install</code>. This ensures that any necessary cluster maintenance
 * tasks will be performed.//from www .j a  va2 s. c o m
 *
 * @param serverProperties the server properties
 * @param password clear text password to connect to the database
 * @param storageNodes the {@link StorageNode storage nodes} to persist
 * @throws Exception
 */
public static void persistStorageNodesIfNecessary(HashMap<String, String> serverProperties, String password,
        Set<StorageNode> storageNodes) throws Exception {
    DatabaseType db = null;
    Connection connection = null;
    Statement queryStatement = null;
    ResultSet resultSet = null;
    PreparedStatement insertStorageNode = null;

    try {
        String dbUrl = serverProperties.get(ServerProperties.PROP_DATABASE_CONNECTION_URL);
        String userName = serverProperties.get(ServerProperties.PROP_DATABASE_USERNAME);
        connection = getDatabaseConnection(dbUrl, userName, password);
        db = DatabaseTypeFactory.getDatabaseType(connection);

        if (!(db instanceof PostgresqlDatabaseType || db instanceof OracleDatabaseType)) {
            throw new IllegalArgumentException("Unknown database type, can't continue: " + db);
        }

        queryStatement = connection.createStatement();
        resultSet = queryStatement.executeQuery("SELECT count(id) FROM rhq_storage_node");
        resultSet.next();

        if (resultSet.getInt(1) == 0) {
            connection.setAutoCommit(false);

            try {
                LOG.info(
                        "Persisting to database new storage nodes for values specified in server configuration property [rhq.storage.nodes]");

                insertStorageNode = connection.prepareStatement(
                        "INSERT INTO rhq_storage_node (id, address, cql_port, operation_mode, ctime, mtime, maintenance_pending) "
                                + "VALUES (?, ?, ?, ?, ?, ?, ?)");

                int id = 1001;
                for (StorageNode storageNode : storageNodes) {
                    insertStorageNode.setInt(1, id);
                    insertStorageNode.setString(2, storageNode.getAddress());
                    insertStorageNode.setInt(3, storageNode.getCqlPort());
                    insertStorageNode.setString(4, StorageNode.OperationMode.INSTALLED.toString());
                    insertStorageNode.setLong(5, System.currentTimeMillis());
                    insertStorageNode.setLong(6, System.currentTimeMillis());
                    insertStorageNode.setBoolean(7, false);

                    insertStorageNode.executeUpdate();
                    id += 1;
                }

                connection.commit();
            } catch (SQLException e) {
                LOG.error("Failed to persist to database the storage nodes specified by server configuration "
                        + "property [rhq.storage.nodes]. Transaction will be rolled back.", e);
                connection.rollback();
                throw e;
            }
        } else {
            LOG.info(
                    "Storage nodes already exist in database. Server configuration property [rhq.storage.nodes] will be ignored.");
        }

    } finally {
        if (db != null) {
            db.closeResultSet(resultSet);
            db.closeStatement(queryStatement);
            db.closeStatement(insertStorageNode);
            db.closeConnection(connection);
        }
    }
}

From source file:com.krawler.esp.servlets.deskeramob.java

public static String createProject(Connection conn, HttpServletRequest request, String companyid,
        String subdomain, String userid) throws ServiceException {
    String status = "";
    DiskFileUpload fu = new DiskFileUpload();
    java.util.List fileItems = null;
    PreparedStatement pstmt = null;
    String imageName = "";
    try {/*from  www  .ja va  2s.c  o  m*/
        fileItems = fu.parseRequest(request);
    } catch (FileUploadException e) {
        throw ServiceException.FAILURE("Admin.createProject", e);
    }

    java.util.HashMap arrParam = new java.util.HashMap();
    java.util.Iterator k = null;
    for (k = fileItems.iterator(); k.hasNext();) {
        FileItem fi1 = (FileItem) k.next();
        arrParam.put(fi1.getFieldName(), fi1.getString());
    }
    try {
        pstmt = conn
                .prepareStatement("select count(projectid) from project where companyid =? AND archived = 0");
        pstmt.setString(1, companyid);
        ResultSet rs = pstmt.executeQuery();
        int noProjects = 0;
        int maxProjects = 0;
        if (rs.next()) {
            noProjects = rs.getInt(1);
        }
        pstmt = conn.prepareStatement("select maxprojects from company where companyid =?");
        pstmt.setString(1, companyid);
        rs = pstmt.executeQuery();
        if (rs.next()) {
            maxProjects = rs.getInt(1);
        }
        if (noProjects == maxProjects) {
            return "The maximum limit for projects for this company has already reached";
        }
    } catch (SQLException e) {
        throw ServiceException.FAILURE("ProfileHandler.getPersonalInfo", e);
    }
    try {
        String projectid = UUID.randomUUID().toString();
        String projName = StringUtil.serverHTMLStripper(arrParam.get("projectname").toString()
                .replaceAll("[^\\w|\\s|'|\\-|\\[|\\]|\\(|\\)]", "").trim());
        String nickName = AdminServlet.makeNickName(conn, projName, 1);
        if (StringUtil.isNullOrEmpty(projName)) {
            status = "failure";
        } else {
            String qry = "INSERT INTO project (projectid,projectname,description,image,companyid, nickname) VALUES (?,?,?,?,?,?)";
            pstmt = conn.prepareStatement(qry);
            pstmt.setString(1, projectid);
            pstmt.setString(2, projName);
            pstmt.setString(3, arrParam.get("aboutproject").toString());
            pstmt.setString(4, imageName);
            pstmt.setString(5, companyid);
            pstmt.setString(6, nickName);
            int df = pstmt.executeUpdate();
            if (df != 0) {
                pstmt = conn.prepareStatement(
                        "INSERT INTO projectmembers (projectid, userid, status, inuseflag, planpermission) "
                                + "VALUES (?, ?, ?, ?, ?)");
                pstmt.setString(1, projectid);
                pstmt.setString(2, userid);
                pstmt.setInt(3, 4);
                pstmt.setBoolean(4, true);
                pstmt.setInt(5, 0);
                pstmt.executeUpdate();
            }
            //                        /DbUtil.executeUpdate(conn,qry,new Object[] { projectid,projName,arrParam.get("aboutproject"), imageName,companyid, nickName});
            if (arrParam.get("image").toString().length() != 0) {
                genericFileUpload uploader = new genericFileUpload();
                uploader.doPost(fileItems, projectid, StorageHandler.GetProfileImgStorePath());
                if (uploader.isUploaded()) {
                    pstmt = null;
                    //                                        DbUtil.executeUpdate(conn,
                    //                                                        "update project set image=? where projectid = ?",
                    //                                                        new Object[] {
                    //                                                                        ProfileImageServlet.ImgBasePath + projectid
                    //                                                                                        + uploader.getExt(), projectid });

                    pstmt = conn.prepareStatement("update project set image=? where projectid = ?");
                    pstmt.setString(1, ProfileImageServlet.ImgBasePath + projectid + uploader.getExt());
                    pstmt.setString(2, projectid);
                    pstmt.executeUpdate();
                    imageName = projectid + uploader.getExt();
                }
            }
            com.krawler.esp.handlers.Forum.setStatusProject(conn, userid, projectid, 4, 0, "", subdomain);
            status = "success";
            AdminServlet.setDefaultWorkWeek(conn, projectid);
            conn.commit();
        }
    } catch (ConfigurationException e) {
        status = "failure";
        throw ServiceException.FAILURE("Admin.createProject", e);
    } catch (SQLException e) {
        status = "failure";
        throw ServiceException.FAILURE("Admin.createProject", e);
    }
    return status;
}

From source file:com.alfaariss.oa.engine.session.jdbc.JDBCSessionFactory.java

/**
 * Uses a batch update to persist all supplied sessions.
 * @param sessions The sessions to persist.
 * @throws PersistenceException If persistance fails.
 * //from  w  w  w. j av a 2 s.c  om
 * @see IEntityManager#persist(IEntity[])
 * @see PreparedStatement#addBatch()
 */
public void persist(JDBCSession[] sessions) throws PersistenceException {
    if (sessions == null)
        throw new IllegalArgumentException("Suplied session array is empty or invalid");

    Connection connection = null;
    PreparedStatement psInsert = null;
    PreparedStatement psDelete = null;
    PreparedStatement psUpdate = null;
    try {
        connection = _oDataSource.getConnection(); //Manage connection
        connection.setAutoCommit(false);

        psInsert = connection.prepareStatement(_sInsertQuery);
        psDelete = connection.prepareStatement(_sRemoveQuery);
        psUpdate = connection.prepareStatement(_sUpdateQuery);

        for (JDBCSession session : sessions) {
            String id = session.getId();
            if (id == null) {
                byte[] baId = new byte[ISession.ID_BYTE_LENGTH];
                do {
                    _random.nextBytes(baId);
                    try {
                        id = ModifiedBase64.encode(baId);
                    } catch (UnsupportedEncodingException e) {
                        _logger.error("Could not create id for byte[]: " + baId, e);
                        throw new PersistenceException(SystemErrors.ERROR_INTERNAL);
                    }
                } while (exists(id)); //Key allready exists   

                session.setId(id);
                //Update expiration time
                long expiration = System.currentTimeMillis() + _lExpiration;
                session.setTgtExpTime(expiration);
                psInsert.setString(1, id);
                psInsert.setString(2, session.getTGTId());
                psInsert.setInt(3, session.getState().ordinal());
                psInsert.setString(4, session.getRequestorId());
                psInsert.setString(5, session.getProfileURL());
                psInsert.setBytes(6, Serialize.encode(session.getUser()));
                psInsert.setTimestamp(7, new Timestamp(expiration));
                psInsert.setBoolean(8, session.isForcedAuthentication());
                psInsert.setBoolean(9, session.isPassive());
                psInsert.setBytes(10, Serialize.encode(session.getAttributes()));
                psInsert.setString(11, session.getForcedUserID());
                psInsert.setBytes(12, Serialize.encode(session.getLocale()));
                psInsert.setBytes(13, Serialize.encode(session.getSelectedAuthNProfile()));
                psInsert.setBytes(14, Serialize.encode(session.getAuthNProfiles()));
                psInsert.addBatch();
            } else if (session.isExpired()) //Expired
            {
                _logger.info("Session Expired: " + id);

                _eventLogger.info(new UserEventLogItem(session, null, UserEvent.SESSION_EXPIRED, this, null));

                psDelete.setString(1, id);
                psDelete.addBatch();
            } else //Update
            {
                //Update expiration time
                long expiration = System.currentTimeMillis() + _lExpiration;
                session.setTgtExpTime(expiration);
                psUpdate.setString(1, session.getTGTId());
                psUpdate.setInt(2, session.getState().ordinal());
                psUpdate.setString(3, session.getRequestorId());
                psUpdate.setString(4, session.getProfileURL());
                psUpdate.setBytes(5, Serialize.encode(session.getUser()));
                psUpdate.setTimestamp(6, new Timestamp(expiration));
                psUpdate.setBoolean(7, session.isForcedAuthentication());
                psInsert.setBoolean(8, session.isPassive());
                psUpdate.setBytes(9, Serialize.encode(session.getAttributes()));
                psUpdate.setString(10, session.getForcedUserID());
                psUpdate.setBytes(11, Serialize.encode(session.getLocale()));
                psUpdate.setBytes(12, Serialize.encode(session.getSelectedAuthNProfile()));
                psUpdate.setBytes(13, Serialize.encode(session.getAuthNProfiles()));
                psUpdate.setString(14, id);
                psUpdate.addBatch();
            }
        }
        try {
            int[] iResult = psInsert.executeBatch();
            if (_logger.isDebugEnabled()) {
                int iTotalAdded = 0;
                for (int i : iResult)
                    iTotalAdded += i;

                _logger.info(iTotalAdded + " new session(s) added by batch");
            }
        } catch (SQLException e) {
            _logger.error("Could not execute insert batch", e);
            throw new PersistenceException(SystemErrors.ERROR_RESOURCE_INSERT);
        }
        try {
            int[] iResult = psDelete.executeBatch();
            if (_logger.isDebugEnabled()) {
                int iTotalDeleted = 0;
                for (int i : iResult)
                    iTotalDeleted += i;

                _logger.info(iTotalDeleted + " session(s) deleted by batch");
            }

        } catch (SQLException e) {
            _logger.error("Could not execute delete batch", e);
            throw new PersistenceException(SystemErrors.ERROR_RESOURCE_REMOVE);
        }
        try {
            int[] iResult = psUpdate.executeBatch();
            if (_logger.isDebugEnabled()) {
                int iTotalUpdated = 0;
                for (int i : iResult)
                    iTotalUpdated += i;

                _logger.info(iTotalUpdated + " session(s) updated by batch");
            }
        } catch (SQLException e) {
            _logger.error("Could not execute update batch", e);
            throw new PersistenceException(SystemErrors.ERROR_RESOURCE_UPDATE);
        }

        connection.commit();
    } catch (SQLException e) {
        _logger.error("Could not execute batch", e);
        try {
            if (connection != null)
                connection.rollback();
        } catch (SQLException e1) {
            _logger.warn("Could not rollback batch", e);
        }

        throw new PersistenceException(SystemErrors.ERROR_INTERNAL);
    } catch (PersistenceException e) {
        try {
            if (connection != null)
                connection.rollback();
        } catch (SQLException e1) {
            _logger.warn("Could not rollback batch", e);
        }
        throw e;
    } catch (Exception e) {
        _logger.error("Internal error during session persist", e);
        throw new PersistenceException(SystemErrors.ERROR_RESOURCE_CONNECT);
    } finally {
        try {
            if (psInsert != null)
                psInsert.close();
        } catch (SQLException e) {
            _logger.debug("Could not close insert statement", e);
        }
        try {
            if (psDelete != null)
                psDelete.close();
        } catch (SQLException e) {
            _logger.debug("Could not close delete statement", e);
        }
        try {
            if (psUpdate != null)
                psUpdate.close();
        } catch (SQLException e) {
            _logger.debug("Could not close update statement", e);
        }
        try {
            if (connection != null)
                connection.close();
        } catch (SQLException e) {
            _logger.debug("Could not close connection", e);
        }
    }
}

From source file:org.apache.sqoop.repository.derby.DerbyRepositoryHandler.java

@Override
public void enableJob(long jobId, boolean enabled, Connection conn) {
    PreparedStatement enableConn = null;

    try {/*from  w w  w.j  a va  2s. c  o m*/
        enableConn = conn.prepareStatement(STMT_ENABLE_JOB);
        enableConn.setBoolean(1, enabled);
        enableConn.setLong(2, jobId);
        enableConn.executeUpdate();
    } catch (SQLException ex) {
        logException(ex, jobId);
        throw new SqoopException(DerbyRepoError.DERBYREPO_0043, ex);
    } finally {
        closeStatements(enableConn);
    }
}

From source file:org.apache.sqoop.repository.derby.DerbyRepositoryHandler.java

@Override
public void enableLink(long connectionId, boolean enabled, Connection conn) {
    PreparedStatement enableConn = null;

    try {/*from w ww .jav a  2  s.c o  m*/
        enableConn = conn.prepareStatement(STMT_ENABLE_LINK);
        enableConn.setBoolean(1, enabled);
        enableConn.setLong(2, connectionId);
        enableConn.executeUpdate();
    } catch (SQLException ex) {
        logException(ex, connectionId);
        throw new SqoopException(DerbyRepoError.DERBYREPO_0042, ex);
    } finally {
        closeStatements(enableConn);
    }
}

From source file:com.concursive.connect.web.modules.login.dao.User.java

/**
 * Description of the Method//  w w w .  jav a  2 s . co m
 *
 * @param db Description of the Parameter
 * @return Description of the Return Value
 * @throws SQLException Description of the Exception
 */
public int update(Connection db) throws SQLException {
    // Update the user
    PreparedStatement pst = db.prepareStatement("UPDATE users "
            + "SET first_name = ?, last_name = ?, username = ?, " + (password != null ? "password = ?, " : "")
            + "company = ?, email = ?, enabled = ?, access_admin = ?, expiration = ?, " + "access_invite = ?, "
            + "account_size = ?, access_add_projects = ?, "
            + "access_contacts_view_all = ?, access_contacts_edit_all = ?, watch_forums = ?, " + "modified = "
            + DatabaseUtils.getCurrentTimestamp(db) + ", modifiedby = ?, "
            + "connect_crm_admin = ?, connect_crm_manager = ? " + "WHERE user_id = ? ");
    int i = 0;
    pst.setString(++i, firstName);
    pst.setString(++i, lastName);
    pst.setString(++i, username);
    if (password != null) {
        pst.setString(++i, password);
    }
    pst.setString(++i, company);
    pst.setString(++i, email);
    pst.setBoolean(++i, enabled);
    pst.setBoolean(++i, accessAdmin);
    DatabaseUtils.setTimestamp(pst, ++i, expiration);
    pst.setBoolean(++i, accessInvite);
    DatabaseUtils.setInt(pst, ++i, accountSize);
    pst.setBoolean(++i, accessAddProjects);
    pst.setBoolean(++i, accessViewAllContacts);
    pst.setBoolean(++i, accessEditAllContacts);
    pst.setBoolean(++i, watchForums);
    pst.setInt(++i, modifiedBy);
    pst.setBoolean(++i, connectCRMAdmin);
    pst.setBoolean(++i, connectCRMManager);
    pst.setInt(++i, id);
    int count = pst.executeUpdate();
    pst.close();
    CacheUtils.invalidateValue(Constants.SYSTEM_USER_CACHE, id);
    return count;
}

From source file:org.exoplatform.social.core.mysql.storage.ActivityMysqlStorageImpl.java

/**
 * update stream item's comment info/* ww w.j a  v a 2  s.  c o  m*/
 */
private void updateStreamItemTime(String activityId, Long time, boolean isHidden) {
    //insert to mysql stream_item table
    Connection dbConnection = null;
    PreparedStatement preparedStatement = null;

    StringBuilder sql = new StringBuilder();
    sql.append("update stream_item").append(" set time = ?, hidable = ?").append(" where activityId = ?");

    try {
        dbConnection = dbConnect.getDBConnection();
        preparedStatement = dbConnection.prepareStatement(sql.toString());
        preparedStatement.setLong(1, time);
        preparedStatement.setBoolean(2, isHidden);
        preparedStatement.setString(3, activityId);

        preparedStatement.executeUpdate();

        LOG.debug("stream item updated");

    } catch (SQLException e) {

        LOG.error("error in stream item update:", e.getMessage());

    } finally {
        try {
            if (preparedStatement != null) {
                preparedStatement.close();
            }

            if (dbConnection != null) {
                dbConnection.close();
            }
        } catch (SQLException e) {
            LOG.error("Cannot close statement or connection:", e.getMessage());
        }
    }
}

From source file:org.apache.ddlutils.platform.PlatformImplBase.java

/**
 * This is the core method to set the parameter of a prepared statement to a given value.
 * The primary purpose of this method is to call the appropriate method on the statement,
 * and to give database-specific implementations the ability to change this behavior.
 * /*from w  w w  .j  av  a  2 s .  c o m*/
 * @param statement The statement
 * @param sqlIndex  The parameter index
 * @param typeCode  The JDBC type code
 * @param value     The value
 * @throws SQLException If an error occurred while setting the parameter value
 */
protected void setStatementParameterValue(PreparedStatement statement, int sqlIndex, int typeCode, Object value)
        throws SQLException {
    if (value == null) {
        statement.setNull(sqlIndex, typeCode);
    } else if (value instanceof String) {
        statement.setString(sqlIndex, (String) value);
    } else if (value instanceof byte[]) {
        statement.setBytes(sqlIndex, (byte[]) value);
    } else if (value instanceof Boolean) {
        statement.setBoolean(sqlIndex, ((Boolean) value).booleanValue());
    } else if (value instanceof Byte) {
        statement.setByte(sqlIndex, ((Byte) value).byteValue());
    } else if (value instanceof Short) {
        statement.setShort(sqlIndex, ((Short) value).shortValue());
    } else if (value instanceof Integer) {
        statement.setInt(sqlIndex, ((Integer) value).intValue());
    } else if (value instanceof Long) {
        statement.setLong(sqlIndex, ((Long) value).longValue());
    } else if (value instanceof BigDecimal) {
        // setObject assumes a scale of 0, so we rather use the typed setter
        statement.setBigDecimal(sqlIndex, (BigDecimal) value);
    } else if (value instanceof Float) {
        statement.setFloat(sqlIndex, ((Float) value).floatValue());
    } else if (value instanceof Double) {
        statement.setDouble(sqlIndex, ((Double) value).doubleValue());
    } else {
        statement.setObject(sqlIndex, value, typeCode);
    }
}

From source file:com.flexive.ejb.beans.ScriptingEngineBean.java

/**
* {@inheritDoc}/*w  ww .ja va2s .  co m*/
* @since 3.1.2
*/
@Override
public FxScriptSchedule updateScriptSchedule(FxScriptScheduleEdit scriptSchedule)
        throws FxApplicationException {
    FxPermissionUtils.checkRole(FxContext.getUserTicket(), Role.ScriptManagement);
    FxPermissionUtils.checkRole(FxContext.getUserTicket(), Role.ScriptExecution);
    FxScriptSchedule ss;
    Connection con = null;
    PreparedStatement ps = null;
    String sql;
    boolean success = false;
    //check script schedule existence
    CacheAdmin.getEnvironment().getScriptSchedule(scriptSchedule.getId());
    //check script existence
    FxScriptInfo si = CacheAdmin.getEnvironment().getScript(scriptSchedule.getScriptId());
    //check for valid script event
    if (si.getEvent() != FxScriptEvent.Manual)
        throw new FxConstraintViolationException("ex.scripting.schedule.wrongScriptEvent");
    //check consistency
    checkScriptScheduleConsistency(scriptSchedule);
    try {
        ss = new FxScriptSchedule(scriptSchedule.getId(), scriptSchedule.getScriptId(),
                scriptSchedule.getName(), scriptSchedule.isActive(), scriptSchedule.getStartTime(),
                scriptSchedule.getEndTime(), scriptSchedule.getRepeatInterval(),
                scriptSchedule.getRepeatTimes(), scriptSchedule.getCronString());
        // Obtain a database connection
        con = Database.getDbConnection(); //        1        2          3            4            5                 6            7               8         9
        sql = "UPDATE " + TBL_SCRIPT_SCHEDULES
                + " SET SNAME=?, ACTIVE=?, STARTTIME=?, ENDTIME=?, REPEATINTERVAL=?, REPEATTIMES=?, CRONSTRING=? WHERE ID=? AND SCRIPT=?";
        ps = con.prepareStatement(sql);
        ps.setString(1, ss.getName());
        ps.setBoolean(2, ss.isActive());
        ps.setTimestamp(3, new Timestamp(ss.getStartTime().getTime()));
        ps.setTimestamp(4, ss.getEndTime() == null ? null : new Timestamp(ss.getEndTime().getTime()));
        ps.setLong(5, ss.getRepeatInterval());
        ps.setInt(6, ss.getRepeatTimes());
        ps.setString(7, ss.getCronString());
        ps.setLong(8, ss.getId());
        ps.setLong(9, ss.getScriptId());
        ps.executeUpdate();
        if (EJBLookup.getTimerService().isInstalled()) {
            EJBLookup.getTimerService().updateScriptSchedule(ss);
        }
        success = true;
    } catch (SQLException exc) {
        throw new FxUpdateException(LOG, exc, "ex.scripting.schedule.update.failed", scriptSchedule.getName(),
                exc.getMessage());
    } finally {
        Database.closeObjects(ScriptingEngineBean.class, con, ps);
        if (!success)
            EJBUtils.rollback(ctx);
        else
            StructureLoader.reloadScripting(FxContext.get().getDivisionId());
    }
    return ss;
}