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.sakaiproject.db.impl.BasicSqlService.java

/**
 * Prepare a prepared statement with fields.
 * //from   w  w w. j  ava  2 s  . c  o  m
 * @param pstmt
 *        The prepared statement to fill in.
 * @param fields
 *        The Object array of values to fill in.
 * @return the next pos that was not filled in.
 * @throws UnsupportedEncodingException
 */
protected int prepareStatement(PreparedStatement pstmt, Object[] fields)
        throws SQLException, UnsupportedEncodingException {
    if (LOG.isDebugEnabled()) {
        LOG.debug(
                "prepareStatement(PreparedStatement " + pstmt + ", Object[] " + Arrays.toString(fields) + ")");
    }

    // put in all the fields
    int pos = 1;
    if ((fields != null) && (fields.length > 0)) {
        for (int i = 0; i < fields.length; i++) {
            if (fields[i] == null || (fields[i] instanceof String && ((String) fields[i]).length() == 0)) {
                // treat a Java null as an SQL null,
                // and ALSO treat a zero-length Java string as an SQL null
                // This makes sure that Oracle vs MySQL use the same value
                // for null.
                sqlServiceSql.setNull(pstmt, pos);

                pos++;
            } else if (fields[i] instanceof Time) {
                Time t = (Time) fields[i];
                sqlServiceSql.setTimestamp(pstmt, new Timestamp(t.getTime()), m_cal, pos);
                pos++;
            }
            //KNL-558 an obvious one
            else if (fields[i] instanceof java.util.Date) {
                java.util.Date d = (java.util.Date) fields[i];
                sqlServiceSql.setTimestamp(pstmt, new Timestamp(d.getTime()), m_cal, pos);
                pos++;
            } else if (fields[i] instanceof Long) {
                long l = ((Long) fields[i]).longValue();
                pstmt.setLong(pos, l);
                pos++;
            } else if (fields[i] instanceof Integer) {
                int n = ((Integer) fields[i]).intValue();
                pstmt.setInt(pos, n);
                pos++;
            } else if (fields[i] instanceof Float) {
                float f = ((Float) fields[i]).floatValue();
                pstmt.setFloat(pos, f);
                pos++;
            } else if (fields[i] instanceof Boolean) {
                pstmt.setBoolean(pos, ((Boolean) fields[i]).booleanValue());
                pos++;
            } else if (fields[i] instanceof byte[]) {
                sqlServiceSql.setBytes(pstmt, (byte[]) fields[i], pos);
                pos++;
            }

            // %%% support any other types specially?
            else {
                String value = fields[i].toString();
                sqlServiceSql.setBytes(pstmt, value, pos);
                pos++;
            }
        }
    }

    return pos;
}

From source file:dk.netarkivet.harvester.datamodel.JobDBDAO.java

/**
 * Update a Job in persistent storage.// ww w .  j ava 2s .  com
 *
 * @param job The Job to update
 * @throws ArgumentNotValid If the Job is null
 * @throws UnknownID If the Job doesn't exist in the DAO
 * @throws IOFailure If writing the job to persistent storage fails
 * @throws PermissionDenied If the job has been updated behind our backs
 */
@Override
public synchronized void update(Job job) {
    ArgumentNotValid.checkNotNull(job, "job");

    Connection connection = HarvestDBConnection.get();
    // Not done as a transaction as it's awfully big.
    // TODO Make sure that a failed job update does... what?
    PreparedStatement statement = null;
    try {
        final Long jobID = job.getJobID();
        if (!exists(connection, jobID)) {
            throw new UnknownID("Job id " + jobID + " is not known in persistent storage");
        }

        connection.setAutoCommit(false);
        statement = connection.prepareStatement("UPDATE jobs SET " + "harvest_id = ?, status = ?, channel = ?, "
                + "forcemaxcount = ?, forcemaxbytes = ?, " + "forcemaxrunningtime = ?," + "orderxml = ?, "
                + "orderxmldoc = ?, seedlist = ?, " + "harvest_num = ?, harvest_errors = ?, "
                + "harvest_error_details = ?, upload_errors = ?, " + "upload_error_details = ?, startdate = ?,"
                + "enddate = ?, num_configs = ?, edition = ?, " + "submitteddate = ?, creationdate = ?, "
                + "resubmitted_as_job = ?, harvestname_prefix = ?," + "snapshot = ?"
                + " WHERE job_id = ? AND edition = ?");
        statement.setLong(1, job.getOrigHarvestDefinitionID());
        statement.setInt(2, job.getStatus().ordinal());
        statement.setString(3, job.getChannel());
        statement.setLong(4, job.getForceMaxObjectsPerDomain());
        statement.setLong(5, job.getMaxBytesPerDomain());
        statement.setLong(6, job.getMaxJobRunningTime());
        DBUtils.setStringMaxLength(statement, 7, job.getOrderXMLName(), Constants.MAX_NAME_SIZE, job,
                "order.xml name");
        final String orderreader = job.getOrderXMLdoc().asXML();
        DBUtils.setClobMaxLength(statement, 8, orderreader, Constants.MAX_ORDERXML_SIZE, job, "order.xml");
        DBUtils.setClobMaxLength(statement, 9, job.getSeedListAsString(), Constants.MAX_COMBINED_SEED_LIST_SIZE,
                job, "seedlist");
        statement.setInt(10, job.getHarvestNum()); // Not in job yet
        DBUtils.setStringMaxLength(statement, 11, job.getHarvestErrors(), Constants.MAX_ERROR_SIZE, job,
                "harvest_error");
        DBUtils.setStringMaxLength(statement, 12, job.getHarvestErrorDetails(), Constants.MAX_ERROR_DETAIL_SIZE,
                job, "harvest_error_details");
        DBUtils.setStringMaxLength(statement, 13, job.getUploadErrors(), Constants.MAX_ERROR_SIZE, job,
                "upload_error");
        DBUtils.setStringMaxLength(statement, 14, job.getUploadErrorDetails(), Constants.MAX_ERROR_DETAIL_SIZE,
                job, "upload_error_details");
        long edition = job.getEdition() + 1;
        DBUtils.setDateMaybeNull(statement, 15, job.getActualStart());
        DBUtils.setDateMaybeNull(statement, 16, job.getActualStop());
        statement.setInt(17, job.getDomainConfigurationMap().size());
        statement.setLong(18, edition);
        DBUtils.setDateMaybeNull(statement, 19, job.getSubmittedDate());
        DBUtils.setDateMaybeNull(statement, 20, job.getCreationDate());
        DBUtils.setLongMaybeNull(statement, 21, job.getResubmittedAsJob());
        statement.setString(22, job.getHarvestFilenamePrefix());
        statement.setBoolean(23, job.isSnapshot());
        statement.setLong(24, job.getJobID());
        statement.setLong(25, job.getEdition());
        final int rows = statement.executeUpdate();
        if (rows == 0) {
            String message = "Edition " + job.getEdition() + " has expired, not updating";
            log.debug(message);
            throw new PermissionDenied(message);
        }
        createJobConfigsEntries(connection, job);
        connection.commit();
        job.setEdition(edition);
    } catch (SQLException e) {
        String message = "SQL error updating job " + job + " in database" + "\n"
                + ExceptionUtils.getSQLExceptionCause(e);
        log.warn(message, e);
        throw new IOFailure(message, e);
    } finally {
        DBUtils.rollbackIfNeeded(connection, "update job", job);
        HarvestDBConnection.release(connection);
    }
}

From source file:com.flexive.core.storage.genericSQL.GenericHierarchicalStorage.java

/**
 * Create a new main entry/*w  w w  .j av  a2 s. c o m*/
 *
 * @param con     an open and valid connection
 * @param newId   the id to use
 * @param version the version to use
 * @param content content to create
 * @return primary key of the created content
 * @throws FxCreateException on errors
 */
protected FxPK createMainEntry(Connection con, long newId, int version, FxContent content,
        boolean keepCreationLCI) throws FxCreateException {
    PreparedStatement ps = null;
    FxPK pk = new FxPK(newId, version);
    try {
        ps = con.prepareStatement(CONTENT_MAIN_INSERT);
        ps.setLong(1, newId);
        ps.setInt(2, version);
        ps.setLong(3, content.getTypeId());
        ps.setLong(4, content.getAclIds().size() > 1 ? ACL.NULL_ACL_ID : content.getAclIds().get(0));
        ps.setLong(5, content.getStepId());
        ps.setInt(6, 1); //if creating a new version, max_ver will be fixed in a later step
        ps.setInt(7, content.isLiveVersion() ? 1 : 0);
        ps.setBoolean(8, content.isMaxVersion());
        ps.setBoolean(9, content.isLiveVersion());
        ps.setBoolean(10, content.isActive());
        ps.setInt(11, (int) content.getMainLanguage());
        if (content.isRelation()) {
            ps.setLong(12, content.getRelatedSource().getId());
            ps.setInt(13, content.getRelatedSource().getVersion());
            ps.setLong(14, content.getRelatedDestination().getId());
            ps.setInt(15, content.getRelatedDestination().getVersion());
            ps.setLong(16, content.getRelatedSourcePosition());
            ps.setLong(17, content.getRelatedDestinationPosition());
        } else {
            ps.setNull(12, java.sql.Types.NUMERIC);
            ps.setNull(13, java.sql.Types.NUMERIC);
            ps.setNull(14, java.sql.Types.NUMERIC);
            ps.setNull(15, java.sql.Types.NUMERIC);
            ps.setNull(16, java.sql.Types.NUMERIC);
            ps.setNull(17, java.sql.Types.NUMERIC);
        }

        if (!content.isForceLifeCycle()) {
            final long userId = FxContext.getUserTicket().getUserId();
            final long now = System.currentTimeMillis();
            if (keepCreationLCI) {
                // keep created_at of existing content
                ps.setLong(18, content.getValue(FxLargeNumber.class, "/CREATED_BY").getBestTranslation());
                ps.setLong(19,
                        content.getValue(FxDateTime.class, "/CREATED_AT").getBestTranslation().getTime());
            } else {
                ps.setLong(18, userId);
                ps.setLong(19, now);
            }
            ps.setLong(20, userId);
            ps.setLong(21, now);
        } else {
            ps.setLong(18, content.getValue(FxLargeNumber.class, "/CREATED_BY").getBestTranslation());
            ps.setLong(19, content.getValue(FxDateTime.class, "/CREATED_AT").getBestTranslation().getTime());
            ps.setLong(20, content.getValue(FxLargeNumber.class, "/MODIFIED_BY").getBestTranslation());
            ps.setLong(21, content.getValue(FxDateTime.class, "/MODIFIED_AT").getBestTranslation().getTime());
        }
        ps.setLong(22, content.getMandatorId());
        final String groupPositions = getGroupPositions(content);
        if (groupPositions != null) {
            StorageManager.getStorageImpl().setBigString(ps, 23, groupPositions);
        } else {
            ps.setNull(23, Types.CLOB);
        }
        ps.executeUpdate();

        updateACLEntries(con, content, pk, true);

    } catch (SQLException e) {
        throw new FxCreateException(LOG, e, "ex.db.sqlError", e.getMessage());
    } catch (FxUpdateException e) {
        throw new FxCreateException(e);
    } finally {
        Database.closeObjects(GenericHierarchicalStorage.class, ps);
    }
    return pk;
}

From source file:com.flexive.ejb.beans.structure.AssignmentEngineBean.java

/**
 * Creates a group assignment/*from  w w  w  . jav a  2 s.com*/
 *
 * @param con                  a valid and open connection
 * @param sql                  an instance of StringBuilder
 * @param group                an instance of the FxGroupAssignment to be persisted
 * @param createSubAssignments if true calls createGroupAssignment is called recursively to create sub assignments
 * @return returns the assignmentId
 * @throws FxApplicationException on errors
 */
private long createGroupAssignment(Connection con, StringBuilder sql, FxGroupAssignmentEdit group,
        boolean createSubAssignments) throws FxApplicationException {
    if (!group.isNew())
        throw new FxInvalidParameterException("ex.structure.assignment.create.existing", group.getXPath());
    if (sql == null) {
        sql = new StringBuilder(1000);
    }
    PreparedStatement ps = null;
    long newAssignmentId;
    try {
        FxGroupAssignment thisGroupAssignment;
        String XPath;
        if (!group.getXPath().startsWith(group.getAssignedType().getName())) {
            if (group.getAlias() != null)
                XPath = XPathElement.buildXPath(false, group.getAssignedType().getName(),
                        XPathElement.stripType(group.getXPath()));
            else
                XPath = "/";
        } else
            XPath = group.getXPath();
        if (group.getAlias() != null) {
            sql.setLength(0);
            sql.append("INSERT INTO ").append(TBL_STRUCT_ASSIGNMENTS).
            //               1  2     3       4       5       6       7       8   9     10     11   12          13     14          15
                    append("(ID,ATYPE,ENABLED,TYPEDEF,MINMULT,MAXMULT,DEFMULT,POS,XPATH,XALIAS,BASE,PARENTGROUP,AGROUP,SYSINTERNAL,GROUPMODE)"
                            + "VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
            ps = con.prepareStatement(sql.toString());
            newAssignmentId = seq.getId(FxSystemSequencer.ASSIGNMENT);
            ps.setLong(1, newAssignmentId);
            ps.setInt(2, FxAssignment.TYPE_GROUP);
            ps.setBoolean(3, group.isEnabled());
            ps.setLong(4, group.getAssignedType().getId());
            ps.setInt(5, group.getMultiplicity().getMin());
            ps.setInt(6, group.getMultiplicity().getMax());
            ps.setInt(7, group.getDefaultMultiplicity());
            int position = getValidPosition(con, sql, group.getPosition(), group.getAssignedType().getId(),
                    group.getParentGroupAssignment());
            ps.setInt(8, position);
            ps.setString(9, XPath);
            ps.setString(10, group.getAlias());
            if (group.getBaseAssignmentId() == FxAssignment.NO_BASE)
                ps.setNull(11, java.sql.Types.NUMERIC);
            else
                ps.setLong(11, group.getBaseAssignmentId());
            ps.setLong(12, group.getParentGroupAssignment() == null ? FxAssignment.NO_PARENT
                    : group.getParentGroupAssignment().getId());
            ps.setLong(13, group.getGroup().getId());
            ps.setBoolean(14, group.isSystemInternal());
            ps.setInt(15, group.getMode().getId());
            ps.executeUpdate();
            ps.close();
            Database.storeFxString(new FxString[] { group.getLabel(), group.getHint() }, con,
                    TBL_STRUCT_ASSIGNMENTS, new String[] { "DESCRIPTION", "HINT" }, "ID", newAssignmentId);
            thisGroupAssignment = new FxGroupAssignment(newAssignmentId, true, group.getAssignedType(),
                    group.getAlias(), XPath, position, group.getMultiplicity(), group.getDefaultMultiplicity(),
                    group.getParentGroupAssignment(), group.getBaseAssignmentId(), group.getLabel(),
                    group.getHint(), group.getGroup(), group.getMode(), null);
            setAssignmentPosition(con, newAssignmentId, group.getPosition());
        } else {
            thisGroupAssignment = null;
            newAssignmentId = FxAssignment.NO_PARENT;
        }
        htracker.track(group.getAssignedType(), "history.assignment.createGroupAssignment", XPath,
                group.getAssignedType().getId(), group.getAssignedType().getName(), group.getGroup().getId(),
                group.getGroup().getName());

        // FxStructureOption inheritance
        boolean isInheritedAssignment = FxSharedUtils.checkAssignmentInherited(group);
        if (isInheritedAssignment) {
            // FxStructureOptions - retrieve only those with an activated "isInherited" flag
            final List<FxStructureOption> inheritedOpts = FxStructureOption.cloneOptions(group.getOptions(),
                    true);
            if (inheritedOpts.size() > 0) {
                storeOptions(con, TBL_STRUCT_GROUP_OPTIONS, "ID", group.getGroup().getId(), newAssignmentId,
                        inheritedOpts);
            }
        } else {
            storeOptions(con, TBL_STRUCT_GROUP_OPTIONS, "ID", group.getGroup().getId(), newAssignmentId,
                    group.getOptions());
        }

        if (group.getBaseAssignmentId() > 0 && createSubAssignments) {
            FxGroupAssignment baseGroup = (FxGroupAssignment) CacheAdmin.getEnvironment()
                    .getAssignment(group.getBaseAssignmentId());
            for (FxGroupAssignment ga : baseGroup.getAssignedGroups()) {
                FxGroupAssignmentEdit gae = new FxGroupAssignmentEdit(ga);
                gae.setEnabled(group.isEnabled());
                createGroupAssignment(con, sql, FxGroupAssignmentEdit.createNew(gae, group.getAssignedType(),
                        ga.getAlias(), XPath, thisGroupAssignment), createSubAssignments);
            }
            for (FxPropertyAssignment pa : baseGroup.getAssignedProperties()) {
                FxPropertyAssignmentEdit pae = new FxPropertyAssignmentEdit(pa);
                pae.setEnabled(group.isEnabled());
                createPropertyAssignment(con, sql, FxPropertyAssignmentEdit.createNew(pae,
                        group.getAssignedType(), pa.getAlias(), XPath, thisGroupAssignment));
            }
        }
        try {
            StructureLoader.reloadAssignments(FxContext.get().getDivisionId());
        } catch (FxApplicationException e) {
            EJBUtils.rollback(ctx);
            throw new FxCreateException(e, "ex.cache", e.getMessage());
        }
        if (group.getAssignedType().getId() != FxType.ROOT_ID)
            createInheritedAssignments(CacheAdmin.getEnvironment().getAssignment(newAssignmentId), con, sql,
                    group.getAssignedType().getDerivedTypes());
    } catch (SQLException e) {
        final boolean uniqueConstraintViolation = StorageManager.isUniqueConstraintViolation(e);
        EJBUtils.rollback(ctx);
        if (uniqueConstraintViolation)
            throw new FxEntryExistsException("ex.structure.assignment.group.exists", group.getAlias(),
                    group.getAssignedType().getName() + group.getXPath());
        throw new FxCreateException(LOG, e, "ex.db.sqlError", e.getMessage());
    } catch (FxNotFoundException e) {
        throw new FxCreateException(e);
    } finally {
        Database.closeObjects(AssignmentEngineBean.class, null, ps);
    }
    return newAssignmentId;
}

From source file:org.LexGrid.util.sql.lgTables.SQLTableUtilities.java

/**
 * Runs SQL Statement "UPDATE" on the given tableName with attribute values
 * and where clause.//from   ww w  .  j  ava2 s  .c  o m
 * 
 * @param tableName
 * @param attributeNameValue
 * @param whereClause
 * @return
 * @throws SQLException
 */
public int updateRow(String tableName, Map attributeNameValue, String whereClause, String dbType)
        throws SQLException {

    StringBuffer stmt = new StringBuffer();
    PreparedStatement prepStmt = null;
    int rowsUpdated = 0;
    Object attribute = null;
    Iterator itr = null;
    String[] key = new String[attributeNameValue.size()];
    int count = 0;

    stmt.append("UPDATE " + tablePrefix_ + tableName.trim() + " SET ");

    itr = attributeNameValue.keySet().iterator();

    while (itr.hasNext()) {
        key[count] = (String) itr.next();
        stmt.append(key[count++] + " = ?,");
    }

    /*
     * for (int i = 0; i < attributeNames.size(); i++) {
     * stmt.append(attributeNames.get(i) + " = ?,"); }
     */

    stmt = stmt.deleteCharAt(stmt.length() - 1);

    if (whereClause != null && !"".equals(whereClause)) {
        stmt.append(" WHERE ");
        stmt.append(whereClause);
    }

    // stmt = stmt.deleteCharAt(stmt.length());

    log.debug("************ UPDATE QUERY ************");
    log.debug(stmt.toString());
    log.debug("**************************************");
    try {

        String statement = new GenericSQLModifier(dbType, false).modifySQL(stmt.toString());

        prepStmt = sqlConnection_.prepareStatement(statement);

        itr = attributeNameValue.keySet().iterator();

        for (count = 0; count < key.length; count++) {

            attribute = attributeNameValue.get(key[count]);

            if (attribute instanceof String) {
                prepStmt.setString(count + 1, (String) attribute);
            } else if (attribute instanceof Blob) {
                prepStmt.setBlob(count + 1, (Blob) attribute);
            } else if (attribute instanceof Boolean) {
                prepStmt.setBoolean(count + 1, ((Boolean) attribute).booleanValue());
            } else if (attribute instanceof Byte) {
                prepStmt.setByte(count + 1, ((Byte) attribute).byteValue());
            } else if (attribute instanceof byte[]) {
                prepStmt.setBytes(count + 1, (byte[]) attribute);
            } else if (attribute instanceof Date) {
                prepStmt.setDate(count + 1, (Date) attribute);
            } else if (attribute instanceof Double) {
                prepStmt.setDouble(count + 1, ((Double) attribute).doubleValue());
            } else if (attribute instanceof Float) {
                prepStmt.setFloat(count + 1, ((Float) attribute).floatValue());
            } else if (attribute instanceof Integer) {
                prepStmt.setInt(count + 1, ((Integer) attribute).intValue());
            } else if (attribute instanceof Long) {
                prepStmt.setLong(count + 1, ((Long) attribute).longValue());
            } else if (attribute instanceof Short) {
                prepStmt.setShort(count + 1, ((Short) attribute).shortValue());
            } else if (attribute instanceof Timestamp) {
                prepStmt.setTimestamp(count + 1, (Timestamp) attribute);
            }
        }

        rowsUpdated = prepStmt.executeUpdate();
    } catch (Exception e) {
        log.error("Exception @ updateRow: " + e.getMessage());
    } finally {
        prepStmt.close();
    }

    return rowsUpdated;

}

From source file:org.lockss.subscription.SubscriptionManager.java

/**
 * Updates the type of a subscription range.
 * //from w  w w  .  jav a 2 s. c  o  m
 * @param conn
 *          A Connection with the database connection to be used.
 * @param subscriptionSeq
 *          A Long with the identifier of the subscription.
 * @param range
 *          A BibliographicPeriod with the subscription range.
 * @param subscribed
 *          A boolean with the indication of whether the LOCKSS installation
 *          is subscribed to the publication range or not.
 * @return an int with the count of rows updated in the database.
 * @throws DbException
 *           if any problem occurred accessing the database.
 */
private int updateSubscriptionRangeType(Connection conn, Long subscriptionSeq, BibliographicPeriod range,
        boolean subscribed) throws DbException {
    final String DEBUG_HEADER = "updateSubscriptionRangeType(): ";
    if (log.isDebug2()) {
        log.debug2(DEBUG_HEADER + "subscriptionSeq = " + subscriptionSeq);
        log.debug2(DEBUG_HEADER + "range = " + range);
        log.debug2(DEBUG_HEADER + "subscribed = " + subscribed);
    }

    int count = 0;

    // Skip an empty range that does not accomplish anything.
    if (range.isEmpty()) {
        if (log.isDebug2())
            log.debug2(DEBUG_HEADER + "count = " + count);
        return count;
    }

    PreparedStatement updateSubscriptionRange = dbManager.prepareStatement(conn,
            UPDATE_SUBSCRIPTION_RANGE_TYPE_QUERY);

    try {
        updateSubscriptionRange.setBoolean(1, subscribed);
        updateSubscriptionRange.setLong(2, subscriptionSeq);
        updateSubscriptionRange.setString(3, range.toDisplayableString());

        count = dbManager.executeUpdate(updateSubscriptionRange);
        if (log.isDebug3())
            log.debug3(DEBUG_HEADER + "count = " + count);
    } catch (SQLException sqle) {
        log.error("Cannot update subscription range", sqle);
        log.error("SQL = '" + UPDATE_SUBSCRIPTION_RANGE_TYPE_QUERY + "'.");
        log.error("subscriptionSeq = " + subscriptionSeq);
        log.error("range = " + range);
        log.error("subscribed = " + subscribed);
        throw new DbException("Cannot update subscription range", sqle);
    } finally {
        DbManager.safeCloseStatement(updateSubscriptionRange);
    }

    if (log.isDebug2())
        log.debug2(DEBUG_HEADER + "count = " + count);
    return count;
}

From source file:com.enonic.vertical.engine.handlers.MenuHandler.java

private void createOrOverrideShortcut(Element shortcutDestinationMenuItem, MenuItemKey shortcutMenuItem)
        throws VerticalCreateException {
    Element shortcutElem = XMLTool.getElement(shortcutDestinationMenuItem, "shortcut");
    int shortcut = Integer.parseInt(shortcutElem.getAttribute("key"));
    boolean forward = Boolean.valueOf(shortcutElem.getAttribute("forward"));
    StringBuffer sql = XDG.generateUpdateSQL(db.tMenuItem,
            new Column[] { db.tMenuItem.mei_mei_lShortcut, db.tMenuItem.mei_bShortcutForward },
            new Column[] { db.tMenuItem.mei_lKey }, null);
    Connection con = null;//from   w ww  .java 2  s  .  c o m
    PreparedStatement prepStmt = null;
    try {
        con = getConnection();
        prepStmt = con.prepareStatement(sql.toString());
        prepStmt.setInt(1, shortcut);
        prepStmt.setBoolean(2, forward);
        prepStmt.setInt(3, shortcutMenuItem.toInt());
        prepStmt.executeUpdate();
    } catch (SQLException sqle) {
        String message = "Failed to create menu item shortcut: %t";
        VerticalEngineLogger.errorCreate(this.getClass(), 0, message, sqle);
    } finally {
        close(con);
        close(prepStmt);
    }
}

From source file:fr.aliacom.obm.common.calendar.CalendarDaoJdbcImpl.java

private PreparedStatement createEventUpdateStatement(Connection con, AccessToken at, Event ev, int sequence)
        throws SQLException {
    PreparedStatement ps;
    String upQ = "UPDATE Event SET event_userupdate=?, " + "event_type=?, event_timezone=?, event_opacity=?, "
            + "event_title=?, event_location=?, " + "event_category1_id=?, event_priority=?, "
            + "event_privacy=?, event_date=?, event_duration=?, " + "event_allday=?, event_repeatkind=?, "
            + "event_repeatfrequence=?, event_repeatdays=?, " + "event_endrepeat=?, event_completed=?, "
            + "event_url=?, event_description=?, event_origin=?, " + "event_sequence=? " + "WHERE event_id=?";

    ps = con.prepareStatement(upQ);//from w ww  .j  av  a  2  s . co m
    try {
        ps.setInt(1, at.getObmId());
        ps.setObject(2, obmHelper.getDBCP().getJdbcObject(ObmHelper.VCOMPONENT, ev.getType().toString()));
        ps.setString(3, ev.getTimezoneName() != null ? ev.getTimezoneName() : "Europe/Paris");
        ps.setObject(4, obmHelper.getDBCP().getJdbcObject(ObmHelper.VOPACITY, ev.getOpacity().toString()));
        ps.setString(5, ev.getTitle());
        ps.setString(6, ev.getLocation());
        Integer cat = catIdFromString(con, ev.getCategory(), at.getDomain().getId());
        if (cat != null) {
            ps.setInt(7, cat);
        } else {
            ps.setNull(7, Types.INTEGER);
        }
        ps.setInt(8, ev.getPriority());
        // do not allow making a private event become public from sync
        // ps.setInt(9, old.getPrivacy() != 1 ? ev.getPrivacy() : old
        // .getPrivacy());
        ps.setInt(9, ev.getPrivacy().toInteger());
        ps.setTimestamp(10, new Timestamp(ev.getStartDate().getTime()));
        ps.setInt(11, ev.getDuration());
        ps.setBoolean(12, ev.isAllday());
        EventRecurrence er = ev.getRecurrence();
        ps.setString(13, er.getKind().toString());
        ps.setInt(14, er.getFrequence());
        ps.setString(15, new RecurrenceDaysSerializer().serialize(er.getDays()));
        if (er.getEnd() != null) {
            ps.setTimestamp(16, new Timestamp(er.getEnd().getTime()));
        } else {
            ps.setNull(16, Types.TIMESTAMP);
        }
        ps.setNull(17, Types.TIMESTAMP);
        ps.setNull(18, Types.VARCHAR);
        ps.setString(19, ev.getDescription());
        ps.setString(20, at.getOrigin());
        ps.setInt(21, sequence);
        ps.setInt(22, ev.getObmId().getObmId());
        return ps;
    } catch (SQLException e) {
        ps.close();
        throw e;
    } catch (RuntimeException e) {
        ps.close();
        throw e;
    }
}

From source file:org.lockss.subscription.SubscriptionManager.java

/**
 * Provides the subscription ranges for a subscription.
 * /*  w ww . j  av a  2s .  co m*/
 * @param conn
 *          A Connection with the database connection to be used.
 * @param subscriptionSeq
 *          A Long with the identifier of the subscription.
 * @param subscribed
 *          A boolean with the subscribed attribute of the ranges to be
 *          provided.
 * @return a List<BibliographicPeriod> with the ranges for the subscription.
 * @throws DbException
 *           if any problem occurred accessing the database.
 */
List<BibliographicPeriod> findSubscriptionRanges(Connection conn, Long subscriptionSeq, boolean subscribed)
        throws DbException {
    final String DEBUG_HEADER = "findSubscriptionsRanges(): ";
    if (log.isDebug2()) {
        log.debug2(DEBUG_HEADER + "subscriptionSeq = " + subscriptionSeq);
        log.debug2(DEBUG_HEADER + "subscribed = " + subscribed);
    }

    String range;
    List<BibliographicPeriod> ranges = new ArrayList<BibliographicPeriod>();
    String query = FIND_SUBSCRIPTION_RANGES_QUERY;
    if (log.isDebug3())
        log.debug3(DEBUG_HEADER + "SQL = " + query);

    PreparedStatement getSubscriptionRanges = dbManager.prepareStatement(conn, query);
    ResultSet resultSet = null;

    try {
        getSubscriptionRanges.setLong(1, subscriptionSeq);
        getSubscriptionRanges.setBoolean(2, subscribed);
        resultSet = dbManager.executeQuery(getSubscriptionRanges);

        while (resultSet.next()) {
            range = resultSet.getString(SUBSCRIPTION_RANGE_COLUMN);
            if (log.isDebug3())
                log.debug3(DEBUG_HEADER + "range = " + range);

            ranges.add(new BibliographicPeriod(range));
        }
    } catch (SQLException sqle) {
        log.error("Cannot get ranges", sqle);
        log.error("SQL = '" + query + "'.");
        log.error("subscriptionSeq = " + subscriptionSeq);
        log.error("subscribed = " + subscribed);
        throw new DbException("Cannot get ranges", sqle);
    } finally {
        DbManager.safeCloseResultSet(resultSet);
        DbManager.safeCloseStatement(getSubscriptionRanges);
    }

    if (log.isDebug2())
        log.debug2(DEBUG_HEADER + "ranges = " + ranges);
    return ranges;
}

From source file:org.lockss.subscription.SubscriptionManager.java

/**
 * Deletes all ranges of a type belonging to a subscription from the database.
 * //from w  w  w.  j a  va 2  s. c o m
 * @param conn
 *          A Connection with the database connection to be used.
 * @param subscriptionSeq
 *          A Long with the identifier of the subscription.
 * @param subscribed
 *          A boolean with the indication of whether the LOCKSS installation
 *          is subscribed to the publication range or not.
 * @return an int with the number of deleted rows.
 * @throws DbException
 *           if any problem occurred accessing the database.
 */
int deleteSubscriptionTypeRanges(Connection conn, Long subscriptionSeq, boolean subscribed) throws DbException {
    final String DEBUG_HEADER = "deleteSubscriptionTypeRanges(): ";
    if (log.isDebug2()) {
        log.debug2(DEBUG_HEADER + "subscriptionSeq = " + subscriptionSeq);
        log.debug2(DEBUG_HEADER + "subscribed = " + subscribed);
    }

    int count = 0;
    PreparedStatement deleteSubscriptionRange = dbManager.prepareStatement(conn,
            DELETE_ALL_SUBSCRIPTION_RANGES_TYPE_QUERY);

    try {
        deleteSubscriptionRange.setLong(1, subscriptionSeq);
        deleteSubscriptionRange.setBoolean(2, subscribed);

        count = dbManager.executeUpdate(deleteSubscriptionRange);
        if (log.isDebug3())
            log.debug3(DEBUG_HEADER + "count = " + count);
    } catch (SQLException sqle) {
        log.error("Cannot delete subscription range", sqle);
        log.error("SQL = '" + DELETE_ALL_SUBSCRIPTION_RANGES_TYPE_QUERY + "'.");
        log.error("subscriptionSeq = " + subscriptionSeq);
        log.error("subscribed = " + subscribed);
        throw new DbException("Cannot delete subscription range", sqle);
    } finally {
        DbManager.safeCloseStatement(deleteSubscriptionRange);
    }

    if (log.isDebug2())
        log.debug2(DEBUG_HEADER + "count = " + count);
    return count;
}