Example usage for java.sql Types INTEGER

List of usage examples for java.sql Types INTEGER

Introduction

In this page you can find the example usage for java.sql Types INTEGER.

Prototype

int INTEGER

To view the source code for java.sql Types INTEGER.

Click Source Link

Document

The constant in the Java programming language, sometimes referred to as a type code, that identifies the generic SQL type INTEGER.

Usage

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

/**
 * {@inheritDoc}//w w w  .  j a  v  a2 s. c  o m
 */
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void updateItemData(long briefcaseId, BriefcaseItemData updateData) throws FxApplicationException {
    if (updateData == null)
        return;
    Briefcase br = load(briefcaseId); // check read permissions
    Connection con = null;
    PreparedStatement stmt = null;
    try {
        con = Database.getDbConnection();
        // check if the item actually exists
        stmt = con.prepareStatement(
                "SELECT COUNT(*) FROM " + TBL_BRIEFCASE_DATA_ITEM + " WHERE briefcase_id=? AND id=? AND pos=?");
        stmt.setLong(1, briefcaseId);
        stmt.setLong(2, updateData.getId());
        stmt.setInt(3, updateData.getPos());
        ResultSet rs = stmt.executeQuery();
        if (rs == null || !rs.next() || rs.getLong(1) != 1)
            throw new FxNotFoundException(LOG, "ex.briefcase.notFound.item", updateData.getId(), br.getName());
        stmt.close();
        stmt = con.prepareStatement("UPDATE " + TBL_BRIEFCASE_DATA_ITEM
        //               1           2           3            4            5           6                    7        8         9
                + " SET intflag1=?, intflag2=?, intflag3=?, longflag1=?, longflag2=?, metadata=? WHERE briefcase_id=? AND id=? AND pos=?");
        stmt.setLong(7, briefcaseId);
        stmt.setLong(8, updateData.getId());
        stmt.setLong(9, updateData.getPos());
        if (updateData.isIntFlagSet(1))
            stmt.setInt(1, updateData.getIntFlag1());
        else
            stmt.setNull(1, Types.INTEGER);
        if (updateData.isIntFlagSet(2))
            stmt.setInt(2, updateData.getIntFlag2());
        else
            stmt.setNull(2, Types.INTEGER);
        if (updateData.isIntFlagSet(3))
            stmt.setInt(3, updateData.getIntFlag3());
        else
            stmt.setNull(3, Types.INTEGER);
        if (updateData.isLongFlagSet(1))
            stmt.setLong(4, updateData.getLongFlag1());
        else
            stmt.setNull(4, Types.BIGINT);
        if (updateData.isLongFlagSet(2))
            stmt.setLong(5, updateData.getLongFlag2());
        else
            stmt.setNull(5, Types.BIGINT);
        stmt.setString(6, updateData.getMetaData());
        stmt.executeUpdate();
    } catch (Exception e) {
        EJBUtils.rollback(ctx);
        throw new FxUpdateException(LOG, e, "ex.briefcase.updateItemData", br.getName(), updateData.getId(),
                e.getMessage());
    } finally {
        Database.closeObjects(BriefcaseEngineBean.class, con, stmt);
    }
}

From source file:nl.ordina.bag.etl.dao.AbstractBAGDAO.java

@Override
public void insertNummeraanduidingen(final List<Nummeraanduiding> nummeraanduidingen) throws DAOException {
    try {/*from  www.  j a  v a2 s .  co m*/
        jdbcTemplate.batchUpdate("insert into bag_nummeraanduiding (" + "bag_nummeraanduiding_id,"
                + "aanduiding_record_inactief," + "aanduiding_record_correctie," + "huisnummer," + "officieel,"
                + "huisletter," + "huisnummertoevoeging," + "postcode," + "begindatum_tijdvak_geldigheid,"
                + "einddatum_tijdvak_geldigheid," + "in_onderzoek," + "type_adresseerbaar_object,"
                + "bron_documentdatum," + "bron_documentnummer," + "nummeraanduiding_status,"
                + "bag_woonplaats_id," + "bag_openbare_ruimte_id"
                + ") values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", new BatchPreparedStatementSetter() {
                    @Override
                    public void setValues(PreparedStatement ps, int i) throws SQLException {
                        ps.setLong(1, nummeraanduidingen.get(i).getIdentificatie());
                        ps.setInt(2, nummeraanduidingen.get(i).getAanduidingRecordInactief().ordinal());
                        ps.setLong(3, nummeraanduidingen.get(i).getAanduidingRecordCorrectie());
                        ps.setInt(4, nummeraanduidingen.get(i).getHuisnummer());
                        ps.setInt(5, nummeraanduidingen.get(i).getOfficieel().ordinal());
                        if (nummeraanduidingen.get(i).getHuisletter() == null)
                            ps.setNull(6, Types.VARCHAR);
                        else
                            ps.setString(6, nummeraanduidingen.get(i).getHuisletter());
                        if (nummeraanduidingen.get(i).getHuisnummertoevoeging() == null)
                            ps.setNull(7, Types.VARCHAR);
                        else
                            ps.setString(7, nummeraanduidingen.get(i).getHuisnummertoevoeging());
                        if (nummeraanduidingen.get(i).getPostcode() == null)
                            ps.setNull(8, Types.VARCHAR);
                        else
                            ps.setString(8, nummeraanduidingen.get(i).getPostcode());
                        ps.setTimestamp(9, new Timestamp(
                                nummeraanduidingen.get(i).getBegindatumTijdvakGeldigheid().getTime()));
                        if (nummeraanduidingen.get(i).getEinddatumTijdvakGeldigheid() == null)
                            ps.setNull(10, Types.TIMESTAMP);
                        else
                            ps.setTimestamp(10, new Timestamp(
                                    nummeraanduidingen.get(i).getEinddatumTijdvakGeldigheid().getTime()));
                        ps.setInt(11, nummeraanduidingen.get(i).getInOnderzoek().ordinal());
                        ps.setInt(12, nummeraanduidingen.get(i).getTypeAdresseerbaarObject().ordinal());
                        ps.setDate(13, new Date(nummeraanduidingen.get(i).getDocumentdatum().getTime()));
                        ps.setString(14, nummeraanduidingen.get(i).getDocumentnummer());
                        ps.setInt(15, nummeraanduidingen.get(i).getNummeraanduidingStatus().ordinal());
                        if (nummeraanduidingen.get(i).getGerelateerdeWoonplaats() == null)
                            ps.setNull(16, Types.INTEGER);
                        else
                            ps.setLong(16, nummeraanduidingen.get(i).getGerelateerdeWoonplaats());
                        ps.setLong(17, nummeraanduidingen.get(i).getGerelateerdeOpenbareRuimte());
                    }

                    @Override
                    public int getBatchSize() {
                        return nummeraanduidingen.size();
                    }
                });
    } catch (DataAccessException e) {
        throw new DAOException("Error inserting nummeraanduidingen", e);
    }
}

From source file:ca.sqlpower.matchmaker.address.AddressPool.java

/**
 * Inserts and updates the contents of the result table with the
 * {@link AddressResult} contents in this {@link AddressPool}.
 * AddressResults that are marked as {@link StorageState#DIRTY} are assumed
 * to be already in the database and are updated. AddressResults that are
 * marked as {@link StorageState#NEW} are assumed to be new entries that do
 * no yet exist in the database and are inserted.
 * //  w ww.j  a  v  a  2 s  .c o  m
 * It is worth noting that at the moment, new Address results won't have an
 * output street number yet (since they have not been validated yet) but a
 * {@link NullPointerException} gets thrown if we try to insert a null
 * Integer, so for the time being, I've set the 'null' steet number to be
 * -1, since I don't believe there's anyone with a negative street number,
 * but if I'm wrong, this will have to be changed.
 * 
 * @throws SQLException
 * @throws SQLObjectException
 */
public void store(Logger engineLogger, boolean useBatchExecute, boolean debug)
        throws SQLException, SQLObjectException {
    setStarted(true);
    setFinished(false);
    setCancelled(false);
    setProgress(0);

    List<AddressResult> dirtyAddresses = new ArrayList<AddressResult>();
    List<AddressResult> deleteAddresses = new ArrayList<AddressResult>();
    List<AddressResult> newAddresses = new ArrayList<AddressResult>();

    for (List<Object> key : addresses.keySet()) {
        AddressResult result = addresses.get(key);
        if (result.getStorageState() == StorageState.DELETE) {
            deleteAddresses.add(result);
        } else if (result.getStorageState() == StorageState.DIRTY) {
            dirtyAddresses.add(result);
        } else if (result.getStorageState() == StorageState.NEW) {
            newAddresses.add(result);
        }

    }

    setJobSize(deleteAddresses.size() + dirtyAddresses.size() + newAddresses.size());

    engineLogger.debug("# of Delete Address Records:" + deleteAddresses.size());
    engineLogger.debug("# of Dirty Address Records:" + dirtyAddresses.size());
    engineLogger.debug("# of New Address Records:" + newAddresses.size());

    Connection con = null;
    PreparedStatement ps = null;
    Statement stmt = null;
    StringBuilder sql = null;
    AddressResult result = null;

    try {
        con = project.createResultTableConnection();
        con.setAutoCommit(false);
        boolean useBatchUpdates = useBatchExecute && con.getMetaData().supportsBatchUpdates();
        SQLTable resultTable = project.getResultTable();
        int keySize = project.getSourceTableIndex().getChildCount();

        if (deleteAddresses.size() > 0) {
            stmt = con.createStatement();

            for (AddressResult currentResult : deleteAddresses) {
                sql = new StringBuilder("DELETE FROM ");
                appendFullyQualifiedTableName(sql, resultTable);
                sql.append(" WHERE ");

                int j = 0;
                for (Object keyValue : currentResult.getKeyValues()) {
                    if (j > 0) {
                        sql.append("AND ");
                    }
                    if (keyValue == null) {
                        sql.append(SOURCE_ADDRESS_KEY_COLUMN_BASE).append(j).append(" is null ");
                    } else if (keyValue instanceof String || keyValue instanceof Character) {
                        sql.append(SOURCE_ADDRESS_KEY_COLUMN_BASE).append(j)
                                .append("=" + SQL.quote(keyValue.toString()) + " ");
                    } else {
                        sql.append(SOURCE_ADDRESS_KEY_COLUMN_BASE).append(j).append("=" + keyValue + " ");
                    }
                    j++;
                }

                engineLogger.debug("Preparing the following address result to be deleted: " + currentResult);
                engineLogger.debug("Executing statement " + sql);

                stmt.execute(sql.toString());
                incrementProgress();
            }

            if (stmt != null)
                stmt.close();
            stmt = null;
        }

        Map<String, Integer> columnMetaData = this.getColumnMetaData(engineLogger, resultTable);
        /*  For backward compatibility, see if old column names are being used.
         *  NOTE: the database may return column names as upper case.
         */
        boolean usingNewNames = true;

        if (columnMetaData.containsKey(OLD_OUTPUT_DELIVERY_INSTALLATION_NAME)) {
            usingNewNames = false;
        }
        engineLogger.debug("Using new shorter names? " + usingNewNames);

        if (dirtyAddresses.size() > 0) {
            //First, create and UPDATE PreparedStatement to update dirty records
            sql = new StringBuilder();
            sql.append("UPDATE ");
            appendFullyQualifiedTableName(sql, resultTable);
            sql.append(" SET ");
            sql.append(INPUT_ADDRESS_LINE1).append("=?, "); // 1
            sql.append(INPUT_ADDRESS_LINE2).append("=?, "); // 2
            sql.append(INPUT_MUNICIPALITY).append("=?, "); // 3
            sql.append(INPUT_PROVINCE).append("=?, "); // 4
            sql.append(INPUT_COUNTRY).append("=?, "); // 5
            sql.append(INPUT_POSTAL_CODE).append("=?, "); // 6
            sql.append(OUTPUT_COUNTRY).append("=?, "); // 7
            if (usingNewNames) {
                sql.append(OUTPUT_DELIVERY_INSTALLATION_NAME).append("=?, "); // 8
                sql.append(OUTPUT_DELIVERY_INSTALLATION_TYPE).append("=?, "); // 9
            } else {
                sql.append(OLD_OUTPUT_DELIVERY_INSTALLATION_NAME).append("=?, "); // 8
                sql.append(OLD_OUTPUT_DELIVERY_INSTALLATION_TYPE).append("=?, "); // 9
            }
            sql.append(OUTPUT_DIRECTION_PREFIX).append("=?, "); // 10
            sql.append(OUTPUT_FAILED_PARSING_STRING).append("=?, "); // 11
            sql.append(OUTPUT_GENERAL_DELIVERY_NAME).append("=?, "); // 12
            sql.append(OUTPUT_LOCK_BOX_NUMBER).append("=?, "); // 13
            sql.append(OUTPUT_LOCK_BOX_TYPE).append("=?, "); // 14
            sql.append(OUTPUT_MUNICIPALITY).append("=?, "); // 15
            sql.append(OUTPUT_POSTAL_CODE).append("=?, "); // 16
            sql.append(OUTPUT_PROVINCE).append("=?, "); // 17
            sql.append(OUTPUT_RURAL_ROUTE_NUMBER).append("=?, "); // 18
            sql.append(OUTPUT_RURAL_ROUTE_TYPE).append("=?, "); // 19
            sql.append(OUTPUT_STREET_DIRECTION).append("=?, "); // 20
            sql.append(OUTPUT_STREET_NAME).append("=?, "); // 21
            sql.append(OUTPUT_STREET_NUMBER).append("=?, "); // 22
            sql.append(OUTPUT_STREET_NUMBER_SUFFIX).append("=?, "); // 23
            if (usingNewNames) {
                sql.append(OUTPUT_STREET_NUMBER_SUFFIX_SEPARATE).append("=?, "); // 23.5
            } else {
                sql.append(OLD_OUTPUT_STREET_NUMBER_SUFFIX_SEPARATE).append("=?, "); // 23.5
            }
            sql.append(OUTPUT_STREET_TYPE).append("=?, "); // 24
            sql.append(OUTPUT_STREET_TYPE_PREFIX).append("=?, "); // 25
            sql.append(OUTPUT_SUITE).append("=?, "); // 26
            sql.append(OUTPUT_SUITE_PREFIX).append("=?, "); // 27
            sql.append(OUTPUT_SUITE_TYPE).append("=?, "); // 28
            sql.append(OUTPUT_TYPE).append("=?, "); // 29
            sql.append(OUTPUT_UNPARSED_ADDRESS).append("=?, "); // 30
            sql.append(OUTPUT_URBAN_BEFORE_RURAL).append("=?, "); // 31
            sql.append(OUTPUT_VALID).append("=? "); // 32
            sql.append("WHERE ");

            String baseStatement = sql.toString();

            int batchCount = 0;
            for (int i = 0; i < dirtyAddresses.size(); i++) {

                sql = new StringBuilder(baseStatement);
                result = dirtyAddresses.get(i);
                int j = 0;

                // I really wish there was a better way to handle this,
                // but unfortunately in SQL, <column> = null and <column> is
                // null are not the same thing, and you usually want 'is
                // null' Why they couldn't just use '= null' is beyond me.
                // Otherwise, we could just use a single prepared statement
                // for all the records. The main reason we had to switch
                // back to using prepared statements is because different RDBMS
                // platforms handle Booleans differently (some support
                // boolean explicitly, others use an integer (1 or 0)
                for (Object keyValue : result.getKeyValues()) {
                    if (j > 0) {
                        sql.append("AND ");
                    }
                    if (keyValue == null) {
                        sql.append(SOURCE_ADDRESS_KEY_COLUMN_BASE).append(j).append(" is null "); // 18+
                    } else if (keyValue instanceof String || keyValue instanceof Character) {
                        sql.append(SOURCE_ADDRESS_KEY_COLUMN_BASE).append(j)
                                .append("=" + SQL.quote(keyValue.toString()) + " "); // 18+
                    } else {
                        sql.append(SOURCE_ADDRESS_KEY_COLUMN_BASE).append(j).append("=" + keyValue + " "); // 18+
                    }
                    j++;
                }

                ps = con.prepareStatement(sql.toString());
                Address inputAddress = result.getInputAddress();
                this.adjustInputAddress(inputAddress, columnMetaData);

                engineLogger.debug(
                        "Setting input unparsed address line 1 to " + inputAddress.getUnparsedAddressLine1());
                ps.setString(1, inputAddress.getUnparsedAddressLine1());
                engineLogger.debug(
                        "Setting input unparsed address line 2 to " + inputAddress.getUnparsedAddressLine2());
                ps.setString(2, inputAddress.getUnparsedAddressLine2());
                engineLogger.debug("Setting input municipality to " + inputAddress.getMunicipality());
                ps.setString(3, inputAddress.getMunicipality());
                engineLogger.debug("Setting input province to " + inputAddress.getProvince());
                ps.setString(4, inputAddress.getProvince());
                engineLogger.debug("Setting input country to " + inputAddress.getCountry());
                ps.setString(5, inputAddress.getCountry());
                engineLogger.debug("Setting input postal code to " + inputAddress.getPostalCode());
                ps.setString(6, inputAddress.getPostalCode());

                Address outputAddress = result.getOutputAddress();
                this.adjustOutputAddress(outputAddress, columnMetaData, usingNewNames);
                engineLogger.debug("Setting output suite to " + outputAddress.getSuite());
                ps.setString(7, outputAddress.getSuite());
                engineLogger.debug("Setting output delivery installation name to "
                        + outputAddress.getDeliveryInstallationName());
                ps.setString(8, outputAddress.getDeliveryInstallationName());
                engineLogger.debug("Setting output delivery nstallation type to "
                        + outputAddress.getDeliveryInstallationType());
                ps.setString(9, outputAddress.getDeliveryInstallationType());
                engineLogger.debug("Setting output direction prefix to " + outputAddress.isDirectionPrefix());
                ps.setBoolean(10, outputAddress.isDirectionPrefix());
                engineLogger.debug(
                        "Setting output failed parsing string to " + outputAddress.getFailedParsingString());
                ps.setString(11, outputAddress.getFailedParsingString());
                engineLogger.debug(
                        "Setting output general delivery name to " + outputAddress.getGeneralDeliveryName());
                ps.setString(12, outputAddress.getGeneralDeliveryName());
                engineLogger.debug("Setting output lock box number to " + outputAddress.getLockBoxNumber());
                ps.setString(13, outputAddress.getLockBoxNumber());
                engineLogger.debug("Setting output lock box type to " + outputAddress.getLockBoxType());
                ps.setString(14, outputAddress.getLockBoxType());
                engineLogger.debug("Setting output municipality to " + outputAddress.getMunicipality());
                ps.setString(15, outputAddress.getMunicipality());
                engineLogger.debug("Setting output postal code to " + outputAddress.getPostalCode());
                ps.setString(16, outputAddress.getPostalCode());
                engineLogger.debug("Setting output province to " + outputAddress.getProvince());
                ps.setString(17, outputAddress.getProvince());
                engineLogger
                        .debug("Setting output rural route number to " + outputAddress.getRuralRouteNumber());
                ps.setString(18, outputAddress.getRuralRouteNumber());
                engineLogger.debug("Setting output rural route type to " + outputAddress.getRuralRouteType());
                ps.setString(19, outputAddress.getRuralRouteType());
                engineLogger.debug("Setting output street direciton to " + outputAddress.getStreetDirection());
                ps.setString(20, outputAddress.getStreetDirection());
                engineLogger.debug("Setting output street to " + outputAddress.getStreet());
                ps.setString(21, outputAddress.getStreet());
                engineLogger.debug("Setting output street number to " + outputAddress.getStreetNumber());
                Integer streetNumber = outputAddress.getStreetNumber();
                if (streetNumber == null) {
                    ps.setNull(22, Types.INTEGER);
                } else {
                    ps.setInt(22, streetNumber);
                }
                engineLogger.debug(
                        "Setting output street number suffix to " + outputAddress.getStreetNumberSuffix());
                ps.setString(23, outputAddress.getStreetNumberSuffix());
                engineLogger.debug("Setting output street number suffix separate to "
                        + outputAddress.isStreetNumberSuffixSeparate());
                Boolean isStreetNumberSuffixSeparate = outputAddress.isStreetNumberSuffixSeparate();
                if (isStreetNumberSuffixSeparate == null) {
                    ps.setNull(24, Types.BOOLEAN);
                } else {
                    ps.setBoolean(24, outputAddress.isStreetNumberSuffixSeparate());
                }
                engineLogger.debug("Setting output suite to " + outputAddress.getSuite());
                ps.setString(25, outputAddress.getStreetType());
                engineLogger.debug("Setting output streetTypePrefix to " + outputAddress.isStreetTypePrefix());
                ps.setBoolean(26, outputAddress.isStreetTypePrefix());
                engineLogger.debug("Setting output suite to " + outputAddress.getSuite());
                ps.setString(27, outputAddress.getSuite());
                engineLogger.debug("Setting output suitePrefix to " + outputAddress.isSuitePrefix());
                ps.setBoolean(28, outputAddress.isSuitePrefix());
                engineLogger.debug("Setting output suiteType to " + outputAddress.getSuiteType());
                ps.setString(29, outputAddress.getSuiteType());
                engineLogger.debug("Setting output type to " + outputAddress.getType());
                RecordType type = outputAddress.getType();
                ps.setString(30, type == null ? null : type.toString());
                engineLogger.debug(
                        "Setting output unparsedAddressLine1 to " + outputAddress.getUnparsedAddressLine1());
                ps.setString(31, outputAddress.getUnparsedAddressLine1());
                engineLogger.debug("Setting output urbanBeforeRural to " + outputAddress.isUrbanBeforeRural());
                Boolean urbanBeforeRural = outputAddress.isUrbanBeforeRural();
                if (urbanBeforeRural == null) {
                    ps.setNull(32, Types.BOOLEAN);
                } else {
                    ps.setBoolean(32, outputAddress.isUrbanBeforeRural());
                }
                engineLogger.debug("Setting valid to " + result.isValid());
                ps.setBoolean(33, result.isValid());

                if (useBatchUpdates) {
                    engineLogger.debug("Adding to batch");
                    ps.addBatch();
                    batchCount++;
                    // TODO: The batchCount should be user setable
                    if (batchCount > 1000) {
                        engineLogger.debug("Executing batch");
                        ps.executeBatch();
                        batchCount = 0;
                    }
                } else {
                    engineLogger.debug("Executing statement");
                    ps.execute();
                }
                incrementProgress();
            }

            // Execute remaining batch statements
            if (batchCount > 0 && useBatchUpdates) {
                ps.executeBatch();
            }

            if (ps != null)
                ps.close();
            ps = null;
        }

        if (newAddresses.size() > 0) {
            //Next, let's meke an INSERT PreparedStatement to insert new records
            sql = new StringBuilder();
            sql.append("INSERT INTO ");
            appendFullyQualifiedTableName(sql, resultTable);
            sql.append("(");
            for (int i = 0; i < keySize; i++) {
                sql.append(SOURCE_ADDRESS_KEY_COLUMN_BASE).append(i).append(", ");
            }
            sql.append(INPUT_ADDRESS_LINE1).append(", ");
            sql.append(INPUT_ADDRESS_LINE2).append(", ");
            sql.append(INPUT_MUNICIPALITY).append(", ");
            sql.append(INPUT_PROVINCE).append(", ");
            sql.append(INPUT_COUNTRY).append(", ");
            sql.append(INPUT_POSTAL_CODE).append(", ");
            sql.append(OUTPUT_COUNTRY).append(", ");
            if (usingNewNames) {
                sql.append(OUTPUT_DELIVERY_INSTALLATION_NAME).append(", ");
                sql.append(OUTPUT_DELIVERY_INSTALLATION_TYPE).append(", ");
            } else {
                sql.append(OLD_OUTPUT_DELIVERY_INSTALLATION_NAME).append(", ");
                sql.append(OLD_OUTPUT_DELIVERY_INSTALLATION_TYPE).append(", ");
            }
            sql.append(OUTPUT_DIRECTION_PREFIX).append(", ");
            sql.append(OUTPUT_FAILED_PARSING_STRING).append(", ");
            sql.append(OUTPUT_GENERAL_DELIVERY_NAME).append(", ");
            sql.append(OUTPUT_LOCK_BOX_NUMBER).append(", ");
            sql.append(OUTPUT_LOCK_BOX_TYPE).append(", ");
            sql.append(OUTPUT_MUNICIPALITY).append(", ");
            sql.append(OUTPUT_POSTAL_CODE).append(", ");
            sql.append(OUTPUT_PROVINCE).append(", ");
            sql.append(OUTPUT_RURAL_ROUTE_NUMBER).append(", ");
            sql.append(OUTPUT_RURAL_ROUTE_TYPE).append(", ");
            sql.append(OUTPUT_STREET_DIRECTION).append(", ");
            sql.append(OUTPUT_STREET_NAME).append(", ");
            sql.append(OUTPUT_STREET_NUMBER).append(", ");
            sql.append(OUTPUT_STREET_NUMBER_SUFFIX).append(", ");
            if (usingNewNames) {
                sql.append(OUTPUT_STREET_NUMBER_SUFFIX_SEPARATE).append(", ");
            } else {
                sql.append(OLD_OUTPUT_STREET_NUMBER_SUFFIX_SEPARATE).append(", ");
            }
            sql.append(OUTPUT_STREET_TYPE).append(", ");
            sql.append(OUTPUT_STREET_TYPE_PREFIX).append(", ");
            sql.append(OUTPUT_SUITE).append(", ");
            sql.append(OUTPUT_SUITE_PREFIX).append(", ");
            sql.append(OUTPUT_SUITE_TYPE).append(", ");
            sql.append(OUTPUT_TYPE).append(", ");
            sql.append(OUTPUT_UNPARSED_ADDRESS).append(", ");
            sql.append(OUTPUT_URBAN_BEFORE_RURAL).append(", ");
            sql.append(OUTPUT_VALID).append(")");
            sql.append("VALUES(");
            for (int i = 0; i < keySize; i++) {
                sql.append("?, ");
            }
            sql.append(
                    "?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
            ps = con.prepareStatement(sql.toString());
            int batchCount = 0;
            for (int i = 0; i < newAddresses.size(); i++) {
                result = newAddresses.get(i);
                int j = 1;

                for (Object keyValue : result.getKeyValues()) {
                    ps.setObject(j, keyValue);
                    j++;
                    engineLogger.debug("Setting key value " + j + " to " + keyValue);
                }

                Address inputAddress = result.getInputAddress();
                this.adjustInputAddress(inputAddress, columnMetaData);

                engineLogger.debug(
                        "Setting input unparsed address line 1 to " + inputAddress.getUnparsedAddressLine1());
                ps.setString(j, inputAddress.getUnparsedAddressLine1());
                engineLogger.debug(
                        "Setting input unparsed address line 2 to " + inputAddress.getUnparsedAddressLine2());
                ps.setString(j + 1, inputAddress.getUnparsedAddressLine2());
                engineLogger.debug("Setting input municipality to " + inputAddress.getMunicipality());
                ps.setString(j + 2, inputAddress.getMunicipality());
                engineLogger.debug("Setting input province to " + inputAddress.getProvince());
                ps.setString(j + 3, inputAddress.getProvince());
                engineLogger.debug("Setting input country to " + inputAddress.getCountry());
                ps.setString(j + 4, inputAddress.getCountry());
                engineLogger.debug("Setting input postal code to " + inputAddress.getPostalCode());
                ps.setString(j + 5, inputAddress.getPostalCode());

                Address outputAddress = result.getOutputAddress();
                this.adjustOutputAddress(outputAddress, columnMetaData, usingNewNames);

                engineLogger.debug("Setting output suite to " + outputAddress.getSuite());
                ps.setString(j + 6, outputAddress.getSuite());
                engineLogger.debug("Setting output delivery installation name to "
                        + outputAddress.getDeliveryInstallationName());
                ps.setString(j + 7, outputAddress.getDeliveryInstallationName());
                engineLogger.debug("Setting output delivery nstallation type to "
                        + outputAddress.getDeliveryInstallationType());
                ps.setString(j + 8, outputAddress.getDeliveryInstallationType());
                engineLogger.debug("Setting output direction prefix to " + outputAddress.isDirectionPrefix());
                ps.setBoolean(j + 9, outputAddress.isDirectionPrefix());
                engineLogger.debug(
                        "Setting output failed parsing string to " + outputAddress.getFailedParsingString());
                ps.setString(j + 10, outputAddress.getFailedParsingString());
                engineLogger.debug(
                        "Setting output general delivery name to " + outputAddress.getGeneralDeliveryName());
                ps.setString(j + 11, outputAddress.getGeneralDeliveryName());
                engineLogger.debug("Setting output lock box number to " + outputAddress.getLockBoxNumber());
                ps.setString(j + 12, outputAddress.getLockBoxNumber());
                engineLogger.debug("Setting output lock box type to " + outputAddress.getLockBoxType());
                ps.setString(j + 13, outputAddress.getLockBoxType());
                engineLogger.debug("Setting output municipality to " + outputAddress.getMunicipality());
                ps.setString(j + 14, outputAddress.getMunicipality());
                engineLogger.debug("Setting output postal code to " + outputAddress.getPostalCode());
                ps.setString(j + 15, outputAddress.getPostalCode());
                engineLogger.debug("Setting output province to " + outputAddress.getProvince());
                ps.setString(j + 16, outputAddress.getProvince());
                engineLogger
                        .debug("Setting output rural route number to " + outputAddress.getRuralRouteNumber());
                ps.setString(j + 17, outputAddress.getRuralRouteNumber());
                engineLogger.debug("Setting output rural route type to " + outputAddress.getRuralRouteType());
                ps.setString(j + 18, outputAddress.getRuralRouteType());
                engineLogger.debug("Setting output street direciton to " + outputAddress.getStreetDirection());
                ps.setString(j + 19, outputAddress.getStreetDirection());
                engineLogger.debug("Setting output street to " + outputAddress.getStreet());
                ps.setString(j + 20, outputAddress.getStreet());
                engineLogger.debug("Setting output street number to " + outputAddress.getStreetNumber());
                Integer streetNumber = outputAddress.getStreetNumber();
                if (streetNumber == null) {
                    ps.setNull(j + 21, Types.INTEGER);
                } else {
                    ps.setInt(j + 21, streetNumber);
                }
                engineLogger.debug(
                        "Setting output street number suffix to " + outputAddress.getStreetNumberSuffix());
                ps.setString(j + 22, outputAddress.getStreetNumberSuffix());
                engineLogger.debug("Setting output street number suffix separate to "
                        + outputAddress.isStreetNumberSuffixSeparate());
                Boolean isStreetNumberSuffixSeparate = outputAddress.isStreetNumberSuffixSeparate();
                if (isStreetNumberSuffixSeparate == null) {
                    ps.setNull(j + 23, Types.BOOLEAN);
                } else {
                    ps.setBoolean(j + 23, outputAddress.isStreetNumberSuffixSeparate());
                }
                engineLogger.debug("Setting output suite to " + outputAddress.getSuite());
                ps.setString(j + 24, outputAddress.getStreetType());
                engineLogger.debug("Setting output streetTypePrefix to " + outputAddress.isStreetTypePrefix());
                ps.setBoolean(j + 25, outputAddress.isStreetTypePrefix());
                engineLogger.debug("Setting output suite to " + outputAddress.getSuite());
                ps.setString(j + 26, outputAddress.getSuite());
                engineLogger.debug("Setting output suitePrefix to " + outputAddress.isSuitePrefix());
                ps.setBoolean(j + 27, outputAddress.isSuitePrefix());
                engineLogger.debug("Setting output suiteType to " + outputAddress.getSuiteType());
                ps.setString(j + 28, outputAddress.getSuiteType());
                engineLogger.debug("Setting output type to " + outputAddress.getType());
                RecordType type = outputAddress.getType();
                ps.setString(j + 29, type == null ? null : type.toString());
                engineLogger.debug(
                        "Setting output unparsedAddressLine1 to " + outputAddress.getUnparsedAddressLine1());
                ps.setString(j + 30, outputAddress.getUnparsedAddressLine1());
                engineLogger.debug("Setting output urbanBeforeRural to " + outputAddress.isUrbanBeforeRural());
                Boolean urbanBeforeRural = outputAddress.isUrbanBeforeRural();
                if (urbanBeforeRural == null) {
                    ps.setNull(j + 31, Types.BOOLEAN);
                } else {
                    ps.setBoolean(j + 31, outputAddress.isUrbanBeforeRural());
                }
                engineLogger.debug("Setting valid to " + result.isValid());
                ps.setBoolean(j + 32, result.isValid());

                engineLogger.debug("Preparing the following address to be inserted: " + result);

                if (useBatchUpdates) {
                    engineLogger.debug("Adding to batch");
                    ps.addBatch();
                    batchCount++;
                    // TODO: The batchCount should be user setable
                    if (batchCount > 1000) {
                        engineLogger.debug("Executing batch");
                        ps.executeBatch();
                        batchCount = 0;
                    }
                } else {
                    engineLogger.debug("Executing statement");
                    ps.execute();
                }
                incrementProgress();
            }

            // Execute remaining batch statements
            if (batchCount > 0 && useBatchUpdates) {
                ps.executeBatch();
            }

            if (ps != null)
                ps.close();
            ps = null;
        }

        if (debug) {
            engineLogger.debug("Rolling back changes");
            con.rollback();
        } else {
            engineLogger.debug("Committing changes");
            con.commit();
        }

        for (AddressResult ar : addresses.values()) {
            ar.markClean();
        }
    } catch (Exception ex) {
        try {
            con.rollback();
        } catch (SQLException sqlEx) {
            engineLogger.error("Error while rolling back. "
                    + "Suppressing this exception to prevent it from overshadowing the orginal exception.",
                    sqlEx);
        }
        throw new RuntimeException("Unexpected exception while storing address validation results.\n"
                + "SQL statement: " + ((sql == null) ? "null" : sql.toString()) + "\n" + "Current result: "
                + ((result == null) ? "null"
                        : "Input Address:\n" + result.getInputAddress() + "\n" + "Output Address:\n"
                                + result.getOutputAddress()),
                ex);
    } finally {
        setFinished(true);
        if (ps != null)
            try {
                ps.close();
            } catch (SQLException e) {
                engineLogger.error("Error while closing PreparedStatement", e);
            }
        if (stmt != null)
            try {
                stmt.close();
            } catch (SQLException e) {
                engineLogger.error("Error while closing Statement", e);
            }
        if (con != null)
            try {
                con.close();
            } catch (SQLException e) {
                engineLogger.error("Error while closing Connection", e);
            }
    }
}

From source file:net.sourceforge.msscodefactory.cfcore.v2_0.CFGenKbOracle.CFGenKbOracleGelExpansionTable.java

public CFGenKbGelExpansionBuff[] readBuffByCallerIdx(CFGenKbAuthorization Authorization, long TenantId,
        long CartridgeId, Integer CallerId) {
    final String S_ProcName = "readBuffByCallerIdx";
    ResultSet resultSet = null;//  w w w .j a v a2 s .c o m
    Connection cnx = schema.getCnx();
    CallableStatement stmtReadBuffByCallerIdx = null;
    List<CFGenKbGelExpansionBuff> buffList = new LinkedList<CFGenKbGelExpansionBuff>();
    try {
        stmtReadBuffByCallerIdx = cnx.prepareCall(
                "begin " + schema.getLowerSchemaDbName() + ".rd_gelexpansionbycalleridx( ?, ?, ?, ?, ?, ?"
                        + ", " + "?" + ", " + "?" + ", " + "?" + " ); end;");
        int argIdx = 1;
        stmtReadBuffByCallerIdx.registerOutParameter(argIdx++, OracleTypes.CURSOR);
        stmtReadBuffByCallerIdx.setLong(argIdx++,
                (Authorization == null) ? 0 : Authorization.getSecClusterId());
        stmtReadBuffByCallerIdx.setString(argIdx++,
                (Authorization == null) ? "" : Authorization.getSecUserId().toString());
        stmtReadBuffByCallerIdx.setString(argIdx++,
                (Authorization == null) ? "" : Authorization.getSecSessionId().toString());
        stmtReadBuffByCallerIdx.setLong(argIdx++,
                (Authorization == null) ? 0 : Authorization.getSecClusterId());
        stmtReadBuffByCallerIdx.setLong(argIdx++, (Authorization == null) ? 0 : Authorization.getSecTenantId());
        stmtReadBuffByCallerIdx.setLong(argIdx++, TenantId);
        stmtReadBuffByCallerIdx.setLong(argIdx++, CartridgeId);
        if (CallerId != null) {
            stmtReadBuffByCallerIdx.setInt(argIdx++, CallerId.intValue());
        } else {
            stmtReadBuffByCallerIdx.setNull(argIdx++, java.sql.Types.INTEGER);
        }
        stmtReadBuffByCallerIdx.execute();
        resultSet = (ResultSet) stmtReadBuffByCallerIdx.getObject(1);
        if (resultSet != null) {
            try {
                while (resultSet.next()) {
                    CFGenKbGelExpansionBuff buff = unpackGelExpansionResultSetToBuff(resultSet);
                    buffList.add(buff);
                }
                try {
                    resultSet.close();
                } catch (SQLException e) {
                }
                resultSet = null;
            } catch (SQLException e) {
            }
        }
        int idx = 0;
        CFGenKbGelExpansionBuff[] retBuff = new CFGenKbGelExpansionBuff[buffList.size()];
        Iterator<CFGenKbGelExpansionBuff> iter = buffList.iterator();
        while (iter.hasNext()) {
            retBuff[idx++] = iter.next();
        }
        return (retBuff);
    } catch (SQLException e) {
        throw CFLib.getDefaultExceptionFactory().newDbException(getClass(), S_ProcName, e);
    } finally {
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
            }
            resultSet = null;
        }
        if (stmtReadBuffByCallerIdx != null) {
            try {
                stmtReadBuffByCallerIdx.close();
            } catch (SQLException e) {
            }
            stmtReadBuffByCallerIdx = null;
        }
    }
}

From source file:net.sourceforge.msscodefactory.cfcrm.v2_1.CFCrmMySql.CFCrmMySqlAttachmentTable.java

public void updateAttachment(CFCrmAuthorization Authorization, CFCrmAttachmentBuff Buff) {
    final String S_ProcName = "updateAttachment";
    ResultSet resultSet = null;/*from  w  w w . j a v a  2  s.  com*/
    try {
        long TenantId = Buff.getRequiredTenantId();
        long AttachmentId = Buff.getRequiredAttachmentId();
        long ContactId = Buff.getRequiredContactId();
        String Description = Buff.getRequiredDescription();
        Integer MimeTypeId = Buff.getOptionalMimeTypeId();
        String Attachment = Buff.getRequiredAttachment();
        int Revision = Buff.getRequiredRevision();
        Connection cnx = schema.getCnx();
        String sql = "call " + schema.getLowerDbSchemaName() + ".sp_update_attchmnt( ?, ?, ?, ?, ?, ?" + ", "
                + "?" + ", " + "?" + ", " + "?" + ", " + "?" + ", " + "?" + ", " + "?" + ", " + "?" + " )";
        if (stmtUpdateByPKey == null) {
            stmtUpdateByPKey = cnx.prepareStatement(sql);
        }
        int argIdx = 1;
        stmtUpdateByPKey.setLong(argIdx++, (Authorization == null) ? 0 : Authorization.getSecClusterId());
        stmtUpdateByPKey.setString(argIdx++,
                (Authorization == null) ? "" : Authorization.getSecUserId().toString());
        stmtUpdateByPKey.setString(argIdx++,
                (Authorization == null) ? "" : Authorization.getSecSessionId().toString());
        stmtUpdateByPKey.setLong(argIdx++, (Authorization == null) ? 0 : Authorization.getSecClusterId());
        stmtUpdateByPKey.setLong(argIdx++, (Authorization == null) ? 0 : Authorization.getSecTenantId());
        stmtUpdateByPKey.setString(argIdx++, "ATTC");
        stmtUpdateByPKey.setLong(argIdx++, TenantId);
        stmtUpdateByPKey.setLong(argIdx++, AttachmentId);
        stmtUpdateByPKey.setLong(argIdx++, ContactId);
        stmtUpdateByPKey.setString(argIdx++, Description);
        if (MimeTypeId != null) {
            stmtUpdateByPKey.setInt(argIdx++, MimeTypeId.intValue());
        } else {
            stmtUpdateByPKey.setNull(argIdx++, java.sql.Types.INTEGER);
        }
        stmtUpdateByPKey.setString(argIdx++, Attachment);
        stmtUpdateByPKey.setInt(argIdx++, Revision);
        try {
            resultSet = stmtUpdateByPKey.executeQuery();
        } catch (SQLException e) {
            if (e.getErrorCode() != 1329) {
                throw e;
            }
            resultSet = null;
        }
        if ((resultSet != null) && resultSet.next()) {
            CFCrmAttachmentBuff updatedBuff = unpackAttachmentResultSetToBuff(resultSet);
            if ((resultSet != null) && resultSet.next()) {
                resultSet.last();
                throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(), S_ProcName,
                        "Did not expect multi-record response, " + resultSet.getRow() + " rows selected");
            }
            Buff.setRequiredContactId(updatedBuff.getRequiredContactId());
            Buff.setRequiredDescription(updatedBuff.getRequiredDescription());
            Buff.setOptionalMimeTypeId(updatedBuff.getOptionalMimeTypeId());
            Buff.setRequiredAttachment(updatedBuff.getRequiredAttachment());
            Buff.setRequiredRevision(updatedBuff.getRequiredRevision());
        } else {
            throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(), S_ProcName,
                    "Expected a single-record response, " + resultSet.getRow() + " rows selected");
        }
    } catch (SQLException e) {
        throw CFLib.getDefaultExceptionFactory().newDbException(getClass(), S_ProcName, e);
    } finally {
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
            }
            resultSet = null;
        }
    }
}

From source file:net.sourceforge.msscodefactory.cfcrm.v2_1.CFCrmMSSql.CFCrmMSSqlAttachmentTable.java

public void updateAttachment(CFCrmAuthorization Authorization, CFCrmAttachmentBuff Buff) {
    final String S_ProcName = "updateAttachment";
    if ("ATTC".equals(Buff.getClassCode())
            && (!schema.isTenantUser(Authorization, Buff.getRequiredTenantId(), "UpdateAttachment"))) {
        throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(), S_ProcName,
                "Permission denied -- User not part of TSecGroup UpdateAttachment");
    }/*from www  .  j a v  a 2 s .  c o  m*/
    try {
        Connection cnx = schema.getCnx();
        long TenantId = Buff.getRequiredTenantId();
        long AttachmentId = Buff.getRequiredAttachmentId();
        long ContactId = Buff.getRequiredContactId();
        String Description = Buff.getRequiredDescription();
        Integer MimeTypeId = Buff.getOptionalMimeTypeId();
        String Attachment = Buff.getRequiredAttachment();
        int Revision = Buff.getRequiredRevision();
        CFCrmAttachmentPKey pkey = schema.getFactoryAttachment().newPKey();
        pkey.setRequiredTenantId(Buff.getRequiredTenantId());
        pkey.setRequiredAttachmentId(Buff.getRequiredAttachmentId());
        CFCrmAttachmentBuff readBuff = lockBuff(Authorization, pkey);
        if (readBuff == null) {
            throw CFLib.getDefaultExceptionFactory().newStaleCacheDetectedException(getClass(), S_ProcName,
                    "Attempted to update record which could not be locked/found",
                    schema.getLowerDbSchemaName() + "..attchmnt", pkey);
        }
        int oldRevision = readBuff.getRequiredRevision();
        if (oldRevision != Revision) {
            throw CFLib.getDefaultExceptionFactory().newCollisionDetectedException(getClass(), S_ProcName,
                    Buff);
        }
        int newRevision = Revision + 1;
        String sql = "UPDATE " + schema.getLowerDbSchemaName() + "..Attchmnt " + "SET " + "tenantid = ?" + ", "
                + "attachmentid = ?" + ", " + "contactid = ?" + ", " + "description = ?" + ", "
                + "mimetypeid = ?" + ", " + "attachment = ?" + ", " + "updatedby = ?, "
                + "updatedat = sysdatetime() " + ", revision = ? " + " WHERE " + "tenantid = ? " + "AND "
                + "attachmentid = ? " + "AND " + "revision = ? ";
        if (stmtUpdateByPKey == null) {
            stmtUpdateByPKey = cnx.prepareStatement(sql);
        }
        int argIdx = 1;

        stmtUpdateByPKey.setLong(argIdx++, TenantId);
        stmtUpdateByPKey.setLong(argIdx++, AttachmentId);
        stmtUpdateByPKey.setLong(argIdx++, ContactId);
        stmtUpdateByPKey.setString(argIdx++, Description);
        if (MimeTypeId != null) {
            stmtUpdateByPKey.setInt(argIdx++, MimeTypeId.intValue());
        } else {
            stmtUpdateByPKey.setNull(argIdx++, java.sql.Types.INTEGER);
        }
        stmtUpdateByPKey.setString(argIdx++, Attachment);
        stmtUpdateByPKey.setString(argIdx++, Authorization.getSecUserId().toString());
        stmtUpdateByPKey.setInt(argIdx++, newRevision);
        stmtUpdateByPKey.setLong(argIdx++, TenantId);
        stmtUpdateByPKey.setLong(argIdx++, AttachmentId);
        stmtUpdateByPKey.setInt(argIdx++, Revision);
        ;
        int rowsAffected = stmtUpdateByPKey.executeUpdate();
        if (rowsAffected != 1) {
            throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(), S_ProcName,
                    "Expected 1 row to be affected by update, not " + rowsAffected);
        }
        Buff.setRequiredRevision(newRevision);
        String sqlAuditUpdated = "INSERT INTO " + schema.getLowerDbSchemaName()
                + "..Attchmnt_h( auditclusterid, " + " auditsessionid, " + " auditstamp" + ", " + "tenantid"
                + ", " + "attachmentid" + ", " + "contactid" + ", " + "description" + ", " + "mimetypeid" + ", "
                + "attachment" + ", " + " revision, " + " auditaction ) " + "SELECT ?, ?, sysdatetime()" + ", "
                + "attc.tenantid" + ", " + "attc.attachmentid" + ", " + "attc.contactid" + ", "
                + "attc.description" + ", " + "attc.mimetypeid" + ", " + "attc.attachment" + ", "
                + " attc.revision, " + " 2 " + "FROM " + schema.getLowerDbSchemaName() + "..Attchmnt AS attc "
                + " WHERE " + "attc.tenantid = ? " + "AND attc.attachmentid = ? ";
        if (stmtAuditUpdatedByPKey == null) {
            stmtAuditUpdatedByPKey = cnx.prepareStatement(sqlAuditUpdated);
        }
        argIdx = 1;
        stmtAuditUpdatedByPKey.setLong(argIdx++, Authorization.getSecClusterId());
        stmtAuditUpdatedByPKey.setString(argIdx++, Authorization.getSecSessionId().toString());
        stmtAuditUpdatedByPKey.setLong(argIdx++, TenantId);
        stmtAuditUpdatedByPKey.setLong(argIdx++, AttachmentId);
        int rowsAudited = stmtAuditUpdatedByPKey.executeUpdate();
        if (rowsAudited != 1) {
            throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(), S_ProcName,
                    "Expected 1 row to be affected by audit via insert-selected, not " + rowsAffected);
        }
    } catch (SQLException e) {
        throw CFLib.getDefaultExceptionFactory().newDbException(getClass(), S_ProcName, e);
    }
}

From source file:net.sourceforge.msscodefactory.cfcore.v2_0.CFGenKbMySql.CFGenKbMySqlGelPopTable.java

public CFGenKbGelPopBuff[] readBuffByPrevIdx(CFGenKbAuthorization Authorization, long TenantId,
        long CartridgeId, Integer PrevId) {
    final String S_ProcName = "readBuffByPrevIdx";
    ResultSet resultSet = null;/*  w  w w  . j a  v a 2 s . c o  m*/
    try {
        Connection cnx = schema.getCnx();
        String sql = "call " + schema.getLowerSchemaDbName() + ".sp_read_gelpop_by_previdx( ?, ?, ?, ?, ?"
                + ", " + "?" + ", " + "?" + ", " + "?" + " )";
        if (stmtReadBuffByPrevIdx == null) {
            stmtReadBuffByPrevIdx = cnx.prepareStatement(sql);
        }
        int argIdx = 1;
        stmtReadBuffByPrevIdx.setLong(argIdx++, (Authorization == null) ? 0 : Authorization.getSecClusterId());
        stmtReadBuffByPrevIdx.setString(argIdx++,
                (Authorization == null) ? "" : Authorization.getSecUserId().toString());
        stmtReadBuffByPrevIdx.setString(argIdx++,
                (Authorization == null) ? "" : Authorization.getSecSessionId().toString());
        stmtReadBuffByPrevIdx.setLong(argIdx++, (Authorization == null) ? 0 : Authorization.getSecClusterId());
        stmtReadBuffByPrevIdx.setLong(argIdx++, (Authorization == null) ? 0 : Authorization.getSecTenantId());
        stmtReadBuffByPrevIdx.setLong(argIdx++, TenantId);
        stmtReadBuffByPrevIdx.setLong(argIdx++, CartridgeId);
        if (PrevId != null) {
            stmtReadBuffByPrevIdx.setInt(argIdx++, PrevId.intValue());
        } else {
            stmtReadBuffByPrevIdx.setNull(argIdx++, java.sql.Types.INTEGER);
        }
        try {
            resultSet = stmtReadBuffByPrevIdx.executeQuery();
        } catch (SQLException e) {
            if (e.getErrorCode() != 1329) {
                throw e;
            }
            resultSet = null;
        }
        List<CFGenKbGelPopBuff> buffList = new LinkedList<CFGenKbGelPopBuff>();
        while ((resultSet != null) && resultSet.next()) {
            CFGenKbGelPopBuff buff = unpackGelPopResultSetToBuff(resultSet);
            buffList.add(buff);
        }
        int idx = 0;
        CFGenKbGelPopBuff[] retBuff = new CFGenKbGelPopBuff[buffList.size()];
        Iterator<CFGenKbGelPopBuff> iter = buffList.iterator();
        while (iter.hasNext()) {
            retBuff[idx++] = iter.next();
        }
        return (retBuff);
    } catch (SQLException e) {
        throw CFLib.getDefaultExceptionFactory().newDbException(getClass(), S_ProcName, e);
    } finally {
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
            }
            resultSet = null;
        }
    }
}

From source file:fr.aliacom.obm.common.contact.ContactDaoJdbcImpl.java

@Override
@AutoTruncate/* w  ww .  j  a  v  a 2 s  . c o  m*/
public Contact modifyContact(AccessToken token, @DatabaseEntity Contact c)
        throws SQLException, FindException, EventNotFoundException, ServerFault {

    String q = "update Contact SET " + "contact_commonname=?, contact_firstname=?, "
            + "contact_lastname=?, contact_origin=?, contact_userupdate=?, "
            + "contact_aka=?, contact_title=?, contact_service=?, contact_company=?, contact_comment=?, "
            + "contact_suffix=?, contact_manager=?, contact_middlename=?, contact_assistant=?, contact_spouse=?, contact_anniversary_id=?, contact_birthday_id=? "
            + "WHERE contact_id=? ";
    logger.info("modify contact with id=" + c.getUid() + " entityId=" + c.getEntityId());

    Connection con = null;
    PreparedStatement ps = null;
    try {
        con = obmHelper.getConnection();

        EventObmId anniversaryId = createOrUpdateDate(token, con, c, c.getAnniversary(), ANNIVERSARY_FIELD);
        c.setAnniversaryId(anniversaryId);

        EventObmId birthdayId = createOrUpdateDate(token, con, c, c.getBirthday(), BIRTHDAY_FIELD);
        c.setBirthdayId(birthdayId);

        ps = con.prepareStatement(q);

        int idx = 1;
        ps.setString(idx++, c.getCommonname());
        ps.setString(idx++, c.getFirstname());
        ps.setString(idx++, c.getLastname());
        ps.setString(idx++, token.getOrigin());
        ps.setInt(idx++, token.getObmId());

        ps.setString(idx++, c.getAka());
        ps.setString(idx++, c.getTitle());
        ps.setString(idx++, c.getService());
        ps.setString(idx++, c.getCompany());
        ps.setString(idx++, c.getComment());

        ps.setString(idx++, c.getSuffix());
        ps.setString(idx++, c.getManager());
        ps.setString(idx++, c.getMiddlename());
        ps.setString(idx++, c.getAssistant());
        ps.setString(idx++, c.getSpouse());
        if (c.getAnniversaryId() == null) {
            ps.setNull(idx++, Types.INTEGER);
        } else {
            ps.setInt(idx++, c.getAnniversaryId().getObmId());
        }
        if (c.getBirthdayId() == null) {
            ps.setNull(idx++, Types.INTEGER);
        } else {
            ps.setInt(idx++, c.getBirthdayId().getObmId());
        }

        ps.setInt(idx++, c.getUid());
        ps.executeUpdate();

        createOrUpdateAddresses(con, c.getEntityId(), c.getAddresses());
        createOrUpdateEmails(con, c.getEntityId(), c.getEmails());
        createOrUpdatePhones(con, c.getEntityId(), c.getPhones());
        createOrUpdateWebsites(con, c);
        createOrUpdateIMIdentifiers(con, c.getEntityId(), c.getImIdentifiers());
    } finally {
        obmHelper.cleanup(con, ps, null);
    }

    indexContact(token, c);

    return c;
}

From source file:net.sourceforge.msscodefactory.cfacc.v2_0.CFAccMySql.CFAccMySqlAttachmentTable.java

public void updateAttachment(CFAccAuthorization Authorization, CFAccAttachmentBuff Buff) {
    final String S_ProcName = "updateAttachment";
    ResultSet resultSet = null;/*from  ww w  . j  a  va2  s .  c  o  m*/
    try {
        long TenantId = Buff.getRequiredTenantId();
        long AttachmentId = Buff.getRequiredAttachmentId();
        long ContactId = Buff.getRequiredContactId();
        String Description = Buff.getRequiredDescription();
        Integer MimeTypeId = Buff.getOptionalMimeTypeId();
        String Attachment = Buff.getRequiredAttachment();
        int Revision = Buff.getRequiredRevision();
        Connection cnx = schema.getCnx();
        String sql = "call " + schema.getLowerSchemaDbName() + ".sp_update_attchmnt( ?, ?, ?, ?, ?, ?" + ", "
                + "?" + ", " + "?" + ", " + "?" + ", " + "?" + ", " + "?" + ", " + "?" + ", " + "?" + " )";
        if (stmtUpdateByPKey == null) {
            stmtUpdateByPKey = cnx.prepareStatement(sql);
        }
        int argIdx = 1;
        stmtUpdateByPKey.setLong(argIdx++, (Authorization == null) ? 0 : Authorization.getSecClusterId());
        stmtUpdateByPKey.setString(argIdx++,
                (Authorization == null) ? "" : Authorization.getSecUserId().toString());
        stmtUpdateByPKey.setString(argIdx++,
                (Authorization == null) ? "" : Authorization.getSecSessionId().toString());
        stmtUpdateByPKey.setLong(argIdx++, (Authorization == null) ? 0 : Authorization.getSecClusterId());
        stmtUpdateByPKey.setLong(argIdx++, (Authorization == null) ? 0 : Authorization.getSecTenantId());
        stmtUpdateByPKey.setString(argIdx++, "ATTC");
        stmtUpdateByPKey.setLong(argIdx++, TenantId);
        stmtUpdateByPKey.setLong(argIdx++, AttachmentId);
        stmtUpdateByPKey.setLong(argIdx++, ContactId);
        stmtUpdateByPKey.setString(argIdx++, Description);
        if (MimeTypeId != null) {
            stmtUpdateByPKey.setInt(argIdx++, MimeTypeId.intValue());
        } else {
            stmtUpdateByPKey.setNull(argIdx++, java.sql.Types.INTEGER);
        }
        stmtUpdateByPKey.setString(argIdx++, Attachment);
        stmtUpdateByPKey.setInt(argIdx++, Revision);
        try {
            resultSet = stmtUpdateByPKey.executeQuery();
        } catch (SQLException e) {
            if (e.getErrorCode() != 1329) {
                throw e;
            }
            resultSet = null;
        }
        if ((resultSet != null) && resultSet.next()) {
            CFAccAttachmentBuff updatedBuff = unpackAttachmentResultSetToBuff(resultSet);
            if ((resultSet != null) && resultSet.next()) {
                resultSet.last();
                throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(), S_ProcName,
                        "Did not expect multi-record response, " + resultSet.getRow() + " rows selected");
            }
            Buff.setRequiredContactId(updatedBuff.getRequiredContactId());
            Buff.setRequiredDescription(updatedBuff.getRequiredDescription());
            Buff.setOptionalMimeTypeId(updatedBuff.getOptionalMimeTypeId());
            Buff.setRequiredAttachment(updatedBuff.getRequiredAttachment());
            Buff.setRequiredRevision(updatedBuff.getRequiredRevision());
        } else {
            throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(), S_ProcName,
                    "Expected a single-record response, " + resultSet.getRow() + " rows selected");
        }
    } catch (SQLException e) {
        throw CFLib.getDefaultExceptionFactory().newDbException(getClass(), S_ProcName, e);
    } finally {
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
            }
            resultSet = null;
        }
    }
}

From source file:net.sourceforge.msscodefactory.cfacc.v2_0.CFAccOracle.CFAccOracleAttachmentTable.java

public CFAccAttachmentBuff[] readBuffByMimeTypeIdx(CFAccAuthorization Authorization, Integer MimeTypeId) {
    final String S_ProcName = "readBuffByMimeTypeIdx";
    ResultSet resultSet = null;/*from  w ww. j a  va2  s.  co  m*/
    Connection cnx = schema.getCnx();
    CallableStatement stmtReadBuffByMimeTypeIdx = null;
    List<CFAccAttachmentBuff> buffList = new LinkedList<CFAccAttachmentBuff>();
    try {
        stmtReadBuffByMimeTypeIdx = cnx.prepareCall("begin " + schema.getLowerSchemaDbName()
                + ".rd_attchmntbymimetypeidx( ?, ?, ?, ?, ?, ?" + ", " + "?" + " ); end;");
        int argIdx = 1;
        stmtReadBuffByMimeTypeIdx.registerOutParameter(argIdx++, OracleTypes.CURSOR);
        stmtReadBuffByMimeTypeIdx.setLong(argIdx++,
                (Authorization == null) ? 0 : Authorization.getSecClusterId());
        stmtReadBuffByMimeTypeIdx.setString(argIdx++,
                (Authorization == null) ? "" : Authorization.getSecUserId().toString());
        stmtReadBuffByMimeTypeIdx.setString(argIdx++,
                (Authorization == null) ? "" : Authorization.getSecSessionId().toString());
        stmtReadBuffByMimeTypeIdx.setLong(argIdx++,
                (Authorization == null) ? 0 : Authorization.getSecClusterId());
        stmtReadBuffByMimeTypeIdx.setLong(argIdx++,
                (Authorization == null) ? 0 : Authorization.getSecTenantId());
        if (MimeTypeId != null) {
            stmtReadBuffByMimeTypeIdx.setInt(argIdx++, MimeTypeId.intValue());
        } else {
            stmtReadBuffByMimeTypeIdx.setNull(argIdx++, java.sql.Types.INTEGER);
        }
        stmtReadBuffByMimeTypeIdx.execute();
        resultSet = (ResultSet) stmtReadBuffByMimeTypeIdx.getObject(1);
        if (resultSet != null) {
            try {
                while (resultSet.next()) {
                    CFAccAttachmentBuff buff = unpackAttachmentResultSetToBuff(resultSet);
                    buffList.add(buff);
                }
                try {
                    resultSet.close();
                } catch (SQLException e) {
                }
                resultSet = null;
            } catch (SQLException e) {
            }
        }
        int idx = 0;
        CFAccAttachmentBuff[] retBuff = new CFAccAttachmentBuff[buffList.size()];
        Iterator<CFAccAttachmentBuff> iter = buffList.iterator();
        while (iter.hasNext()) {
            retBuff[idx++] = iter.next();
        }
        return (retBuff);
    } catch (SQLException e) {
        throw CFLib.getDefaultExceptionFactory().newDbException(getClass(), S_ProcName, e);
    } finally {
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
            }
            resultSet = null;
        }
        if (stmtReadBuffByMimeTypeIdx != null) {
            try {
                stmtReadBuffByMimeTypeIdx.close();
            } catch (SQLException e) {
            }
            stmtReadBuffByMimeTypeIdx = null;
        }
    }
}