Example usage for java.sql ResultSet TYPE_SCROLL_INSENSITIVE

List of usage examples for java.sql ResultSet TYPE_SCROLL_INSENSITIVE

Introduction

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

Prototype

int TYPE_SCROLL_INSENSITIVE

To view the source code for java.sql ResultSet TYPE_SCROLL_INSENSITIVE.

Click Source Link

Document

The constant indicating the type for a ResultSet object that is scrollable but generally not sensitive to changes to the data that underlies the ResultSet.

Usage

From source file:edu.ku.brc.specify.conversion.IdHashMapper.java

/**
 * Cleans up temporary data./*from  w  ww.j a  va 2s.  co  m*/
 */
public void cleanup() {
    closeSQLStatements();

    if (mapTableName != null && doDelete) {
        try {
            Statement stmt = oldConn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
                    ResultSet.CONCUR_READ_ONLY);
            stmt.executeUpdate("DROP TABLE `" + mapTableName + "`");
            stmt.close();

        } catch (com.mysql.jdbc.exceptions.MySQLSyntaxErrorException ex) {
            log.error(ex);

        } catch (Exception ex) {
            //ex.printStackTrace();
            log.error(ex);
        }
        mapTableName = null;
    }
}

From source file:com.oracle.tutorial.jdbc.CoffeesFrame.java

public CachedRowSet getContentsOfCoffeesTable() throws SQLException {
    CachedRowSet crs = null;//w  w w  .j av a 2 s  .  c om
    try {
        connection = settings.getConnection();
        crs = new CachedRowSetImpl();
        crs.setType(ResultSet.TYPE_SCROLL_INSENSITIVE);
        crs.setConcurrency(ResultSet.CONCUR_UPDATABLE);
        crs.setUsername(settings.userName);
        crs.setPassword(settings.password);

        // In MySQL, to disable auto-commit, set the property relaxAutoCommit to
        // true in the connection URL.

        if (this.settings.dbms.equals("mysql")) {
            crs.setUrl(settings.urlString + "?relaxAutoCommit=true");
        } else {
            crs.setUrl(settings.urlString);
        }

        // Regardless of the query, fetch the contents of COFFEES

        crs.setCommand("select COF_NAME, SUP_ID, PRICE, SALES, TOTAL from COFFEES");
        crs.execute();

    } catch (SQLException e) {
        JDBCTutorialUtilities.printSQLException(e);
    }
    return crs;
}

From source file:com.taobao.datax.plugins.writer.oraclejdbcwriter.OracleJdbcWriter.java

@Override
public int post(PluginParam param) {
    if (StringUtils.isBlank(this.post))
        return PluginStatus.SUCCESS.value();

    Statement stmt = null;/*from  ww  w. j  a  v a 2 s . co m*/
    try {
        this.connection = DBSource.getConnection(this.sourceUniqKey);

        stmt = this.connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);

        for (String subSql : this.post.split(";")) {
            this.logger.info(String.format("Excute prepare sql %s .", subSql));
            stmt.execute(subSql);
        }

        return PluginStatus.SUCCESS.value();
    } catch (Exception e) {
        e.printStackTrace();
        throw new DataExchangeException(e.getCause());
    } finally {
        try {
            if (null != stmt) {
                stmt.close();
            }
            if (null != this.connection) {
                this.connection.close();
                this.connection = null;
            }
        } catch (Exception e2) {
        }

    }
}

From source file:com.streamsets.pipeline.stage.origin.jdbc.JdbcSource.java

private void supportsScrollableCursor(List<ConfigIssue> issues, Source.Context context,
        DatabaseMetaData dbMetadata) throws SQLException {
    if (!txnColumnName.isEmpty() && !dbMetadata.supportsResultSetType(ResultSet.TYPE_SCROLL_INSENSITIVE)) {
        issues.add(context.createConfigIssue(Groups.CDC.name(), TXN_ID_COLUMN_NAME, JdbcErrors.JDBC_30));
    }/*w  ww. j  a v a  2  s  .  co m*/
}

From source file:org.plasma.sdo.jdbc.service.GraphQuery.java

private int countResults(Connection con, Query query, PlasmaType type) {
    int result = 0;
    Object[] params = new Object[0];
    FilterAssembler filterAssembler = null;

    StringBuilder sqlQuery = new StringBuilder();
    AliasMap aliasMap = new AliasMap(type);

    sqlQuery.append("SELECT COUNT(*)");
    sqlQuery.append(aliasMap.getAlias(type));
    Statement statement = null;//from w w  w .j  av a2s.com
    ResultSet rs = null;

    try {
        Where where = query.findWhereClause();
        if (where != null) {
            filterAssembler = new FilterAssembler(where, type, aliasMap);
            sqlQuery.append(" ");
            sqlQuery.append(filterAssembler.getFilter());
            params = filterAssembler.getParams();

            if (log.isDebugEnabled()) {
                log.debug("filter: " + filterAssembler.getFilter());
            }
        } else {
            sqlQuery.append(" FROM ");
            sqlQuery.append(getQualifiedPhysicalName(type));
            sqlQuery.append(" ");
            sqlQuery.append(aliasMap.getAlias(type));
        }
        if (query.getStartRange() != null && query.getEndRange() != null)
            log.warn("query range (start: " + query.getStartRange() + ", end: " + query.getEndRange()
                    + ") ignored for count operation");

        if (log.isDebugEnabled()) {
            log.debug("queryString: " + sqlQuery.toString());
            log.debug("executing...");
        }

        statement = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        statement.execute(sqlQuery.toString());
        rs = statement.getResultSet();
        rs.first();
        result = rs.getInt(1);
    } catch (Throwable t) {
        StringBuffer buf = this.generateErrorDetail(t, sqlQuery.toString(), filterAssembler);
        log.error(buf.toString());
        throw new DataAccessException(t);
    } finally {
        try {
            if (rs != null)
                rs.close();
            if (statement != null)
                statement.close();
        } catch (SQLException e) {
            log.error(e.getMessage(), e);
        }
    }
    return result;
}

From source file:br.org.indt.ndg.server.client.TemporaryOpenRosaBussinessDelegate.java

public String getFormattedSurvey(String formId, String imei) {
    String result = null;/*www.ja va  2  s.  c om*/
    PreparedStatement selectSurveyWithIdStmt = null;
    PreparedStatement deleteSurveyForImeiStmt = null;
    Connection conn = null;
    try {
        conn = getDbConnection();
        selectSurveyWithIdStmt = conn.prepareStatement(SELECT_SURVEY_WITH_ID_STATEMENT,
                ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        selectSurveyWithIdStmt.setString(1, formId);
        ResultSet results = selectSurveyWithIdStmt.executeQuery();
        if (results.first()) {
            result = results.getString(SURVEY_CONTENT_COLUMN);
            // remove survey from available to download for this user
            deleteSurveyForImeiStmt = conn.prepareStatement(DELETE_SURVEYS_FOR_IMEI);
            deleteSurveyForImeiStmt.setString(1, formId);
            deleteSurveyForImeiStmt.setString(2, imei);
            deleteSurveyForImeiStmt.executeUpdate();
        }
    } catch (SQLException e) {
        e.printStackTrace();
    } finally {
        try {
            selectSurveyWithIdStmt.close();
            conn.close();
        } catch (Exception e) {
        }
    }
    return result;
}

From source file:fr.bird.bloom.model.GeographicTreatment.java

/**
 * Check if coordinates (latitude and longitude) are included in the country indicated by the iso2 code
 * /*from w ww .ja  v a 2  s  .c  o  m*/
 * @return void
 */
public List<String> checkCoordinatesIso2Code() {

    //this.getDarwinCore().associateIdData();

    List<String> listToDelete = new ArrayList<>();

    //Map<String, List<String>> idAssoData = this.getDarwinCore().getIdAssoData();
    final String resourcePath = BloomConfig.getResourcePath();
    List<String> idList = this.getDarwinCore().getID();
    //int iLatitude = this.getDarwinCore().getIndiceFromTag("decimalLatitude_");
    //int iLongitude = this.getDarwinCore().getIndiceFromTag("decimalLongitude_");
    //int iIso2 = this.getDarwinCore().getIndiceFromTag("countryCode_");
    //int iGbifID = this.getDarwinCore().getIndiceFromTag("gbifID_");

    int nbWrongIso2 = 0;
    List<String> listIDtoDelete = new ArrayList<>();
    for (int i = 0; i < idList.size(); i++) {
        String id_ = idList.get(i);
        //System.out.println(id_);
        //for (String id_ : idAssoData.keySet()) {
        //System.out.println(id_);
        if (!"id_".equals(id_)) {
            //List<String> listInfos = idAssoData.get(id_);
            boolean errorIso = true;
            boolean errorCoord = false;
            float latitude = -1;
            float longitude = -1;
            String iso2 = "error";
            String gbifId_ = "error";
            String iso3 = "error";

            String valueLatitude = this.getDarwinCore().getValueFromColumn("decimalLatitude_",
                    id_.replaceAll("\"", ""));
            System.err.println("decimalLatitude : " + valueLatitude);
            if (!valueLatitude.equals("error")) {
                try {
                    latitude = Float.parseFloat(valueLatitude.replaceAll("\"", ""));
                } catch (NumberFormatException ex) {
                    errorCoord = true;
                }
            }

            String valueLongitude = this.getDarwinCore().getValueFromColumn("decimalLongitude_",
                    id_.replaceAll("\"", ""));
            if (!valueLongitude.equals("error")) {
                try {
                    longitude = Float.parseFloat(valueLongitude.replaceAll("\"", ""));
                } catch (NumberFormatException ex) {
                    errorCoord = true;
                }
            }

            iso2 = this.getDarwinCore().getValueFromColumn("countryCode_", id_.replaceAll("\"", ""))
                    .replaceAll("\"", "");
            //gbifId_ = this.getDarwinCore().getValueFromColumn("gbifID_", id_.replaceAll("\"", "")).replaceAll("\"", "");

            if (!iso2.equals("error") && !errorCoord) {
                iso3 = this.convertIso2ToIso3(iso2);

                /*
                try {
                   latitude = Float.parseFloat(listInfos.get(iLatitude).replace("\"", ""));
                }
                catch (NumberFormatException nfe){
                   System.err.println(listInfos.get(iLatitude).replace("\"", ""));
                }
                longitude = Float.parseFloat(listInfos.get(iLongitude).replace("\"", ""));
                iso2 = listInfos.get(iIso2);
                */

                //gbifId_ = listInfos.get(iGbifID);
                if (!iso3.equals("error")) {
                    File geoJsonFile = new File(
                            resourcePath + "gadm_json/" + iso3.toUpperCase() + "_adm0.json");
                    GeometryFactory geometryFactory = new GeometryFactory();
                    Point point = geometryFactory.createPoint(new Coordinate(longitude, latitude));
                    System.out.println("--------------------------------------------------------------");
                    System.out.println("------------------ Check point in polygon --------------------");
                    System.out.println("Lat : " + latitude + "\tLong : " + longitude);
                    System.out.println("id_ : " + id_ + "\tIso3 : " + iso3 + "\tiso2 : " + iso2);

                    boolean isContained = this.polygonContainedPoint(point, geoJsonFile);

                    System.out.println("The point is contained in the polygone : " + isContained);
                    System.out.println("--------------------------------------------------------------\n");

                    if (!isContained) {
                        errorIso = true;
                        //nbWrongIso2 ++;
                        //listIDtoDelete.add(id_);
                    } else {
                        errorIso = false;
                    }
                } else {
                    errorIso = true;
                }
            } else {
                errorIso = true;
            }

            if (errorIso) {
                nbWrongIso2++;
                listIDtoDelete.add(id_);
            }
        }
    }
    if (listIDtoDelete.size() > 0) {
        String sqlIDCleanToSelect = "SELECT abstract_,acceptedNameUsage_,acceptedNameUsageID_,accessRights_,accrualMethod_,accrualPeriodicity_,accrualPolicy_,"
                + "alternative_,associatedMedia_,associatedOccurrences_,associatedOrganisms_,associatedReferences_,associatedSequences_,associatedTaxa_,audience_,"
                + "available_,basisOfRecord_,bed_,behavior_,bibliographicCitation_,catalogNumber_,class_,classKey_,collectionCode_,collectionID_,conformsTo_,continent_,"
                + "contributor_,coordinateAccuracy_,coordinatePrecision_,coordinateUncertaintyInMeters_,country_,countryCode_,county_,coverage_,created_,creator_,"
                + "dataGeneralizations_,datasetID_,datasetKey_,datasetName_,date_,dateAccepted_,dateCopyrighted_,dateIdentified_,dateSubmitted_,day_,decimalLatitude_,"
                + "decimalLongitude_,depth_,depthAccuracy_,description_,disposition_,distanceAboveSurface_,distanceAboveSurfaceAccuracy_,dynamicProperties_,"
                + "earliestAgeOrLowestStage_,earliestEonOrLowestEonothem_,earliestEpochOrLowestSeries_,earliestEraOrLowestErathem_,earliestPeriodOrLowestSystem_,"
                + "educationLevel_,elevation_,elevationAccuracy_,endDayOfYear_,establishmentMeans_,event_,eventDate_,eventID_,eventRemarks_,eventTime_,extent_,family_,"
                + "familyKey_,fieldNotes_,fieldNumber_,footprintSpatialFit_,footprintSRS_,footprintWKT_,format_,formation_,gbifID_,genericName_,genus_,genusKey_,"
                + "geodeticDatum_,geologicalContext_,geologicalContextID_,georeferencedBy_,georeferencedDate_,georeferenceProtocol_,georeferenceRemarks_,"
                + "georeferenceSources_,georeferenceVerificationStatus_,group_,habitat_,hasCoordinate_,hasFormat_,hasGeospatialIssues_,hasPart_,hasVersion_,"
                + "higherClassification_,higherGeography_,higherGeographyID_,highestBiostratigraphicZone_,identification_,identificationID_,identificationQualifier_,"
                + "identificationReferences_,identificationRemarks_,identificationVerificationStatus_,identifiedBy_,identifier_,idFile_,individualCount_,individualID_,"
                + "informationWithheld_,infraspecificEpithet_,institutionCode_,institutionID_,instructionalMethod_,isFormatOf_,island_,islandGroup_,isPartOf_,"
                + "isReferencedBy_,isReplacedBy_,isRequiredBy_,issue_,issued_,isVersionOf_,kingdom_,kingdomKey_,language_,lastCrawled_,lastInterpreted_,lastParsed_,"
                + "latestAgeOrHighestStage_,latestEonOrHighestEonothem_,latestEpochOrHighestSeries_,latestEraOrHighestErathem_,latestPeriodOrHighestSystem_,license_,"
                + "lifeStage_,lithostratigraphicTerms_,livingSpecimen_,locality_,locationAccordingTo_,locationID_,locationRemarks_,lowestBiostratigraphicZone_,"
                + "machineObservation_,materialSample_,materialSampleID_,maximumDepthinMeters_,maximumDistanceAboveSurfaceInMeters_,maximumElevationInMeters_,"
                + "measurementAccuracy_,measurementDeterminedBy_,measurementDeterminedDate_,measurementID_,measurementMethod_,measurementOrFact_,measurementRemarks_,"
                + "measurementType_,measurementUnit_,mediator_,mediaType_,medium_,member_,minimumDepthinMeters_,minimumDistanceAboveSurfaceInMeters_,"
                + "minimumElevationInMeters_,modified_,month_,municipality_,nameAccordingTo_,nameAccordingToID_,namePublishedIn_,namePublishedInID_,namePublishedInYear_,"
                + "nomenclaturalCode_,nomenclaturalStatus_,occurrence_,occurrenceDetails_,occurrenceID_,occurrenceRemarks_,occurrenceStatus_,order_,orderKey_,organism_,"
                + "organismID_,organismName_,organismRemarks_,organismScope_,originalNameUsage_,originalNameUsageID_,otherCatalogNumbers_,ownerInstitutionCode_,"
                + "parentNameUsage_,parentNameUsageID_,phylum_,phylumKey_,pointRadiusSpatialFit_,preparations_,preservedSpecimen_,previousIdentifications_,protocol_,"
                + "provenance_,publisher_,publishingCountry_,recordedBy_,recordNumber_,references_,relatedResourceID_,relationshipAccordingTo_,"
                + "relationshipEstablishedDate_,relationshipRemarks_,relation_,replaces_,reproductiveCondition_,requires_,resourceID_,resourceRelationship_,"
                + "resourceRelationshipID_,rights_,rightsHolder_,samplingEffort_,samplingProtocol_,scientificName_,scientificNameAuthorship_,scientificNameID_,sex_,"
                + "source_,spatial_,species_,speciesKey_,specificEpithet_,startDayOfYear_,stateProvince_,subgenus_,subgenusKey_,subject_,tableOfContents_,taxon_,"
                + "taxonConceptID_,taxonID_,taxonKey_,taxonomicStatus_,taxonRank_,taxonRemarks_,temporal_,title_,type_,typeStatus_,typifiedName_,valid_,"
                + "verbatimCoordinates_,verbatimCoordinateSystem_,verbatimDate_,verbatimDepth_,verbatimElevation_,verbatimEventDate_,verbatimLatitude_,"
                + "verbatimLocality_,verbatimLongitude_,verbatimSRS_,verbatimTaxonRank_,vernacularName_,waterBody_,year_ FROM Workflow.Clean_"
                + this.getUuid() + " WHERE Clean_" + this.getUuid() + ".id_=";

        String sqlIDCleanToDelete = "DELETE FROM Workflow.Clean_" + this.getUuid() + " WHERE id_=";
        for (int l = 0; l < listIDtoDelete.size(); l++) {
            if (l != listIDtoDelete.size() - 1) {
                sqlIDCleanToDelete += listIDtoDelete.get(l) + " OR id_=";
                sqlIDCleanToSelect += listIDtoDelete.get(l) + " OR Clean_" + this.getUuid() + ".id_=";
            } else {
                sqlIDCleanToDelete += listIDtoDelete.get(l) + ";";
                sqlIDCleanToSelect += listIDtoDelete.get(l) + ";";
            }
        }
        Statement statement = null;
        try {
            statement = ConnectionDatabase.getConnection().createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
                    ResultSet.CONCUR_READ_ONLY);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        DatabaseTreatment newConnectionSelectID = new DatabaseTreatment(statement);
        List<String> messagesSelectID = new ArrayList<>();
        //String sqlSelectID =  + id_ + ";";
        messagesSelectID.add("\n--- Select wrong matching between polygon and Iso2 code ---\n");
        messagesSelectID.addAll(newConnectionSelectID.executeSQLcommand("executeQuery", sqlIDCleanToSelect));
        //messagesSelectID.add(sqlIDCleanToSelect);
        for (int j = 0; j < messagesSelectID.size(); j++) {
            System.out.println(messagesSelectID.get(j));
        }

        List<String> selectIDResults = newConnectionSelectID.getResultatSelect();
        for (int k = 0; k < selectIDResults.size(); k++) {
            if (!listToDelete.contains(selectIDResults.get(k))) {
                listToDelete.add(selectIDResults.get(k));
            }
        }
        Statement statementDelete = null;
        try {
            statementDelete = ConnectionDatabase.getConnection()
                    .createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        DatabaseTreatment newConnectionDeleteID = new DatabaseTreatment(statementDelete);
        List<String> messagesDeleteID = new ArrayList<>();
        //String sqlDeleteID = "DELETE FROM Workflow.Clean_" + this.getUuid() + " WHERE id_=" + id_ + ";";
        messagesDeleteID.add("\n--- Delete wrong matching between polygon and Iso2 code ---\n");
        messagesDeleteID.addAll(newConnectionDeleteID.executeSQLcommand("executeUpdate", sqlIDCleanToDelete));
        List<String> deleteIDResults = newConnectionDeleteID.getResultatSelect();
        messagesDeleteID.add("nb lignes affectes :" + listToDelete.size());
        for (int i = 0; i < messagesDeleteID.size(); i++) {
            System.out.println(messagesDeleteID.get(i));
        }

    }

    this.setNbWrongIso2(nbWrongIso2);

    return listToDelete;
}

From source file:eu.optimis_project.monitoring.storage.MySQLStorageManager.java

public void dropTable() throws SQLException {
    final String createTable = "DROP TABLE IF EXISTS " + tableName + ";";

    Statement statement = null;/*w w  w.j av  a  2 s. co  m*/
    try {
        log.debug("Executing query: " + createTable);
        statement = getConnection().createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
                ResultSet.CONCUR_UPDATABLE);
        statement.execute(createTable);
    } catch (SQLException e) {
        throw e;
    } finally {
        try {
            if (statement != null) {
                statement.close();
            }
        } catch (SQLException e) {
            log.debug("Failed to close statement.", 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  . ja  v a  2  s.c  om*/
 *
 * @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.user.core.claim.dao.ClaimDAO.java

protected void deleteClaimMapping(Connection dbConnection, String claimUri, String dialectUri)
        throws UserStoreException {
    PreparedStatement prepStmt = null;
    boolean isFinalRow = true;
    try {/*from w  w  w .  j a  v a 2  s  . co m*/
        if (dialectUri.equals(UserCoreConstants.DEFAULT_CARBON_DIALECT)) {
            //prepStmt = dbConnection
            //      .prepareStatement(ClaimDBConstants.GET_CLAIMS_FOR_DIALECTT_SQL);
            prepStmt = dbConnection.prepareStatement(ClaimDBConstants.GET_CLAIMS_FOR_DIALECTT_SQL,
                    ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
            prepStmt.setString(1, dialectUri);
            prepStmt.setInt(2, tenantId);
            prepStmt.setInt(3, tenantId);
            ResultSet rs = prepStmt.executeQuery();
            while (rs.next()) {
                if (rs.getRow() > 1) {
                    isFinalRow = false;
                    break;
                }
            }
            if (isFinalRow) {
                throw new UserStoreException("Cannot delete all claim mappings");
            }
        }

        prepStmt = dbConnection.prepareStatement(ClaimDBConstants.DELETE_CLAIM_SQL);
        prepStmt.setString(1, claimUri);
        prepStmt.setString(2, dialectUri);
        prepStmt.setInt(3, tenantId);
        prepStmt.setInt(4, tenantId);
        prepStmt.executeUpdate();
        prepStmt.close();

    } catch (SQLException e) {
        log.error("Database Error - " + e.getMessage(), e);
        throw new UserStoreException("Database Error - " + e.getMessage(), e);
    } finally {
        DatabaseUtil.closeAllConnections(null, prepStmt);
    }
}