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.jabyftw.lobstercraft.player.PlayerHandlerService.java

/**
 * Kick or ban player, online or not. This won't announce to the server and will keep a record on MySQL. This method <b>SHOULD</b> run asynchronously.
 *
 * @param offlinePlayer  player to be kicked
 * @param banType        kick type/*  w  w  w. j a  va 2s  . c  o  m*/
 * @param reason         reason to be at record, from 4 to 120 characters
 * @param moderatorId    moderator to be stored, can be null
 * @param bannedDuration ban duration, can be null
 * @return a ban response to the CommandSender
 */
public BanResponse kickPlayer(@NotNull OfflinePlayer offlinePlayer, @NotNull final BanType banType,
        @NotNull final String reason, @Nullable Integer moderatorId, @Nullable final Long bannedDuration) {
    // Check if player is registered
    if (!offlinePlayer.isRegistered())
        return BanResponse.PLAYER_NOT_REGISTERED;

    // Set variables
    int playerId = offlinePlayer.getPlayerId();
    long recordDate = System.currentTimeMillis();

    // Check unban date
    Long unbanDate;
    if (banType != BanType.PLAYER_TEMPORARILY_BANNED) // Only temporary banned requires this argument
        unbanDate = null;
    else if (bannedDuration != null)
        unbanDate = recordDate + bannedDuration;
    else
        return BanResponse.BAN_DURATION_NOT_SET;

    // Check if reason has right size
    if (!Util.checkStringLength(reason, 4, 120))
        return BanResponse.INVALID_REASON_LENGTH;

    try {
        // Retrieve connection
        Connection connection = LobsterCraft.dataSource.getConnection();

        // Prepare statement
        PreparedStatement preparedStatement = connection.prepareStatement(
                // 6 arguments
                "INSERT INTO `minecraft`.`ban_records` (`user_playerId`, `user_moderatorId`, `banType`, `recordDate`, `reason`, `unbanDate`) VALUES (?, ?, ?, ?, ?, ?);",
                Statement.RETURN_GENERATED_KEYS);

        // Set variables for query
        preparedStatement.setInt(1, playerId);
        preparedStatement.setObject(2, moderatorId, Types.INTEGER); // will write null if is null
        preparedStatement.setByte(3, banType.getTypeId());
        preparedStatement.setLong(4, recordDate);
        preparedStatement.setString(5, reason);
        preparedStatement.setObject(6, unbanDate, Types.BIGINT);

        // Execute statement
        preparedStatement.execute();

        // Retrieve generated keys
        ResultSet generatedKeys = preparedStatement.getGeneratedKeys();

        // Throw error if there is no generated key
        if (!generatedKeys.next())
            throw new SQLException("There is no generated key");

        // Create entry
        BannedPlayerEntry bannedPlayerEntry = new BannedPlayerEntry(generatedKeys.getLong("recordId"),
                moderatorId, banType, recordDate, reason, unbanDate);

        // Add entry to storage
        synchronized (playerBanEntries) {
            playerBanEntries.putIfAbsent(playerId, new HashSet<>());
            playerBanEntries.get(playerId).add(bannedPlayerEntry);
        }

        // Close everything
        generatedKeys.close();
        preparedStatement.close();
        connection.close();

        // Schedule player kick, if he is online
        OnlinePlayer onlinePlayer = offlinePlayer.getOnlinePlayer(null);
        if (onlinePlayer != null)
            Bukkit.getServer().getScheduler().runTask(LobsterCraft.plugin, () -> {
                if (onlinePlayer.getPlayer().isOnline())
                    // Kick player if he is online
                    onlinePlayer.getPlayer().kickPlayer(bannedPlayerEntry.getKickMessage());
            });

        return BanResponse.SUCCESSFULLY_EXECUTED;
    } catch (SQLException exception) {
        exception.printStackTrace();
        return BanResponse.ERROR_OCCURRED;
    }
}

From source file:net.sourceforge.msscodefactory.cfacc.v2_0.CFAccMSSql.CFAccMSSqlContactListTable.java

public void updateContactList(CFAccAuthorization Authorization, CFAccContactListBuff Buff) {
    final String S_ProcName = "updateContactList";
    ResultSet resultSet = null;/*from  w  w w .  j  a va  2 s  .  c  om*/
    try {
        long ContactListId = Buff.getRequiredContactListId();
        long TenantId = Buff.getRequiredTenantId();
        String Description = Buff.getRequiredDescription();
        Integer StripDigits = Buff.getOptionalStripDigits();
        int Revision = Buff.getRequiredRevision();
        Connection cnx = schema.getCnx();
        String sql = "exec sp_update_ctclst ?, ?, ?, ?, ?, ?" + ", " + "?" + ", " + "?" + ", " + "?" + ", "
                + "?" + ", " + "?";
        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++, "CTL");
        stmtUpdateByPKey.setLong(argIdx++, ContactListId);
        stmtUpdateByPKey.setLong(argIdx++, TenantId);
        stmtUpdateByPKey.setString(argIdx++, Description);
        if (StripDigits != null) {
            stmtUpdateByPKey.setInt(argIdx++, StripDigits.intValue());
        } else {
            stmtUpdateByPKey.setNull(argIdx++, java.sql.Types.INTEGER);
        }
        stmtUpdateByPKey.setInt(argIdx++, Revision);
        stmtUpdateByPKey.execute();
        boolean moreResults = true;
        resultSet = null;
        while (resultSet == null) {
            try {
                moreResults = stmtUpdateByPKey.getMoreResults();
            } catch (SQLException e) {
                throw CFLib.getDefaultExceptionFactory().newDbException(getClass(), S_ProcName, e);
            }
            if (moreResults) {
                try {
                    resultSet = stmtUpdateByPKey.getResultSet();
                } catch (SQLException e) {
                }
            } else if (-1 == stmtUpdateByPKey.getUpdateCount()) {
                break;
            }
        }
        if (resultSet == null) {
            throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0,
                    "resultSet");
        }
        if (resultSet.next()) {
            CFAccContactListBuff updatedBuff = unpackContactListResultSetToBuff(resultSet);
            if (resultSet.next()) {
                resultSet.last();
                throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(), S_ProcName,
                        "Did not expect multi-record response, " + resultSet.getRow() + " rows selected");
            }
            Buff.setRequiredDescription(updatedBuff.getRequiredDescription());
            Buff.setOptionalStripDigits(updatedBuff.getOptionalStripDigits());
            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:com.zimbra.cs.db.DbMailItem.java

public static void setFolder(MailItem item, Folder folder) throws ServiceException {
    Mailbox mbox = item.getMailbox();/*ww  w .ja v  a  2s.c  om*/
    if (mbox != folder.getMailbox()) {
        throw MailServiceException.WRONG_MAILBOX();
    }
    checkNamingConstraint(mbox, folder.getId(), item.getName(), item.getId());

    DbConnection conn = mbox.getOperationConnection();
    PreparedStatement stmt = null;
    try {
        String imapRenumber = mbox.isTrackingImap()
                ? ", imap_id = CASE WHEN imap_id IS NULL THEN NULL ELSE 0 END"
                : "";
        int pos = 1;
        boolean hasIndexId = false;
        if (item instanceof Folder) {
            stmt = conn.prepareStatement("UPDATE " + getMailItemTableName(item)
                    + " SET parent_id = ?, folder_id = ?, prev_folders = ?, mod_metadata = ?, change_date = ?"
                    + " WHERE " + IN_THIS_MAILBOX_AND + "id = ?");
            stmt.setInt(pos++, folder.getId());
        } else if (item instanceof Conversation && !(item instanceof VirtualConversation)) {
            stmt = conn.prepareStatement("UPDATE " + getMailItemTableName(item)
                    + " SET folder_id = ?, prev_folders = ?, mod_metadata = ?, change_date = ?" + imapRenumber
                    + " WHERE " + IN_THIS_MAILBOX_AND + "parent_id = ?");
        } else {
            // set the indexId, in case it changed (moving items out of junk can trigger an index ID change)
            hasIndexId = true;
            stmt = conn.prepareStatement("UPDATE " + getMailItemTableName(item)
                    + " SET folder_id = ?, prev_folders = ?, index_id = ?, mod_metadata = ?, change_date = ? "
                    + imapRenumber + " WHERE " + IN_THIS_MAILBOX_AND + "id = ?");
        }
        stmt.setInt(pos++, folder.getId());
        int modseq = mbox.getOperationChangeID();
        String prevFolders = findPrevFolders(item, modseq);
        stmt.setString(pos++, prevFolders);
        item.getUnderlyingData().setPrevFolders(prevFolders);
        if (hasIndexId) {
            if (item.getIndexStatus() == MailItem.IndexStatus.NO) {
                stmt.setNull(pos++, Types.INTEGER);
            } else {
                stmt.setInt(pos++, item.getIndexId());
            }
        }
        stmt.setInt(pos++, modseq);
        stmt.setInt(pos++, mbox.getOperationTimestamp());
        pos = setMailboxId(stmt, mbox, pos);
        stmt.setInt(pos++, item instanceof VirtualConversation ? ((VirtualConversation) item).getMessageId()
                : item.getId());
        stmt.executeUpdate();
    } catch (SQLException e) {
        // catch item_id uniqueness constraint violation and return failure
        if (Db.errorMatches(e, Db.Error.DUPLICATE_ROW)) {
            throw MailServiceException.ALREADY_EXISTS(item.getName(), e);
        } else {
            throw ServiceException.FAILURE("writing new folder data for item " + item.getId(), e);
        }
    } finally {
        DbPool.closeStatement(stmt);
    }
}

From source file:net.sourceforge.msscodefactory.cfasterisk.v2_1.CFAstSybase.CFAstSybaseSchema.java

public int nextMimeTypeIdGen() {
    if (!inTransaction) {
        throw CFLib.getDefaultExceptionFactory().newUsageException(getClass(), "nextMimeTypeIdGen",
                "Not in a transaction");
    }/* ww  w .ja v  a 2 s  . c  o m*/
    CallableStatement stmtNext = null;
    try {
        final String sql = "{ call sp_next_mimetypeidgen( ? ) }";
        stmtNext = cnx.prepareCall(sql);
        stmtNext.registerOutParameter(1, java.sql.Types.INTEGER);
        stmtNext.execute();
        int nextId = stmtNext.getInt(1);
        return (nextId);
    } catch (SQLException e) {
        throw CFLib.getDefaultExceptionFactory().newDbException(getClass(), "nextMimeTypeIdGen", e);
    } finally {
        if (stmtNext != null) {
            try {
                stmtNext.close();
            } catch (SQLException e) {
            }
            stmtNext = null;
        }
    }
}

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

public void updateContactList(CFAccAuthorization Authorization, CFAccContactListBuff Buff) {
    final String S_ProcName = "updateContactList";
    ResultSet resultSet = null;// w w w  .j a v  a2s.c o m
    try {
        long ContactListId = Buff.getRequiredContactListId();
        long TenantId = Buff.getRequiredTenantId();
        String Description = Buff.getRequiredDescription();
        Integer StripDigits = Buff.getOptionalStripDigits();
        int Revision = Buff.getRequiredRevision();
        Connection cnx = schema.getCnx();
        String sql = "call " + schema.getLowerSchemaDbName() + ".sp_update_ctclst( ?, ?, ?, ?, ?, ?" + ", "
                + "?" + ", " + "?" + ", " + "?" + ", " + "?" + ", " + "?" + " )";
        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++, "CTL");
        stmtUpdateByPKey.setLong(argIdx++, ContactListId);
        stmtUpdateByPKey.setLong(argIdx++, TenantId);
        stmtUpdateByPKey.setString(argIdx++, Description);
        if (StripDigits != null) {
            stmtUpdateByPKey.setInt(argIdx++, StripDigits.intValue());
        } else {
            stmtUpdateByPKey.setNull(argIdx++, java.sql.Types.INTEGER);
        }
        stmtUpdateByPKey.setInt(argIdx++, Revision);
        try {
            resultSet = stmtUpdateByPKey.executeQuery();
        } catch (SQLException e) {
            if (e.getErrorCode() != 1329) {
                throw e;
            }
            resultSet = null;
        }
        if ((resultSet != null) && resultSet.next()) {
            CFAccContactListBuff updatedBuff = unpackContactListResultSetToBuff(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.setRequiredDescription(updatedBuff.getRequiredDescription());
            Buff.setOptionalStripDigits(updatedBuff.getOptionalStripDigits());
            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:info.raack.appliancelabeler.data.JDBCDatabase.java

public void storeUserOnOffLabels(final List<ApplianceStateTransition> detectedStateTransitions) {

    for (final ApplianceStateTransition transition : detectedStateTransitions) {
        KeyHolder keyHolder = new GeneratedKeyHolder();
        jdbcTemplate.update(new PreparedStatementCreator() {
            public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
                PreparedStatement ps = connection.prepareStatement(insertApplianceStateTransition,
                        new String[] { "id" });

                ps.setInt(1, transition.getUserAppliance().getId());
                if (transition.getDetectionAlgorithmId() > 0) {
                    ps.setInt(2, transition.getDetectionAlgorithmId());
                } else {
                    ps.setNull(2, Types.INTEGER);
                }//w  w w  .jav  a 2s.co m
                ps.setLong(3, transition.getTime());
                ps.setBoolean(4, transition.isOn());
                return ps;
            }
        }, keyHolder);

        transition.setId(keyHolder.getKey().intValue());
    }
}

From source file:dk.netarkivet.common.utils.DBUtils.java

/**
 * Insert an Integer in prepared statement.
 * @param s a prepared statement/*w w  w.jav a  2s. co  m*/
 * @param i the index of the statement, where the Integer should be inserted
 * @param value The Integer to insert (maybe null)
 * @throws SQLException If i does not correspond to a
 * parameter marker in the PreparedStatement, or a database access error
 * occurs or this method is called on a closed PreparedStatement
 */
public static void setIntegerMaybeNull(PreparedStatement s, int i, Integer value) throws SQLException {
    ArgumentNotValid.checkNotNull(s, "PreparedStatement s");

    if (value != null) {
        s.setInt(i, value);
    } else {
        s.setNull(i, Types.INTEGER);
    }
}

From source file:com.rapid.actions.Database.java

public JSONObject doQuery(RapidRequest rapidRequest, JSONObject jsonAction, Application application,
        DataFactory df) throws Exception {

    // place holder for the object we're going to return
    JSONObject jsonData = null;/*w ww  .j ava2  s .c o  m*/

    // retrieve the sql
    String sql = _query.getSQL();

    // only if there is some sql is it worth going further
    if (sql != null) {

        // get any json inputs
        JSONObject jsonInputData = jsonAction.optJSONObject("data");

        // initialise the parameters list
        ArrayList<Parameters> parametersList = new ArrayList<Parameters>();

        // populate the parameters from the inputs collection (we do this first as we use them as the cache key due to getting values from the session)
        if (_query.getInputs() == null) {

            // just add an empty parameters member if no inputs
            parametersList.add(new Parameters());

        } else {

            // if there is input data
            if (jsonInputData != null) {

                // get any input fields
                JSONArray jsonFields = jsonInputData.optJSONArray("fields");
                // get any input rows
                JSONArray jsonRows = jsonInputData.optJSONArray("rows");

                // if we have fields and rows
                if (jsonFields != null && jsonRows != null) {

                    // loop the input rows (only the top row if not multirow)
                    for (int i = 0; i < jsonRows.length() && (_query.getMultiRow() || i == 0); i++) {

                        // get this jsonRow
                        JSONArray jsonRow = jsonRows.getJSONArray(i);
                        // make the parameters for this row
                        Parameters parameters = new Parameters();

                        // loop the query inputs
                        for (Parameter input : _query.getInputs()) {
                            // get the input id
                            String id = input.getItemId();
                            // get the input field
                            String field = input.getField();
                            // add field to id if present
                            if (field != null && !"".equals(field))
                                id += "." + field;
                            // retain the value
                            String value = null;
                            // if it looks like a control, or a system value (bit of extra safety checking)
                            if ("P".equals(id.substring(0, 1)) && id.indexOf("_C") > 0
                                    || id.indexOf("System.") == 0) {
                                // loop the json inputs looking for the value
                                if (jsonInputData != null) {
                                    for (int j = 0; j < jsonFields.length(); j++) {
                                        // get the id from the fields
                                        String jsonId = jsonFields.optString(j);
                                        // if the id we want matches this one 
                                        if (id.toLowerCase().equals(jsonId.toLowerCase())) {
                                            // get the value
                                            value = jsonRow.optString(j, null);
                                            // no need to keep looking
                                            break;
                                        }
                                    }
                                }
                            }
                            // if still null try the session
                            if (value == null)
                                value = (String) rapidRequest.getSessionAttribute(input.getItemId());
                            // add the parameter
                            parameters.add(value);
                        }

                        // add the parameters to the list
                        parametersList.add(parameters);

                    } // row loop

                } // input fields and rows check

            } // input data check

        } // query inputs check

        // placeholder for the action cache
        ActionCache actionCache = rapidRequest.getRapidServlet().getActionCache();

        // if an action cache was found
        if (actionCache != null) {

            // log that we found action cache
            _logger.debug("Database action cache found");

            // attempt to fetch data from the cache
            jsonData = actionCache.get(application.getId(), getId(), parametersList.toString());

        }

        // if there isn't a cache or no data was retrieved
        if (jsonData == null) {

            try {

                // instantiate jsonData
                jsonData = new JSONObject();
                // fields collection
                JSONArray jsonFields = new JSONArray();
                // rows collection can start initialised
                JSONArray jsonRows = new JSONArray();

                // trim the sql
                sql = sql.trim();

                // check the verb
                if (sql.toLowerCase().startsWith("select") || sql.toLowerCase().startsWith("with")) {

                    // set readonly to true (makes for faster querying)
                    df.setReadOnly(true);

                    // loop the parameterList getting a result set for each parameters (input row)
                    for (Parameters parameters : parametersList) {

                        // get the result set!
                        ResultSet rs = df.getPreparedResultSet(rapidRequest, sql, parameters);

                        // get it's meta data for the field names
                        ResultSetMetaData rsmd = rs.getMetaData();

                        // got fields indicator
                        boolean gotFields = false;

                        // loop the result set
                        while (rs.next()) {

                            // initialise the row
                            JSONArray jsonRow = new JSONArray();

                            // loop the columns
                            for (int i = 0; i < rsmd.getColumnCount(); i++) {
                                // add the field name to the fields collection if not done yet
                                if (!gotFields)
                                    jsonFields.put(rsmd.getColumnLabel(i + 1));
                                // get the column type
                                int columnType = rsmd.getColumnType(i + 1);
                                // add the data to the row according to it's type   
                                switch (columnType) {
                                case (Types.NUMERIC):
                                    jsonRow.put(rs.getDouble(i + 1));
                                    break;
                                case (Types.INTEGER):
                                    jsonRow.put(rs.getInt(i + 1));
                                    break;
                                case (Types.BIGINT):
                                    jsonRow.put(rs.getLong(i + 1));
                                    break;
                                case (Types.FLOAT):
                                    jsonRow.put(rs.getFloat(i + 1));
                                    break;
                                case (Types.DOUBLE):
                                    jsonRow.put(rs.getDouble(i + 1));
                                    break;
                                default:
                                    jsonRow.put(rs.getString(i + 1));
                                }
                            }
                            // add the row to the rows collection
                            jsonRows.put(jsonRow);
                            // remember we now have our fields
                            gotFields = true;

                        }

                        // close the record set
                        rs.close();

                    }

                } else {

                    // assume rows affected is 0
                    int rows = 0;

                    // sql check
                    if (sql.length() > 0) {

                        // perform update for all incoming parameters (one parameters collection for each row)
                        for (Parameters parameters : parametersList) {
                            rows += df.getPreparedUpdate(rapidRequest, sql, parameters);
                        }

                        // add a psuedo field 
                        jsonFields.put("rows");

                        // create a row array
                        JSONArray jsonRow = new JSONArray();
                        // add the rows updated
                        jsonRow.put(rows);
                        // add the row we just made
                        jsonRows.put(jsonRow);

                    }

                }

                // add the fields to the data object
                jsonData.put("fields", jsonFields);
                // add the rows to the data object
                jsonData.put("rows", jsonRows);

                // check for any child database actions
                if (_childDatabaseActions != null) {
                    // if there really are some
                    if (_childDatabaseActions.size() > 0) {
                        // get any child data
                        JSONArray jsonChildQueries = jsonAction.optJSONArray("childQueries");
                        // if there was some
                        if (jsonChildQueries != null) {
                            // loop
                            for (int i = 0; i < jsonChildQueries.length(); i++) {
                                // fetch the data
                                JSONObject jsonChildAction = jsonChildQueries.getJSONObject(i);
                                // read the index (the position of the child this related to
                                int index = jsonChildAction.getInt("index");
                                // get the relevant child action
                                Database childDatabaseAction = _childDatabaseActions.get(index);
                                // get the resultant child data
                                JSONObject jsonChildData = childDatabaseAction.doQuery(rapidRequest,
                                        jsonChildAction, application, df);

                                // a map for indexes of matching fields between our parent and child
                                Map<Integer, Integer> fieldsMap = new HashMap<Integer, Integer>();
                                // the child fields
                                JSONArray jsonChildFields = jsonChildData.getJSONArray("fields");
                                if (jsonChildFields != null) {
                                    // loop the parent fields
                                    for (int j = 0; j < jsonFields.length(); j++) {
                                        // loop the child fields
                                        for (int k = 0; k < jsonChildFields.length(); k++) {
                                            // get parent field
                                            String field = jsonFields.getString(j);
                                            // get child field
                                            String childField = jsonChildFields.getString(k);
                                            // if both not null
                                            if (field != null && childField != null) {
                                                // check for match
                                                if (field.toLowerCase().equals(childField.toLowerCase()))
                                                    fieldsMap.put(j, k);
                                            }
                                        }
                                    }
                                }

                                // add a field for the results of this child action
                                jsonFields.put("childAction" + (i + 1));

                                // if matching fields
                                if (fieldsMap.size() > 0) {
                                    // an object with a null value for when there is no match
                                    Object nullObject = null;
                                    // get the child rows
                                    JSONArray jsonChildRows = jsonChildData.getJSONArray("rows");
                                    // if we had some
                                    if (jsonChildRows != null) {
                                        // loop the parent rows
                                        for (int j = 0; j < jsonRows.length(); j++) {
                                            // get the parent row
                                            JSONArray jsonRow = jsonRows.getJSONArray(j);
                                            // make a new rows collection for the child subset
                                            JSONArray jsonChildRowsSubset = new JSONArray();
                                            // loop the child rows
                                            for (int k = 0; k < jsonChildRows.length(); k++) {
                                                // get the child row
                                                JSONArray jsonChildRow = jsonChildRows.getJSONArray(k);
                                                // assume no matches
                                                int matches = 0;
                                                // loop the fields map
                                                for (Integer l : fieldsMap.keySet()) {
                                                    // parent value
                                                    Object parentValue = null;
                                                    // get the value if there are enough
                                                    if (jsonRow.length() > l)
                                                        parentValue = jsonRow.get(l);
                                                    // child value
                                                    Object childValue = null;
                                                    if (jsonChildRow.length() > l)
                                                        childValue = jsonChildRow.get(fieldsMap.get(l));
                                                    // non null check
                                                    if (parentValue != null && childValue != null) {
                                                        // a string we will concert the child value to
                                                        String parentString = null;
                                                        // check the parent value type
                                                        if (parentValue.getClass() == String.class) {
                                                            parentString = (String) parentValue;
                                                        } else if (parentValue.getClass() == Integer.class) {
                                                            parentString = Integer
                                                                    .toString((Integer) parentValue);
                                                        } else if (parentValue.getClass() == Long.class) {
                                                            parentString = Long.toString((Long) parentValue);
                                                        } else if (parentValue.getClass() == Double.class) {
                                                            parentString = Double
                                                                    .toString((Double) parentValue);
                                                        } else if (parentValue.getClass() == Boolean.class) {
                                                            parentString = Boolean
                                                                    .toString((Boolean) parentValue);
                                                        }
                                                        // a string we will convert the child value to
                                                        String childString = null;
                                                        // check the parent value type
                                                        if (childValue.getClass() == String.class) {
                                                            childString = (String) childValue;
                                                        } else if (childValue.getClass() == Integer.class) {
                                                            childString = Integer
                                                                    .toString((Integer) childValue);
                                                        } else if (childValue.getClass() == Long.class) {
                                                            childString = Long.toString((Long) childValue);
                                                        } else if (childValue.getClass() == Double.class) {
                                                            childString = Double.toString((Double) childValue);
                                                        } else if (childValue.getClass() == Boolean.class) {
                                                            childString = Boolean
                                                                    .toString((Boolean) childValue);
                                                        }
                                                        // non null check
                                                        if (parentString != null && childString != null) {
                                                            // do the match!
                                                            if (parentString.equals(childString))
                                                                matches++;
                                                        }
                                                    } // values non null                                          
                                                } // field map loop
                                                  // if we got some matches for all the fields add this row to the subset
                                                if (matches == fieldsMap.size())
                                                    jsonChildRowsSubset.put(jsonChildRow);
                                            } // child row loop
                                              // if our child subset has rows in it
                                            if (jsonChildRowsSubset.length() > 0) {
                                                // create a new childSubset object
                                                JSONObject jsonChildDataSubset = new JSONObject();
                                                // add the fields
                                                jsonChildDataSubset.put("fields", jsonChildFields);
                                                // add the subset of rows
                                                jsonChildDataSubset.put("rows", jsonChildRowsSubset);
                                                // add the child database action data subset
                                                jsonRow.put(jsonChildDataSubset);
                                            } else {
                                                // add an empty cell
                                                jsonRow.put(nullObject);
                                            }
                                        } // parent row loop                                 
                                    } // jsonChildRows null check
                                } else {
                                    // loop the parent rows
                                    for (int j = 0; j < jsonRows.length(); j++) {
                                        // get the row
                                        JSONArray jsonRow = jsonRows.getJSONArray(j);
                                        // add the child database action data
                                        jsonRow.put(jsonChildData);
                                    }
                                } // matching fields check

                            } // jsonChildQueries loop
                        } // jsonChildQueries null check                      
                    } // _childDatabaseActions size > 0                                                      
                } // _childDatabaseActions not null

                // cache if in use
                if (actionCache != null)
                    actionCache.put(application.getId(), getId(), parametersList.toString(), jsonData);

            } catch (Exception ex) {

                // log the error
                _logger.error(ex);

                // close the data factory and silently fail
                try {
                    df.close();
                } catch (Exception ex2) {
                }

                // only throw if no action cache
                if (actionCache == null) {
                    throw ex;
                } else {
                    _logger.debug("Error not shown to user due to cache : " + ex.getMessage());
                }

            } // jsonData not null

        } // jsonData == null

    } // got sql

    return jsonData;

}

From source file:net.sourceforge.msscodefactory.cfacc.v2_0.CFAccDb2LUW.CFAccDb2LUWAttachmentTable.java

public CFAccAttachmentBuff[] readBuffByMimeTypeIdx(CFAccAuthorization Authorization, Integer MimeTypeId) {
    final String S_ProcName = "readBuffByMimeTypeIdx";
    ResultSet resultSet = null;//from  w w w  .  jav  a 2s .c  o  m
    try {
        Connection cnx = schema.getCnx();
        final String sql = "CALL sp_read_attchmnt_by_mimetypeidx( ?, ?, ?, ?, ?" + ", " + "?" + " )";
        if (stmtReadBuffByMimeTypeIdx == null) {
            stmtReadBuffByMimeTypeIdx = cnx.prepareStatement(sql);
        }
        int argIdx = 1;
        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);
        }
        resultSet = stmtReadBuffByMimeTypeIdx.executeQuery();
        List<CFAccAttachmentBuff> buffList = new LinkedList<CFAccAttachmentBuff>();
        while (resultSet.next()) {
            CFAccAttachmentBuff buff = unpackAttachmentResultSetToBuff(resultSet);
            buffList.add(buff);
        }
        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;
        }
    }
}

From source file:net.sourceforge.msscodefactory.cfacc.v2_0.CFAccPgSql.CFAccPgSqlAttachmentTable.java

public CFAccAttachmentBuff[] readBuffByMimeTypeIdx(CFAccAuthorization Authorization, Integer MimeTypeId) {
    final String S_ProcName = "readBuffByMimeTypeIdx";
    ResultSet resultSet = null;/*from w ww. ja  v a 2s .  c o m*/
    try {
        Connection cnx = schema.getCnx();
        String sql = "SELECT * FROM " + schema.getLowerSchemaDbName()
                + ".sp_read_attchmnt_by_mimetypeidx( ?, ?, ?, ?, ?" + ", " + "?" + " )";
        if (stmtReadBuffByMimeTypeIdx == null) {
            stmtReadBuffByMimeTypeIdx = cnx.prepareStatement(sql);
        }
        int argIdx = 1;
        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);
        }
        resultSet = stmtReadBuffByMimeTypeIdx.executeQuery();
        List<CFAccAttachmentBuff> buffList = new LinkedList<CFAccAttachmentBuff>();
        while (resultSet.next()) {
            CFAccAttachmentBuff buff = unpackAttachmentResultSetToBuff(resultSet);
            buffList.add(buff);
        }
        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;
        }
    }
}