Example usage for java.sql ResultSet relative

List of usage examples for java.sql ResultSet relative

Introduction

In this page you can find the example usage for java.sql ResultSet relative.

Prototype

boolean relative(int rows) throws SQLException;

Source Link

Document

Moves the cursor a relative number of rows, either positive or negative.

Usage

From source file:it.cnr.icar.eric.server.persistence.rdb.RegistryObjectDAO.java

private void getRegistryObjectsIdsFromResultSet(ResultSet rs, int startIndex, int maxResults,
        StringBuffer adhocQuerys, StringBuffer associations, StringBuffer auEvents,
        StringBuffer classifications, StringBuffer schemes, StringBuffer classificationNodes,
        StringBuffer externalIds, StringBuffer externalLinks, StringBuffer extrinsicObjects,
        StringBuffer federations, StringBuffer organizations, StringBuffer registrys, StringBuffer packages,
        StringBuffer serviceBindings, StringBuffer services, StringBuffer specificationLinks,
        StringBuffer subscriptions, StringBuffer users, StringBuffer persons)
        throws SQLException, RegistryException {
    HashSet<String> processed = new HashSet<String>();

    if (startIndex > 0) {
        // calling rs.next() is a workaround for some drivers, such
        // as Derby's, that do not set the cursor during call to
        // rs.relative(...)
        rs.next();/*from w w  w  .  ja v a 2  s.  c om*/
        @SuppressWarnings("unused")
        boolean onRow = rs.relative(startIndex - 1);
    }

    int cnt = 0;
    while (rs.next()) {
        String id = rs.getString("id");

        // Only process if not already processed
        // This avoid OutOfMemoryError when huge number of objects match
        // Currently this happens when name and desc are null and their
        // predicates get pruned but the tablename stays.
        // TODO: Fix query pruning so tableName is pruned if not used.
        if (!(processed.contains(id))) {
            cnt++;
            String type = rs.getString("objectType");
            // System.err.println("id=" + id + " objectType=" + type +
            // " extrinsicObjects=" + extrinsicObjects);

            // log.info(ServerResourceBundle.getInstance().getString("message.objectType=''",
            // new Object[]{type}));
            if (type.equalsIgnoreCase(BindingUtility.CANONICAL_OBJECT_TYPE_ID_AdhocQuery)) {
                if (adhocQuerys.length() == 0) {
                    adhocQuerys.append("'" + id + "'");
                } else {
                    adhocQuerys.append(",'" + id + "'");
                }
            } else if (type.equalsIgnoreCase(BindingUtility.CANONICAL_OBJECT_TYPE_ID_Association)) {
                if (associations.length() == 0) {
                    associations.append("'" + id + "'");
                } else {
                    associations.append(",'" + id + "'");
                }
            } else if (type.equalsIgnoreCase(BindingUtility.CANONICAL_OBJECT_TYPE_ID_AuditableEvent)) {
                if (auEvents.length() == 0) {
                    auEvents.append("'" + id + "'");
                } else {
                    auEvents.append(",'" + id + "'");
                }
            } else if (type.equalsIgnoreCase(BindingUtility.CANONICAL_OBJECT_TYPE_ID_Classification)) {
                if (classifications.length() == 0) {
                    classifications.append("'" + id + "'");
                } else {
                    classifications.append(",'" + id + "'");
                }
            } else if (type.equalsIgnoreCase(BindingUtility.CANONICAL_OBJECT_TYPE_ID_ClassificationNode)) {
                if (classificationNodes.length() == 0) {
                    classificationNodes.append("'" + id + "'");
                } else {
                    classificationNodes.append(",'" + id + "'");
                }
            } else if (type.equalsIgnoreCase(BindingUtility.CANONICAL_OBJECT_TYPE_ID_ClassificationScheme)) {
                if (schemes.length() == 0) {
                    schemes.append("'" + id + "'");
                } else {
                    schemes.append(",'" + id + "'");
                }
            } else if (type.equalsIgnoreCase(BindingUtility.CANONICAL_OBJECT_TYPE_ID_ExternalIdentifier)) {
                if (externalIds.length() == 0) {
                    externalIds.append("'" + id + "'");
                } else {
                    externalIds.append(",'" + id + "'");
                }
            } else if (type.equalsIgnoreCase(BindingUtility.CANONICAL_OBJECT_TYPE_ID_ExternalLink)) {
                if (externalLinks.length() == 0) {
                    externalLinks.append("'" + id + "'");
                } else {
                    externalLinks.append(",'" + id + "'");
                }
            } else if (type.equalsIgnoreCase(BindingUtility.CANONICAL_OBJECT_TYPE_ID_ExtrinsicObject)) {
                if (extrinsicObjects.length() == 0) {
                    extrinsicObjects.append("'" + id + "'");
                } else {
                    extrinsicObjects.append(",'" + id + "'");
                }
            } else if (type.equalsIgnoreCase(BindingUtility.CANONICAL_OBJECT_TYPE_ID_Federation)) {
                if (federations.length() == 0) {
                    federations.append("'" + id + "'");
                } else {
                    federations.append(",'" + id + "'");
                }
            } else if (type.equalsIgnoreCase(BindingUtility.CANONICAL_OBJECT_TYPE_ID_Organization)) {
                if (organizations.length() == 0) {
                    organizations.append("'" + id + "'");
                } else {
                    organizations.append(",'" + id + "'");
                }
            } else if (type.equalsIgnoreCase(BindingUtility.CANONICAL_OBJECT_TYPE_ID_Registry)) {
                if (registrys.length() == 0) {
                    registrys.append("'" + id + "'");
                } else {
                    registrys.append(",'" + id + "'");
                }
            } else if (type.equalsIgnoreCase(BindingUtility.CANONICAL_OBJECT_TYPE_ID_RegistryPackage)) {
                if (packages.length() == 0) {
                    packages.append("'" + id + "'");
                } else {
                    packages.append(",'" + id + "'");
                }
            } else if (type.equalsIgnoreCase(BindingUtility.CANONICAL_OBJECT_TYPE_ID_ServiceBinding)) {
                if (serviceBindings.length() == 0) {
                    serviceBindings.append("'" + id + "'");
                } else {
                    serviceBindings.append(",'" + id + "'");
                }
            } else if (type.equalsIgnoreCase(BindingUtility.CANONICAL_OBJECT_TYPE_ID_Service)) {
                if (services.length() == 0) {
                    services.append("'" + id + "'");
                } else {
                    services.append(",'" + id + "'");
                }
            } else if (type.equalsIgnoreCase(BindingUtility.CANONICAL_OBJECT_TYPE_ID_SpecificationLink)) {
                if (specificationLinks.length() == 0) {
                    specificationLinks.append("'" + id + "'");
                } else {
                    specificationLinks.append(",'" + id + "'");
                }
            } else if (type.equalsIgnoreCase(BindingUtility.CANONICAL_OBJECT_TYPE_ID_Subscription)) {
                if (subscriptions.length() == 0) {
                    subscriptions.append("'" + id + "'");
                } else {
                    subscriptions.append(",'" + id + "'");
                }
            } else if (type.equalsIgnoreCase(BindingUtility.CANONICAL_OBJECT_TYPE_ID_User)) {
                if (users.length() == 0) {
                    users.append("'" + id + "'");
                } else {
                    users.append(",'" + id + "'");
                }
            } else if (type.equalsIgnoreCase(BindingUtility.CANONICAL_OBJECT_TYPE_ID_Person)) {
                if (persons.length() == 0) {
                    persons.append("'" + id + "'");
                } else {
                    persons.append(",'" + id + "'");
                }
            } else {
                // Type is user defined. Table could be either
                // ExtrinsicObject or ExternalLink
                SQLPersistenceManagerImpl pm = SQLPersistenceManagerImpl.getInstance();

                ArrayList<String> queryParams = new ArrayList<String>();
                queryParams.add(id.toUpperCase());
                ExtrinsicObjectType eo = (ExtrinsicObjectType) pm.getRegistryObjectMatchingQuery(context,
                        "SELECT * from ExtrinsicObject where UPPER(id) = ?", queryParams, "ExtrinsicObject");

                if (eo != null) {
                    if (extrinsicObjects.length() == 0) {
                        extrinsicObjects.append("'" + id + "'");
                    } else {
                        extrinsicObjects.append(",'" + id + "'");
                    }
                } else {
                    ExternalLinkType el = (ExternalLinkType) pm.getRegistryObjectMatchingQuery(context,
                            "SELECT * from ExternalLink where UPPER(id) = ?", queryParams, "ExternalLink");

                    if (el != null) {
                        if (externalLinks.length() == 0) {
                            externalLinks.append("'" + id + "'");
                        } else {
                            externalLinks.append(",'" + id + "'");
                        }
                    } else {
                        throw new RegistryException(ServerResourceBundle.getInstance()
                                .getString("message.unknownObjectType", new Object[] { type }));
                    }
                }
            }
            processed.add(id);

            if (cnt == maxResults) {
                break;
            }
        }
    }

    if (cnt > 1000) {
        log.warn(ServerResourceBundle.getInstance().getString("message.WarningExcessiveResultSetSizeQUery",
                new Object[] { new Integer(cnt) }));
    }
}

From source file:it.cnr.icar.eric.server.persistence.rdb.SQLPersistenceManagerImpl.java

/**
 * Executes an SQL Query./*from ww w. ja  va 2 s  . c o m*/
 */
@SuppressWarnings({ "static-access", "unchecked" })
public List<IdentifiableType> executeSQLQuery(ServerRequestContext context, String sqlQuery,
        List<String> queryParams, ResponseOptionType ebResponseOptionType, String tableName, List<?> objectRefs,
        IterativeQueryParams paramHolder) throws RegistryException {
    @SuppressWarnings("rawtypes")
    List ebIdentifiableTypeResultList = null;
    Connection connection = null;
    int startIndex = paramHolder.startIndex;
    int maxResults = paramHolder.maxResults;
    int totalResultCount = -1;
    Statement stmt = null;

    try {
        connection = context.getConnection();

        java.sql.ResultSet rs = null;

        tableName = Utility.getInstance().mapTableName(tableName);

        ReturnType returnType = ebResponseOptionType.getReturnType();
        @SuppressWarnings("unused")
        boolean returnComposedObjects = ebResponseOptionType.isReturnComposedObjects();

        if (maxResults < 0) {
            if (queryParams == null) {
                stmt = connection.createStatement();
            } else {
                stmt = connection.prepareStatement(sqlQuery);
            }
        } else {
            if (queryParams == null) {
                stmt = connection.createStatement(java.sql.ResultSet.TYPE_SCROLL_INSENSITIVE,
                        java.sql.ResultSet.CONCUR_READ_ONLY);
            } else {
                stmt = connection.prepareStatement(sqlQuery, java.sql.ResultSet.TYPE_SCROLL_INSENSITIVE,
                        java.sql.ResultSet.CONCUR_READ_ONLY);
            }
        }

        if (log.isDebugEnabled()) {
            log.debug("Executing query: '" + sqlQuery + "'");
            if (dumpStackOnQuery) {
                Thread.currentThread().dumpStack();
            }
        }

        if (queryParams == null) {
            rs = stmt.executeQuery(sqlQuery);
        } else {
            Iterator<String> iter = queryParams.iterator();
            int paramCount = 0;
            while (iter.hasNext()) {
                Object param = iter.next();
                ((PreparedStatement) stmt).setObject(++paramCount, param);
            }
            rs = ((PreparedStatement) stmt).executeQuery();
        }
        if (maxResults >= 0) {
            rs.last();
            totalResultCount = rs.getRow();
            // Reset back to before first row so that DAO can correctly
            // scroll
            // through the result set
            rs.beforeFirst();
        }
        @SuppressWarnings("unused")
        Iterator<?> iter = null;

        log.debug("::3:: SQL result ReturnType" + returnType.toString());

        if (returnType == ReturnType.OBJECT_REF) {

            ebIdentifiableTypeResultList = new ArrayList<Object>();

            if (startIndex > 0) {
                rs.last();
                totalResultCount = rs.getRow();
                rs.beforeFirst();
                // calling rs.next() is a workaround for some drivers, such
                // as Derby's, that do not set the cursor during call to
                // rs.relative(...)
                rs.next();
                @SuppressWarnings("unused")
                boolean onRow = rs.relative(startIndex - 1);
            }

            int cnt = 0;
            while (rs.next()) {

                ObjectRefType ebObjectRefType = bu.rimFac.createObjectRefType();
                // TODO: JAXBElement

                String id = rs.getString(1);
                ebObjectRefType.setId(id);
                ebIdentifiableTypeResultList.add(ebObjectRefType);

                if (++cnt == maxResults) {
                    break;
                }
            }
        } else if (returnType == ReturnType.REGISTRY_OBJECT) {
            context.setResponseOption(ebResponseOptionType);
            RegistryObjectDAO roDAO = new RegistryObjectDAO(context);
            ebIdentifiableTypeResultList = roDAO.getObjects(rs, startIndex, maxResults);

        } else if ((returnType == ReturnType.LEAF_CLASS)
                || (returnType == ReturnType.LEAF_CLASS_WITH_REPOSITORY_ITEM)) {
            ebIdentifiableTypeResultList = getObjects(context, connection, rs, tableName, ebResponseOptionType,
                    objectRefs, startIndex, maxResults);

        } else {
            throw new RegistryException(ServerResourceBundle.getInstance()
                    .getString("message.invalidReturnType", new Object[] { returnType }));
        }

    } catch (SQLException e) {
        throw new RegistryException(e);
    } finally {
        try {
            if (stmt != null) {
                stmt.close();
            }
        } catch (SQLException sqle) {
            log.error(ServerResourceBundle.getInstance().getString("message.CaughtException1"), sqle);
        }
    }

    paramHolder.totalResultCount = totalResultCount;

    return ebIdentifiableTypeResultList;
}

From source file:com.github.woonsan.jdbc.jcr.impl.JcrJdbcResultSetTest.java

@Test
public void testUnsupportedOperations() throws Exception {
    Statement statement = getConnection().createStatement();
    ResultSet rs = statement.executeQuery(SQL_EMPS);

    try {//from ww  w  .  j ava2 s  . com
        rs.getWarnings();
        fail();
    } catch (UnsupportedOperationException ignore) {
    }

    try {
        rs.clearWarnings();
        fail();
    } catch (UnsupportedOperationException ignore) {
    }

    try {
        rs.getCursorName();
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.getObject(1);
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.getObject("ename");
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.isLast();
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.beforeFirst();
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.afterLast();
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.first();
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.last();
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.absolute(1);
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.relative(1);
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.previous();
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.moveToCurrentRow();
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.updateNull(1);
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.updateNull("col1");
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.updateBoolean(1, true);
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.updateBoolean("col1", true);
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.updateByte(1, (byte) 0);
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.updateByte("col1", (byte) 0);
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.updateShort(1, (short) 0);
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.updateShort("col1", (short) 0);
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.updateInt(1, 0);
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.updateInt("col1", 0);
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.updateLong(1, (long) 0);
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.updateLong("col1", (long) 0);
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.updateFloat(1, (float) 0.1);
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.updateFloat("col1", (float) 0.1);
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.updateDouble(1, 0.1);
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.updateDouble("col1", 0.1);
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.updateBigDecimal(1, new BigDecimal("100000000"));
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.updateBigDecimal("col1", new BigDecimal("100000000"));
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.updateString(1, "Unknown");
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.updateString("col1", "Unknown");
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.updateBytes(1, null);
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.updateBytes("col1", null);
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.updateDate(1, null);
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.updateDate("col1", null);
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.updateTime(1, null);
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.updateTime("col1", null);
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.updateTimestamp(1, null);
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.updateTimestamp("col1", null);
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.updateAsciiStream(1, null, 0);
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.updateAsciiStream(1, null, (long) 0);
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.updateAsciiStream("col1", null, 0);
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.updateAsciiStream("col1", null, (long) 0);
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.updateAsciiStream(1, null);
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.updateAsciiStream("col1", null);
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.updateBinaryStream(1, null, 0);
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.updateBinaryStream(1, null, (long) 0);
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.updateBinaryStream("col1", null, 0);
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.updateBinaryStream("col1", null, (long) 0);
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.updateBinaryStream(1, null);
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.updateBinaryStream("col1", null);
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.updateCharacterStream(1, null, 0);
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.updateCharacterStream(1, null, (long) 0);
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.updateCharacterStream("col1", null, 0);
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.updateCharacterStream("col1", null, (long) 0);
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.updateCharacterStream(1, null);
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.updateCharacterStream("col1", null);
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.updateObject(1, null, 1);
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.updateObject("col1", null, 1);
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.updateObject(1, null);
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.updateObject("col1", null);
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.insertRow();
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.updateRow();
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.deleteRow();
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.refreshRow();
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.cancelRowUpdates();
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.moveToInsertRow();
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.getObject(1, (Map<String, Class<?>>) null);
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.getObject("col1", (Map<String, Class<?>>) null);
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.getRef(1);
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.getRef("col1");
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.getBlob(1);
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.getBlob("col1");
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.getClob(1);
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.getClob("col1");
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.getURL(1);
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.getURL("col1");
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.updateRef(1, null);
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.updateRef("col1", null);
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.updateBlob(1, (Blob) null);
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.updateBlob("col1", (Blob) null);
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.updateClob(1, (Clob) null);
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.updateClob("col1", (Clob) null);
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.updateArray(1, (Array) null);
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.updateArray("col1", (Array) null);
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.getRowId(1);
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.getRowId("col1");
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.updateRowId(1, null);
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.updateRowId("col1", null);
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.updateNString(1, null);
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.updateNString("col1", null);
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.updateNClob(1, (NClob) null);
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.updateNClob("col1", (NClob) null);
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.getNClob(1);
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.getNClob("col1");
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.getSQLXML(1);
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.getSQLXML("col1");
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.updateSQLXML(1, null);
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.updateSQLXML("col1", null);
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.getNString(1);
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.getNString("col1");
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.getNCharacterStream(1);
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.getNCharacterStream("col1");
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.updateNCharacterStream(1, null, 0);
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.updateNCharacterStream(1, null, (long) 0);
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.updateNCharacterStream("col1", null, 0);
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.updateNCharacterStream("col1", null, (long) 0);
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.updateAsciiStream(1, null, 0);
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.updateAsciiStream(1, null, (long) 0);
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.updateAsciiStream("col1", null, 0);
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.updateAsciiStream("col1", null, (long) 0);
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.updateBinaryStream(1, null, 0);
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.updateBinaryStream(1, null, (long) 0);
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.updateBinaryStream("col1", null, 0);
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.updateBinaryStream("col1", null, (long) 0);
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.updateCharacterStream(1, null, 0);
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.updateCharacterStream(1, null, (long) 0);
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.updateCharacterStream("col1", null, 0);
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.updateCharacterStream("col1", null, (long) 0);
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.updateBlob(1, null, 0);
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.updateBlob("col1", null, 0);
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.updateClob(1, null, 0);
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.updateClob("col1", null, 0);
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.updateNClob(1, null, 0);
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.updateNClob("col1", null, 0);
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.updateNCharacterStream(1, null);
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.updateNCharacterStream("col1", null);
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.updateAsciiStream(1, null);
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.updateAsciiStream("col1", null);
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.updateBinaryStream(1, null);
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.updateBinaryStream("col1", null);
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.updateCharacterStream(1, null);
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.updateCharacterStream("col1", null);
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.updateBlob(1, (InputStream) null);
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.updateBlob("col1", (InputStream) null);
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.updateClob(1, (Reader) null);
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.updateClob("col1", (Reader) null);
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.updateNClob(1, (Reader) null);
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.updateNClob("col1", (Reader) null);
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.getObject(1, (Class<?>) null);
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    try {
        rs.getObject("col1", (Class<?>) null);
        fail();
    } catch (SQLFeatureNotSupportedException ignore) {
    }

    rs.close();
    assertTrue(rs.isClosed());

    statement.close();
    assertTrue(statement.isClosed());
}

From source file:org.freebxml.omar.server.persistence.rdb.AbstractDAO.java

/**
 * Gets a List of binding objects from specified ResultSet.
 *//*from  w w  w .  j a  v  a2 s.  c  om*/
public List getObjects(ResultSet rs, int startIndex, int maxResults) throws RegistryException {
    List res = new java.util.ArrayList();

    try {
        if (startIndex > 0) {
            // calling rs.next() is a workaround for some drivers, such
            // as Derby's, that do not set the cursor during call to 
            // rs.relative(...)
            rs.next();
            boolean onRow = rs.relative(startIndex - 1);
        }

        int cnt = 0;
        while (rs.next()) {
            Object obj = createObject();
            loadObject(obj, rs);
            res.add(obj);

            if (++cnt == maxResults) {
                break;
            }
        }
    } catch (SQLException e) {
        log.error(ServerResourceBundle.getInstance().getString("message.CaughtException1"), e);
        throw new RegistryException(e);
    } catch (JAXBException j) {
        log.error(ServerResourceBundle.getInstance().getString("message.CaughtException1"), j);
        throw new RegistryException(j);
    }

    return res;
}

From source file:org.freebxml.omar.server.persistence.rdb.RegistryObjectDAO.java

private void getRegistryObjectsIdsFromResultSet(ResultSet rs, int startIndex, int maxResults,
        StringBuffer adhocQuerys, StringBuffer associations, StringBuffer auEvents,
        StringBuffer classifications, StringBuffer schemes, StringBuffer classificationNodes,
        StringBuffer externalIds, StringBuffer externalLinks, StringBuffer extrinsicObjects,
        StringBuffer federations, StringBuffer organizations, StringBuffer registrys, StringBuffer packages,
        StringBuffer serviceBindings, StringBuffer services, StringBuffer specificationLinks,
        StringBuffer subscriptions, StringBuffer users, StringBuffer persons)
        throws SQLException, RegistryException {
    HashSet processed = new HashSet();

    if (startIndex > 0) {
        // calling rs.next() is a workaround for some drivers, such
        // as Derby's, that do not set the cursor during call to 
        // rs.relative(...)
        rs.next();//from www .j a v  a  2 s.  c o m
        boolean onRow = rs.relative(startIndex - 1);
    }

    int cnt = 0;
    while (rs.next()) {
        String id = rs.getString("id");

        //Only process if not already processed
        //This avoid OutOfMemoryError when huge number of objects match
        //Currently this happens when name and desc are null and their
        //predicates get pruned but the tablename stays.
        //TODO: Fix query pruning so tableName is pruned if not used.
        if (!(processed.contains(id))) {
            cnt++;
            String type = rs.getString("objectType");
            //System.err.println("id=" + id + " objectType=" + type + " extrinsicObjects=" + extrinsicObjects);

            //log.info(ServerResourceBundle.getInstance().getString("message.objectType=''", new Object[]{type}));
            if (type.equalsIgnoreCase(BindingUtility.CANONICAL_OBJECT_TYPE_ID_AdhocQuery)) {
                if (adhocQuerys.length() == 0) {
                    adhocQuerys.append("'" + id + "'");
                } else {
                    adhocQuerys.append(",'" + id + "'");
                }
            } else if (type.equalsIgnoreCase(BindingUtility.CANONICAL_OBJECT_TYPE_ID_Association)) {
                if (associations.length() == 0) {
                    associations.append("'" + id + "'");
                } else {
                    associations.append(",'" + id + "'");
                }
            } else if (type.equalsIgnoreCase(BindingUtility.CANONICAL_OBJECT_TYPE_ID_AuditableEvent)) {
                if (auEvents.length() == 0) {
                    auEvents.append("'" + id + "'");
                } else {
                    auEvents.append(",'" + id + "'");
                }
            } else if (type.equalsIgnoreCase(BindingUtility.CANONICAL_OBJECT_TYPE_ID_Classification)) {
                if (classifications.length() == 0) {
                    classifications.append("'" + id + "'");
                } else {
                    classifications.append(",'" + id + "'");
                }
            } else if (type.equalsIgnoreCase(BindingUtility.CANONICAL_OBJECT_TYPE_ID_ClassificationNode)) {
                if (classificationNodes.length() == 0) {
                    classificationNodes.append("'" + id + "'");
                } else {
                    classificationNodes.append(",'" + id + "'");
                }
            } else if (type.equalsIgnoreCase(BindingUtility.CANONICAL_OBJECT_TYPE_ID_ClassificationScheme)) {
                if (schemes.length() == 0) {
                    schemes.append("'" + id + "'");
                } else {
                    schemes.append(",'" + id + "'");
                }
            } else if (type.equalsIgnoreCase(BindingUtility.CANONICAL_OBJECT_TYPE_ID_ExternalIdentifier)) {
                if (externalIds.length() == 0) {
                    externalIds.append("'" + id + "'");
                } else {
                    externalIds.append(",'" + id + "'");
                }
            } else if (type.equalsIgnoreCase(BindingUtility.CANONICAL_OBJECT_TYPE_ID_ExternalLink)) {
                if (externalLinks.length() == 0) {
                    externalLinks.append("'" + id + "'");
                } else {
                    externalLinks.append(",'" + id + "'");
                }
            } else if (type.equalsIgnoreCase(BindingUtility.CANONICAL_OBJECT_TYPE_ID_ExtrinsicObject)) {
                if (extrinsicObjects.length() == 0) {
                    extrinsicObjects.append("'" + id + "'");
                } else {
                    extrinsicObjects.append(",'" + id + "'");
                }
            } else if (type.equalsIgnoreCase(BindingUtility.CANONICAL_OBJECT_TYPE_ID_Federation)) {
                if (federations.length() == 0) {
                    federations.append("'" + id + "'");
                } else {
                    federations.append(",'" + id + "'");
                }
            } else if (type.equalsIgnoreCase(BindingUtility.CANONICAL_OBJECT_TYPE_ID_Organization)) {
                if (organizations.length() == 0) {
                    organizations.append("'" + id + "'");
                } else {
                    organizations.append(",'" + id + "'");
                }
            } else if (type.equalsIgnoreCase(BindingUtility.CANONICAL_OBJECT_TYPE_ID_Registry)) {
                if (registrys.length() == 0) {
                    registrys.append("'" + id + "'");
                } else {
                    registrys.append(",'" + id + "'");
                }
            } else if (type.equalsIgnoreCase(BindingUtility.CANONICAL_OBJECT_TYPE_ID_RegistryPackage)) {
                if (packages.length() == 0) {
                    packages.append("'" + id + "'");
                } else {
                    packages.append(",'" + id + "'");
                }
            } else if (type.equalsIgnoreCase(BindingUtility.CANONICAL_OBJECT_TYPE_ID_ServiceBinding)) {
                if (serviceBindings.length() == 0) {
                    serviceBindings.append("'" + id + "'");
                } else {
                    serviceBindings.append(",'" + id + "'");
                }
            } else if (type.equalsIgnoreCase(BindingUtility.CANONICAL_OBJECT_TYPE_ID_Service)) {
                if (services.length() == 0) {
                    services.append("'" + id + "'");
                } else {
                    services.append(",'" + id + "'");
                }
            } else if (type.equalsIgnoreCase(BindingUtility.CANONICAL_OBJECT_TYPE_ID_SpecificationLink)) {
                if (specificationLinks.length() == 0) {
                    specificationLinks.append("'" + id + "'");
                } else {
                    specificationLinks.append(",'" + id + "'");
                }
            } else if (type.equalsIgnoreCase(BindingUtility.CANONICAL_OBJECT_TYPE_ID_Subscription)) {
                if (subscriptions.length() == 0) {
                    subscriptions.append("'" + id + "'");
                } else {
                    subscriptions.append(",'" + id + "'");
                }
            } else if (type.equalsIgnoreCase(BindingUtility.CANONICAL_OBJECT_TYPE_ID_User)) {
                if (users.length() == 0) {
                    users.append("'" + id + "'");
                } else {
                    users.append(",'" + id + "'");
                }
            } else if (type.equalsIgnoreCase(BindingUtility.CANONICAL_OBJECT_TYPE_ID_Person)) {
                if (persons.length() == 0) {
                    persons.append("'" + id + "'");
                } else {
                    persons.append(",'" + id + "'");
                }
            } else {
                //Type is user defined. Table could be either ExtrinsicObject or ExternalLink
                SQLPersistenceManagerImpl pm = SQLPersistenceManagerImpl.getInstance();

                ArrayList queryParams = new ArrayList();

                // COMMENT 1:
                // HIEOS/AMS: Commented the following two lines of code. No need to convert 'id' to upper case
                // and subsequently compare using SQL's UPPER function (Using this prevents
                /// evaluation of indices on 'id').
                // queryParams.add(id.toUpperCase());
                // ExtrinsicObjectType eo = (ExtrinsicObjectType) pm.getRegistryObjectMatchingQuery(context, "SELECT * from ExtrinsicObject where UPPER(id) = ?", queryParams, "ExtrinsicObject");
                queryParams.add(id);
                ExtrinsicObjectType eo = (ExtrinsicObjectType) pm.getRegistryObjectMatchingQuery(context,
                        "SELECT * from ExtrinsicObject where id = ?", queryParams, "ExtrinsicObject");

                if (eo != null) {
                    if (extrinsicObjects.length() == 0) {
                        extrinsicObjects.append("'" + id + "'");
                    } else {
                        extrinsicObjects.append(",'" + id + "'");
                    }
                } else {
                    // HIEOS/AMS: See COMMENT 1.
                    // ExternalLinkType el = (ExternalLinkType) pm.getRegistryObjectMatchingQuery(context, "SELECT * from ExternalLink where UPPER(id) = ?", queryParams, "ExternalLink");
                    ExternalLinkType el = (ExternalLinkType) pm.getRegistryObjectMatchingQuery(context,
                            "SELECT * from ExternalLink where id = ?", queryParams, "ExternalLink");

                    if (el != null) {
                        if (externalLinks.length() == 0) {
                            externalLinks.append("'" + id + "'");
                        } else {
                            externalLinks.append(",'" + id + "'");
                        }
                    } else {
                        throw new RegistryException(ServerResourceBundle.getInstance()
                                .getString("message.unknownObjectType", new Object[] { type }));
                    }
                }
            }
            processed.add(id);

            if (cnt == maxResults) {
                break;
            }
        }
    }

    if (cnt > 1000) {
        log.warn(ServerResourceBundle.getInstance().getString("message.WarningExcessiveResultSetSizeQUery",
                new Object[] { new Integer(cnt) }));
    }
}

From source file:org.freebxml.omar.server.persistence.rdb.SQLPersistenceManagerImpl.java

/**
 * Executes an SQL Query.//  www . j  a  va2  s. c  o m
 */
public List executeSQLQuery(ServerRequestContext context, String sqlQuery, List queryParams,
        ResponseOptionType responseOption, String tableName, List objectRefs, IterativeQueryParams paramHolder)
        throws RegistryException {
    List res = null;
    Connection connection = null;
    int startIndex = paramHolder.startIndex;
    int maxResults = paramHolder.maxResults;
    int totalResultCount = -1;
    Statement stmt = null;

    try {
        connection = context.getConnection();

        java.sql.ResultSet rs = null;

        tableName = org.freebxml.omar.common.Utility.getInstance().mapTableName(tableName);

        ReturnType returnType = responseOption.getReturnType();
        boolean returnComposedObjects = responseOption.isReturnComposedObjects();

        if (maxResults < 0) {
            if (queryParams == null) {
                stmt = connection.createStatement();
            } else {
                stmt = connection.prepareStatement(sqlQuery);
            }
        } else {
            if (queryParams == null) {
                stmt = connection.createStatement(java.sql.ResultSet.TYPE_SCROLL_INSENSITIVE,
                        java.sql.ResultSet.CONCUR_READ_ONLY);
            } else {
                stmt = connection.prepareStatement(sqlQuery, java.sql.ResultSet.TYPE_SCROLL_INSENSITIVE,
                        java.sql.ResultSet.CONCUR_READ_ONLY);
            }
        }

        if (log.isDebugEnabled()) {
            log.debug("Executing query: '" + sqlQuery + "'");
            if (dumpStackOnQuery) {
                Thread.currentThread().dumpStack();
            }
        }
        log.trace("SQL = " + sqlQuery); // HIEOS/BHT: (DEBUG)

        if (queryParams == null) {

            rs = stmt.executeQuery(sqlQuery);
        } else {
            Iterator iter = queryParams.iterator();
            int paramCount = 0;
            while (iter.hasNext()) {
                Object param = iter.next();
                ((PreparedStatement) stmt).setObject(++paramCount, param);
                // HIEOS/BHT (DEBUG):
                log.trace("  -> param(" + new Integer(paramCount).toString() + "): " + (String) param);
            }
            rs = ((PreparedStatement) stmt).executeQuery();
        }
        if (maxResults >= 0) {
            rs.last();
            totalResultCount = rs.getRow();
            // Reset back to before first row so that DAO can correctly scroll
            // through the result set
            rs.beforeFirst();
        }
        java.util.Iterator iter = null;

        if (returnType == ReturnType.OBJECT_REF) {
            res = new java.util.ArrayList();

            if (startIndex > 0) {
                rs.last();
                totalResultCount = rs.getRow();
                rs.beforeFirst();
                // calling rs.next() is a workaround for some drivers, such
                // as Derby's, that do not set the cursor during call to 
                // rs.relative(...)
                rs.next();
                boolean onRow = rs.relative(startIndex - 1);
                // HIEOS/BHT (DEBUG):
                log.trace(" -> Total Result Count: " + totalResultCount);
            }

            int cnt = 0;
            while (rs.next()) {
                org.oasis.ebxml.registry.bindings.rim.ObjectRef or = bu.rimFac.createObjectRef();
                String id = rs.getString(1);
                or.setId(id);
                res.add(or);

                if (++cnt == maxResults) {
                    break;
                }
            }
            // HIEOS/BHT (DEBUG):
            log.trace(" -> cnt: " + totalResultCount);
        } else if (returnType == ReturnType.REGISTRY_OBJECT) {
            context.setResponseOption(responseOption);
            RegistryObjectDAO roDAO = new RegistryObjectDAO(context);
            res = roDAO.getObjects(rs, startIndex, maxResults);
            // HIEOS/BHT (DEBUG):
            log.trace(" -> Object Size: " + res.size());
        } else if ((returnType == ReturnType.LEAF_CLASS)
                || (returnType == ReturnType.LEAF_CLASS_WITH_REPOSITORY_ITEM)) {
            res = getObjects(context, connection, rs, tableName, responseOption, objectRefs, startIndex,
                    maxResults);
            // HIEOS/BHT (DEBUG):
            log.trace(" -> Object Size: " + res.size());
        } else {
            throw new RegistryException(ServerResourceBundle.getInstance()
                    .getString("message.invalidReturnType", new Object[] { returnType }));
        }

    } catch (SQLException e) {
        throw new RegistryException(e);
    } catch (javax.xml.bind.JAXBException e) {
        throw new RegistryException(e);
    } finally {
        try {
            if (stmt != null) {
                stmt.close();
            }
        } catch (SQLException sqle) {
            log.error(ServerResourceBundle.getInstance().getString("message.CaughtException1"), sqle);
        }
    }

    paramHolder.totalResultCount = totalResultCount;

    return res;
}

From source file:org.pentaho.di.core.database.Database.java

public boolean relative(ResultSet rs, int rows) throws KettleDatabaseException {
    try {/* w  ww  . j  a va  2 s.  c o m*/
        return rs.relative(rows);
    } catch (SQLException e) {
        throw new KettleDatabaseException("Unable to move the resultset forward " + rows + " rows", e);
    }
}

From source file:org.wso2.carbon.registry.core.jdbc.dao.JDBCCommentsVersionDAO.java

/**
 * Method to get comments added to a given resource.
 *
 * @param resource the resource./*  ww  w . j av  a 2 s .  c o  m*/
 *
 * @return an array of comments.
 * @throws RegistryException if an error occurs while getting comments.
 */
public Comment[] getComments(ResourceImpl resource) throws RegistryException {

    JDBCDatabaseTransaction.ManagedRegistryConnection conn = JDBCDatabaseTransaction.getConnection();
    try {
        String dbName = conn.getMetaData().getDatabaseProductName();
        if (dbName.contains("Microsoft") || dbName.equals("Oracle")) {
            enableApiPagination = "false";
        }
    } catch (SQLException e) {
        throw new RegistryException("Failed to get Database product name ", e);
    }

    List<Comment> commentList = new ArrayList<Comment>();
    PreparedStatement s = null;
    ResultSet results = null;
    String path = resource.getPath();

    boolean paginated = false;
    int start = 0;
    int count = 0;
    String sortOrder = "";
    String sortBy = "";
    MessageContext messageContext = null;
    //   enableApiPagination is the value of system property - enable.registry.api.paginating
    if (enableApiPagination == null || enableApiPagination.equals("true")) {
        messageContext = MessageContext.getCurrentMessageContext();
        if (messageContext != null && PaginationUtils.isPaginationHeadersExist(messageContext)) {

            PaginationContext paginationContext = PaginationUtils.initPaginationContext(messageContext);
            start = paginationContext.getStart();
            if (start == 0) {
                start = 1;
            }
            count = paginationContext.getCount();
            sortBy = paginationContext.getSortBy();
            sortOrder = paginationContext.getSortOrder();
            paginated = true;

        }
    }
    try {
        String sql = "SELECT C.REG_ID, C.REG_COMMENT_TEXT, C.REG_USER_ID, C.REG_COMMENTED_TIME "
                + "FROM REG_COMMENT C, REG_RESOURCE_COMMENT RC "
                + "WHERE C.REG_ID=RC.REG_COMMENT_ID AND RC.REG_VERSION = ? "
                + "AND C.REG_TENANT_ID=? AND RC.REG_TENANT_ID=?";

        if (paginated) {
            if (!"".equals(sortBy) && !"".equals(sortOrder)) {
                sql = sql + " ORDER BY " + sortBy + " " + sortOrder;

            }
        }
        if (enableApiPagination == null || enableApiPagination.equals("true")) {
            // TYPE_SCROLL_INSENSITIVE and CONCUR_UPDATABLE should be set to move the cursor through the resultSet
            s = conn.prepareStatement(sql, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
        } else {
            s = conn.prepareStatement(sql);
        }
        s.setLong(1, resource.getVersionNumber());
        s.setInt(2, CurrentSession.getTenantId());
        s.setInt(3, CurrentSession.getTenantId());

        results = s.executeQuery();

        if (paginated) {
            //Check start index is a valid one
            if (results.relative(start)) {
                //This is to get cursor to correct position to execute results.next().
                results.previous();
                int i = 0;
                while (results.next() && i < count) {
                    i++;
                    commentList.add(getComment(results, path));
                }
            } else {
                log.debug("start index doesn't exist in the result set");
            }
            //move the cursor to the last index
            if (results.last()) {
                log.debug("cursor move to the last index of result set");
            } else {
                log.debug("cursor doesn't move to the last index of result set");
            }
            //set row count to the message context.
            PaginationUtils.setRowCount(messageContext, Integer.toString(results.getRow()));

        } else {
            while (results.next()) {
                commentList.add(getComment(results, path));
            }
        }

    } catch (SQLException e) {

        String msg = "Failed to get comments on resource " + path + ". " + e.getMessage();
        log.error(msg, e);
        throw new RegistryException(msg, e);
    } finally {
        try {
            try {
                if (results != null) {
                    results.close();
                }
            } finally {
                if (s != null) {
                    s.close();
                }
            }
        } catch (SQLException ex) {
            String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR;
            log.error(msg, ex);
        }
    }

    return commentList.toArray(new Comment[commentList.size()]);
}

From source file:org.wso2.carbon.registry.core.jdbc.dao.JDBCLogsDAO.java

private List<LogEntry> internalGetLogs(boolean paginate, String resourcePath, int action, String userName,
        Date from, Date to, boolean descending, Connection conn) throws RegistryException {
    try {/*from  ww w  .  j  a  v  a 2  s  .  c  o m*/
        String dbName = conn.getMetaData().getDatabaseProductName();
        if (dbName.contains("Microsoft") || dbName.equals("Oracle")) {
            enableApiPagination = "false";
        }
    } catch (SQLException e) {
        throw new RegistryException("Failed to get Database product name ", e);
    }

    if (conn == null) {
        log.fatal(
                "Failed to get Logs. Communications link failure. The connection to the database could not be acquired.");
        throw new RegistryException(
                "Failed to get Logs. Communications link failure. The connection to the database could not be acquired.");
    }

    PreparedStatement s = null;
    ResultSet results = null;

    boolean paginated = false;
    int start = 0;
    int count = 0;
    String sortOrder = "";
    String sortBy = "";
    MessageContext messageContext = null;
    //   enableApiPagination is the value of system property - enable.registry.api.paginating
    if (enableApiPagination == null || enableApiPagination.equals("true")) {
        messageContext = MessageContext.getCurrentMessageContext();
        if (messageContext != null && PaginationUtils.isPaginationHeadersExist(messageContext)) {

            PaginationContext paginationContext = PaginationUtils.initPaginationContext(messageContext);
            start = paginationContext.getStart();
            count = paginationContext.getCount();
            if (start == 0) {
                start = 1;
            }
            sortBy = paginationContext.getSortBy();
            sortOrder = paginationContext.getSortOrder();
            paginated = paginate;
        }
    }
    String sql = "SELECT REG_PATH, REG_USER_ID, REG_LOGGED_TIME, REG_ACTION, REG_ACTION_DATA FROM " + "REG_LOG";

    boolean queryStarted = false;
    sql = addWherePart(resourcePath, queryStarted, sql, userName, from, to, action);

    if (descending) {
        sql = sql + " ORDER BY REG_LOGGED_TIME DESC";
    }
    try {
        if (enableApiPagination == null || enableApiPagination.equals("true")) {
            // TYPE_SCROLL_INSENSITIVE and CONCUR_UPDATABLE should be set to move the cursor through the resultSet
            s = conn.prepareStatement(sql, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
        } else {
            s = conn.prepareStatement(sql);
        }
        int paramNumber = 1;

        if (resourcePath != null) {
            s.setString(paramNumber, resourcePath);
            paramNumber++;
        }

        if (userName != null) {
            s.setString(paramNumber, userName);
            paramNumber++;
        }

        if (from != null) {
            s.setTimestamp(paramNumber, new Timestamp(from.getTime()));
            paramNumber++;
        }

        if (to != null) {
            s.setTimestamp(paramNumber, new Timestamp(to.getTime()));
            paramNumber++;
        }

        if (action != -1) {
            s.setInt(paramNumber, action);
            paramNumber++;
        }
        s.setInt(paramNumber, CurrentSession.getTenantId());

        results = s.executeQuery();

        List<LogEntry> resultList = new ArrayList<LogEntry>();
        if (paginated) {
            //Check start index is a valid one
            if (results.relative(start)) {
                //This is to get cursor to correct position to execute results.next().
                results.previous();
                int i = 0;
                while (results.next() && i < count) {
                    i++;
                    resultList.add(getLogEntry(results));
                }
            } else {
                log.debug("start index doesn't exist in the result set");
            }
            //move the cursor to the last index
            if (results.last()) {
                log.debug("cursor move to the last index of result set");
            } else {
                log.debug("cursor doesn't move to the last index of result set");
            }
            //set row count to the message context.
            PaginationUtils.setRowCount(messageContext, Integer.toString(results.getRow()));

        } else {
            while (results.next()) {
                resultList.add(getLogEntry(results));
            }
            LogEntry[] logEntries = resultList.toArray(new LogEntry[resultList.size()]);
            resultList = Arrays.asList(logEntries);
        }
        return resultList;

    } catch (SQLException e) {

        String msg = "Failed to get logs. " + e.getMessage();
        log.error(msg, e);
        throw new RegistryException(msg, e);
    } finally {
        try {
            try {
                if (results != null) {
                    results.close();
                }
            } finally {
                if (s != null) {
                    s.close();
                }
            }
        } catch (SQLException ex) {
            String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR;
            log.error(msg, ex);
        }
    }
}

From source file:org.wso2.carbon.registry.core.jdbc.dao.JDBCTagsVersionDAO.java

/**
 * Method to get tags added to the given resource, along with the count.
 *
 * @param resourceImpl the resource.//w w w  .j a v a 2s  .  com
 *
 * @return an array of tags (with counts).
 * @throws RegistryException if an error occurred while getting tags.
 */
public Tag[] getTagsWithCount(ResourceImpl resourceImpl) throws RegistryException {

    JDBCDatabaseTransaction.ManagedRegistryConnection conn = JDBCDatabaseTransaction.getConnection();

    try {
        String dbName = conn.getMetaData().getDatabaseProductName();
        if (dbName.contains("Microsoft") || dbName.equals("Oracle")) {
            enableApiPagination = "false";
        }
    } catch (SQLException e) {
        throw new RegistryException("Failed to get Database product name ", e);
    }

    List<Tag> tagList = new ArrayList<Tag>();
    ResultSet result = null;
    PreparedStatement ps = null;

    boolean paginated = false;
    int start = 0;
    int count = 0;
    String sortOrder = "";
    String sortBy = "";
    MessageContext messageContext = null;
    //   enableApiPagination is the value of system property - enable.registry.api.paginating
    if (enableApiPagination == null || enableApiPagination.equals("true")) {
        messageContext = MessageContext.getCurrentMessageContext();
        if (messageContext != null && PaginationUtils.isPaginationHeadersExist(messageContext)) {

            PaginationContext paginationContext = PaginationUtils.initPaginationContext(messageContext);
            start = paginationContext.getStart();
            if (start == 0) {
                start = 1;
            }
            count = paginationContext.getCount();
            sortBy = paginationContext.getSortBy();
            sortOrder = paginationContext.getSortOrder();
            paginated = true;
        }
    }
    try {
        String sql = "SELECT T.REG_TAG_NAME, COUNT(T.REG_ID) FROM REG_TAG T, REG_RESOURCE_TAG RT "
                + "WHERE RT.REG_VERSION=? AND T.REG_ID=RT.REG_TAG_ID AND "
                + "T.REG_TENANT_ID=? AND RT.REG_TENANT_ID=? " + "GROUP BY T.REG_TAG_NAME";

        if (paginated) {
            if (!"".equals(sortBy) && !"".equals(sortOrder)) {
                sql = sql + " ORDER BY " + sortBy + " " + sortOrder;

            }
        }
        if (enableApiPagination == null || enableApiPagination.equals("true")) {
            // TYPE_SCROLL_INSENSITIVE and CONCUR_UPDATABLE should be set to move the cursor through the resultSet
            ps = conn.prepareStatement(sql, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
        } else {
            ps = conn.prepareStatement(sql);
        }
        ps.setLong(1, resourceImpl.getVersionNumber());
        ps.setInt(2, CurrentSession.getTenantId());
        ps.setInt(3, CurrentSession.getTenantId());

        result = ps.executeQuery();
        if (paginated) {
            //Check start index is a valid one
            if (result.relative(start)) {
                //This is to get cursor to correct position to execute results.next().
                result.previous();
                int i = 0;
                while (result.next() && i < count) {
                    i++;
                    tagList.add(getTag(result));
                }
            } else {
                log.debug("start index doesn't exist in the result set");
            }
            //move the cursor to the last index
            if (result.last()) {
                log.debug("cursor move to the last index of result set");
            } else {
                log.debug("cursor doesn't move to the last index of result set");
            }
            //set row count to the message context.
            PaginationUtils.setRowCount(messageContext, Integer.toString(result.getRow()));
        } else {
            while (result.next()) {
                tagList.add(getTag(result));
            }
        }

    } catch (SQLException e) {

        String msg = "Failed to get tags and tag counts of the resource " + resourceImpl.getPath() + ". "
                + e.getMessage();
        log.error(msg, e);
        throw new RegistryException(msg, e);
    } finally {
        try {
            try {
                if (result != null) {
                    result.close();
                }
            } finally {
                if (ps != null) {
                    ps.close();
                }
            }
        } catch (SQLException ex) {
            String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR;
            log.error(msg, ex);
        }
    }

    return tagList.toArray(new Tag[tagList.size()]);
}