Duplications

FileLine
org/apache/torque/util/BasePeerImpl.java1442
org/apache/torque/util/BasePeerImpl.java1600
            List<Object> replacements = setPreparedStatementReplacements(
                    statement,
                    query.getPreparedStatementReplacements(),
                    0);

            long startTime = System.currentTimeMillis();
            log.debug("Executing query " + query
                    + ", parameters = "
                    + replacements);

            resultSet = statement.executeQuery();
            long queryEndTime = System.currentTimeMillis();
            log.trace("query took " + (queryEndTime - startTime)
                    + " milliseconds");

            long offset;
            Database database = Torque.getDatabase(criteria.getDbName());
            if (database.getAdapter().supportsNativeOffset())
            {
                offset = 0; //database takes care of offset
            }
            else
            {
                offset = criteria.getOffset();
            }

            long limit;
            if (database.getAdapter().supportsNativeLimit())
            {
                limit = -1; //database takes care of offset
            }
            else
            {
                if (database.getAdapter().supportsNativeOffset())
                {
                    limit = criteria.getLimit();
                }
                else
                {
                    if (criteria.getLimit() == -1)
                    {
                        limit = criteria.getLimit();
                    }
                    else
                    {
                        limit = offset + criteria.getLimit();
                    }
                }
            }

            List<TT> result = new ArrayList<TT>();
            int rowNumber = 0;
            while (resultSet.next())
            {
                if (rowNumber < offset)
                {
                    rowNumber++;
                    continue;
                }
                if (limit >= 0 && rowNumber >= limit)
                {
                    break;
                }

                TT rowResult = mapper.processRow(resultSet, 0);
                result.add(rowResult);

                rowNumber++;
            }
            long mappingEndTime = System.currentTimeMillis();
            log.trace("mapping took " + (mappingEndTime - queryEndTime)
                    + " milliseconds");

            if (criteria.isSingleRecord() && result.size() > 1)
            {
                throw new TooManyRowsException(
                        "Criteria expected single Record and "
                        + "Multiple Records were selected");
            }
            return result;
        }
        catch (SQLException e)
        {
            String dbName = criteria.getDbName();
            final Adapter adapter = Torque.getAdapter(dbName);
            if (adapter != null)
            {
                throw adapter.toTorqueException(e);
            }
            throw new TorqueException(e);
        }
        finally
        {
            if (resultSet != null)
            {
                try
                {
                    resultSet.close();
                }
                catch (SQLException e)
                {
                    log.warn("error closing resultSet", e);
                }
            }
            if (statement != null)
            {
                try
                {
                    statement.close();
                }
                catch (SQLException e)
                {
                    log.warn("error closing statement", e);
                }
            }
        }
    }

    /**
     * Selects at most a single row from a database an maps them to objects.
     *
     * @param criteria A Criteria specifying the records to select, not null.
     * @param mapper The mapper creating the objects from the resultSet,
     *        not null.
     *
     * @return The selected row, or null if no records was selected.
     *
     * @throws TorqueException if querying the database fails.
     */
    public <TT> TT doSelectSingleRecord(
FileLine
org/apache/torque/util/SummaryHelper.java308
org/apache/torque/util/SummaryHelper.java416
        org.apache.torque.criteria.Criteria c = buildCriteria(crit);
        String query = SqlBuilder.buildQuery(c).toString();
        RecordMapper<List<Object>> mapper = new ObjectListMapper(resultTypes);

        Statement statement = null;
        ResultSet resultSet = null;
        List<List<Object>> rows = new ArrayList<List<Object>>();
        try
        {
            statement = conn.createStatement();
            long startTime = System.currentTimeMillis();
            logger.debug("Executing query " + query);

            resultSet = statement.executeQuery(query.toString());
            long queryEndTime = System.currentTimeMillis();
            logger.trace("query took " + (queryEndTime - startTime)
                    + " milliseconds");

            while (resultSet.next())
            {
                List<Object> rowResult = mapper.processRow(resultSet, 0);
                rows.add(rowResult);
            }
            long mappingEndTime = System.currentTimeMillis();
            logger.trace("mapping took " + (mappingEndTime - queryEndTime)
                    + " milliseconds");
        }
        catch (SQLException e)
        {
            throw new TorqueException(e);
        }
        finally
        {
            if (resultSet != null)
            {
                try
                {
                    resultSet.close();
                }
                catch (SQLException e)
                {
                    logger.warn("error closing resultSet", e);
                }
            }
            if (statement != null)
            {
                try
                {
                    statement.close();
                }
                catch (SQLException e)
                {
                    logger.warn("error closing statement", e);
                }
            }
        }

        List<ListOrderedMapCI> resultsList = new Vector<ListOrderedMapCI>(rows.size());
        List<String> columnNames = new ArrayList<String>();
        for (Column column : c.getSelectColumns())
        {
            columnNames.add(column.getColumnName());
        }
        columnNames.addAll(c.getAsColumns().keySet());
        for (List<Object> row : rows)
        {
            ListOrderedMapCI recordMap = new ListOrderedMapCI();
            for (int i = 0; i < row.size(); i++)
            {
                Object value = row.get(i);
                String cName = columnNames.get(i);
                if (cName == null || cName.equals(""))
                 {
                    if (excludeExprColumns())
                    {
                        continue;
                    }
                    cName = "Expr" + i;
                }
                recordMap.put(cName, value);
            }
            resultsList.add(recordMap);
        }
        return resultsList;
    }
FileLine
org/apache/torque/util/BasePeerImpl.java1984
org/apache/torque/util/BasePeerImpl.java2087
                org.apache.torque.criteria.Criteria criteria,
                ColumnValues updateValues,
                Connection connection)
            throws TorqueException
    {
        Query query = SqlBuilder.buildQuery(criteria);
        query.setType(Query.Type.UPDATE);

        query.getFromClause().clear();
        String fullTableName = SqlBuilder.getFullTableName(
                getTableMap().getName(),
                criteria.getDbName());
        query.getFromClause().add(new FromElement(fullTableName));

        List<JdbcTypedValue> replacementObjects
                = new ArrayList<JdbcTypedValue>();
        for (Map.Entry<Column, JdbcTypedValue> updateValue
                : updateValues.entrySet())
        {
            Column column = updateValue.getKey();
            query.getSelectClause().add(column.getColumnName());
            replacementObjects.add(updateValue.getValue());
        }

        PreparedStatement preparedStatement = null;
        try
        {
            preparedStatement = connection.prepareStatement(query.toString());
            int position = 1;
            for (JdbcTypedValue replacementObject : replacementObjects)
            {
                Object value = replacementObject.getValue();
                if (value != null)
                {
                    preparedStatement.setObject(position, value);
                }
                else
                {
                    preparedStatement.setNull(
                            position,
                            replacementObject.getJdbcType());
                }
                position++;
            }
            List<Object> replacements = setPreparedStatementReplacements(
                    preparedStatement,
                    query.getPreparedStatementReplacements(),
                    position - 1);
            long startTime = System.currentTimeMillis();
            log.debug("Executing update " + query.toString()
                    + " using update parameters " + replacementObjects
                    + " and query parameters "
                    + replacements);

            int affectedRows = preparedStatement.executeUpdate();
            long queryEndTime = System.currentTimeMillis();
            log.trace("update took " + (queryEndTime - startTime)
                    + " milliseconds");

            preparedStatement.close();
            preparedStatement = null;
            return affectedRows;
        }
        catch (SQLException e)
        {
FileLine
org/apache/torque/sql/SqlBuilder.java1469
org/apache/torque/sql/whereclausebuilder/InBuilder.java60
    {
        PreparedStatementPart result = new PreparedStatementPart();

        boolean ignoreCaseApplied = false;
        List<String> inClause = new ArrayList<String>();
        boolean nullContained = false;
        if (whereClausePart.getRValue() instanceof Iterable)
        {
            for (Object listValue : (Iterable<?>) whereClausePart.getRValue())
            {
                if (listValue == null)
                {
                    nullContained = true;
                    continue;
                }
                result.getPreparedStatementReplacements().add(listValue);
                if (ignoreCase && listValue instanceof String)
                {
                    inClause.add(adapter.ignoreCase("?"));
                    ignoreCaseApplied = true;
                }
                else
                {
                    inClause.add("?");
                }
            }
        }
        else if (whereClausePart.getRValue().getClass().isArray())
        {
            for (Object arrayValue : (Object[]) whereClausePart.getRValue())
            {
                if (arrayValue == null)
                {
                    nullContained = true;
                    continue;
                }
                result.getPreparedStatementReplacements().add(arrayValue);
                if (ignoreCase && arrayValue instanceof String)
                {
                    inClause.add(adapter.ignoreCase("?"));
                    ignoreCaseApplied = true;
                }
                else
                {
                    inClause.add("?");
                }
            }
        }
        else
        {
            throw new IllegalArgumentException(
                    "Unknown rValue type "
                    + whereClausePart.getRValue().getClass().getName()
                    + ". rValue must be an instance of "
                    + " Iterable or Array");
        }

        if (nullContained)
        {
            result.getSql().append('(');
        }
FileLine
org/apache/torque/sql/SqlBuilder.java1394
org/apache/torque/sql/whereclausebuilder/LikeBuilder.java156
        if (replaceWithEquals)
        {
            if (whereClausePart.getOperator().equals(SqlEnum.NOT_LIKE)
                    || whereClausePart.getOperator().equals(SqlEnum.NOT_ILIKE))
            {
                result.getSql().append(SqlEnum.NOT_EQUAL);
            }
            else
            {
                result.getSql().append(SqlEnum.EQUAL);
            }

            // remove escape backslashes from String
            position = 0;
            sb = new StringBuffer();
            while (position < value.length())
            {
                char checkWildcard = value.charAt(position);

                if (checkWildcard == BACKSLASH
                        && position + 1 < value.length())
                {
                    position++;
                    // code below copies escaped character into sb
                    checkWildcard = value.charAt(position);
                }
                sb.append(checkWildcard);
                position++;
            }
            value = sb.toString();
        }
        else
        {
            result.getSql().append(whereClausePart.getOperator());
        }

        String rValueSql = "?";
        // handle ignoreCase if necessary
        if (ignoreCase && (!(adapter.useIlike()) || replaceWithEquals))
        {
            rValueSql = adapter.ignoreCase(rValueSql);
        }
        // handle escape clause if necessary
        if (!replaceWithEquals && adapter.useEscapeClauseForLike())
        {
            rValueSql = rValueSql + SqlEnum.ESCAPE + "'\\'";
        }

        result.getPreparedStatementReplacements().add(value);
        result.getSql().append(rValueSql);
        return result;
    }
FileLine
org/apache/torque/util/CountHelper.java297
org/apache/torque/util/CountHelper.java352
                org.apache.torque.criteria.Criteria c,
                Connection conn,
                String columnName,
                TableMap tableMap)
            throws TorqueException
    {
        /* Clear the select columns. */
        c.getSelectColumns().clear();
        c.getOrderByColumns().clear();
        c.getGroupByColumns().clear();

        UniqueList<String> criteriaSelectModifiers
            = c.getSelectModifiers();

        boolean distinct = false;
        if (criteriaSelectModifiers != null
            && criteriaSelectModifiers.size() > 0
            && criteriaSelectModifiers.contains(SqlEnum.DISTINCT.toString()))
        {
            criteriaSelectModifiers.remove(SqlEnum.DISTINCT.toString());
            distinct = true;
        }

        c.addSelectColumn(new Count(new ColumnImpl(columnName), distinct));

        String databaseName = (c.getDbName() == null)
                ? Torque.getDefaultDB()
                : c.getDbName();

        BasePeerImpl<Integer> peer = new BasePeerImpl<Integer>(
                new IntegerMapper(),
                tableMap, databaseName);

        List<Integer> result = (conn == null)
            ? peer.doSelect(c)
            : peer.doSelect(c, conn);

        return result.get(0);
    }
FileLine
org/apache/torque/sql/SqlBuilder.java1302
org/apache/torque/sql/whereclausebuilder/LikeBuilder.java59
    public PreparedStatementPart buildPs(
                WhereClauseExpression whereClausePart,
                boolean ignoreCase,
                Adapter adapter)
            throws TorqueException
    {
        if (!(whereClausePart.getRValue() instanceof String))
        {
            throw new TorqueException(
                "rValue must be a String for the operator "
                    + whereClausePart.getOperator());
        }
        String value = (String) whereClausePart.getRValue();
        // If selection criteria contains wildcards use LIKE otherwise
        // use = (equals).  Wildcards can be escaped by prepending
        // them with \ (backslash). However, if we switch from
        // like to equals, we need to remove the escape characters.
        // from the wildcards.
        // So we need two passes: The first replaces * and ? by % and _,
        // and checks whether we switch to equals,
        // the second removes escapes if we have switched to equals.
        int position = 0;
        StringBuffer sb = new StringBuffer();
        boolean replaceWithEquals = true;
        while (position < value.length())
        {
            char checkWildcard = value.charAt(position);

            switch (checkWildcard)
            {
            case BACKSLASH:
                if (position + 1 >= value.length())
                {
                    // ignore backslashes at end
                    break;
                }
                position++;
                char escapedChar = value.charAt(position);
                if (escapedChar != '*' && escapedChar != '?')
                {
                    sb.append(checkWildcard);
                }
                // code below copies escaped character into sb
                checkWildcard = escapedChar;
                break;
            case '%':
            case '_':
                replaceWithEquals = false;
                break;
            case '*':
                replaceWithEquals = false;
                checkWildcard = '%';
                break;
            case '?':
                replaceWithEquals = false;
                checkWildcard = '_';
                break;
            default:
                break;
            }

            sb.append(checkWildcard);
            position++;
        }
        value = sb.toString();
FileLine
org/apache/torque/util/BasePeerImpl.java443
org/apache/torque/util/BasePeerImpl.java597
            preparedStatement = con.prepareStatement(sql);
            List<Object> replacements = setPreparedStatementReplacements(
                    preparedStatement,
                    query.getPreparedStatementReplacements(),
                    0);
            long startTime = System.currentTimeMillis();
            log.debug("Executing delete " + sql
                    + ", parameters = "
                    + replacements);

            int affectedRows = preparedStatement.executeUpdate();
            long queryEndTime = System.currentTimeMillis();
            log.trace("delete took " + (queryEndTime - startTime)
                    + " milliseconds");

            preparedStatement.close();
            preparedStatement = null;
            return affectedRows;
        }
        catch (SQLException e)
        {
            final String dbName = criteria.getDbName();
            final Adapter adapter = Torque.getAdapter(dbName);
            if (adapter != null)
            {
                throw adapter.toTorqueException(e);
            }
            throw new TorqueException(e);
        }
        finally
        {
            if (preparedStatement != null)
            {
                try
                {
                    preparedStatement.close();
                }
                catch (SQLException e)
                {
                    log.warn("error closing prepared statement", e);
                }
            }
        }
    }
FileLine
org/apache/torque/util/SummaryHelper.java516
org/apache/torque/util/SummaryHelper.java598
            org.apache.torque.criteria.Criteria c) throws TorqueException
    {
        c.getSelectColumns().clear();
        c.getGroupByColumns().clear();

        UniqueList<String> criteriaSelectModifiers;
        criteriaSelectModifiers = c.getSelectModifiers();

        if (criteriaSelectModifiers != null
            && criteriaSelectModifiers.size() > 0
            && criteriaSelectModifiers.contains(SqlEnum.DISTINCT.toString()))
        {
            criteriaSelectModifiers.remove(SqlEnum.DISTINCT.toString());
        }
        c.setIgnoreCase(false);

        List<Column> cols = getGroupByColumns();
        boolean haveFromTable = !cols.isEmpty(); // Group By cols define src table.
        for (Column col : cols)
        {
            c.addGroupByColumn(col);
            c.addSelectColumn(col);
        }
        if (haveFromTable)
        {
            logger.debug("From table defined by Group By Cols");
        }

        // Check if the from table is set via a where clause.
        if (!haveFromTable && c.getTopLevelCriterion() != null)
FileLine
org/apache/torque/criteria/Criteria.java56
org/apache/torque/util/Criteria.java71
public class Criteria implements Serializable, CriteriaInterface<Criteria>
{
    /** Serial version. */
    private static final long serialVersionUID = -9001666575933085601L;

    /** Comparison type. */
    public static final SqlEnum EQUAL = SqlEnum.EQUAL;

    /** Comparison type. */
    public static final SqlEnum NOT_EQUAL = SqlEnum.NOT_EQUAL;

    /** Comparison type. */
    public static final SqlEnum ALT_NOT_EQUAL = SqlEnum.ALT_NOT_EQUAL;

    /** Comparison type. */
    public static final SqlEnum GREATER_THAN = SqlEnum.GREATER_THAN;

    /** Comparison type. */
    public static final SqlEnum LESS_THAN = SqlEnum.LESS_THAN;

    /** Comparison type. */
    public static final SqlEnum GREATER_EQUAL = SqlEnum.GREATER_EQUAL;

    /** Comparison type. */
    public static final SqlEnum LESS_EQUAL = SqlEnum.LESS_EQUAL;

    /** Comparison type. */
    public static final SqlEnum LIKE = SqlEnum.LIKE;

    /** Comparison type. */
    public static final SqlEnum NOT_LIKE = SqlEnum.NOT_LIKE;

    /** Comparison type. */
    public static final SqlEnum ILIKE = SqlEnum.ILIKE;

    /** Comparison type. */
    public static final SqlEnum NOT_ILIKE = SqlEnum.NOT_ILIKE;

    /** Comparison type. */
    public static final SqlEnum CUSTOM = SqlEnum.CUSTOM;
FileLine
org/apache/torque/dsfactory/PerUserPoolDataSourceFactory.java83
org/apache/torque/dsfactory/SharedPoolDataSourceFactory.java83
        SharedPoolDataSource dataSource = new SharedPoolDataSource();
        Configuration c = Torque.getConfiguration();

        if (c == null || c.isEmpty())
        {
            log.warn("Global Configuration not set,"
                    + " no Default pool data source configured!");
        }
        else
        {
            Configuration conf = c.subset(DEFAULT_POOL_KEY);
            applyConfiguration(conf, dataSource);
        }

        Configuration conf = configuration.subset(POOL_KEY);
        applyConfiguration(conf, dataSource);
        return dataSource;
    }


    /**
     * Closes the pool associated with this factory and releases it.
     * @throws TorqueException if the pool cannot be closed properly
     */
    public void close() throws TorqueException
    {
        try
        {
            ds.close();
        }
        catch (Exception e)
        {
            log.error("Exception caught during close()", e);
            throw new TorqueException(e);
        }
        ds = null;
    }
}
FileLine
org/apache/torque/util/SummaryHelper.java545
org/apache/torque/util/SummaryHelper.java627
        if (!haveFromTable && c.getTopLevelCriterion() != null)
        {
            haveFromTable = true;
            logger.debug("From table defined by a where clause");
        }

        ListOrderedMapCI cMap = getAggregates();
        OrderedMapIterator iMap = cMap.orderedMapIterator();
        while (iMap.hasNext())
        {
            String key = (String) iMap.next();
            SQLFunction f = (SQLFunction) iMap.getValue();
            Column col =  f.getColumn();
            c.addAsColumn(key, new ColumnImpl(
                    null,
                    col.getTableName(),
                    col.getColumnName(),
                    f.getSqlExpression()));
            if (!haveFromTable)    // Last chance. Get it from the func.
            {
                {
                    // Kludgy Where table.col = table.col clause to force
                    // from table identification.
                    c.and(col,