Example usage for java.sql PreparedStatement setFetchSize

List of usage examples for java.sql PreparedStatement setFetchSize

Introduction

In this page you can find the example usage for java.sql PreparedStatement setFetchSize.

Prototype

void setFetchSize(int rows) throws SQLException;

Source Link

Document

Gives the JDBC driver a hint as to the number of rows that should be fetched from the database when more rows are needed for ResultSet objects generated by this Statement.

Usage

From source file:com.commander4j.db.JDBUserReport.java

public boolean isValidUserReport() {

    PreparedStatement stmt;
    ResultSet rs;/*w w  w .  ja  va2s  .  com*/
    boolean result = false;

    try {
        stmt = Common.hostList.getHost(getHostID()).getConnection(getSessionID()).prepareStatement(
                Common.hostList.getHost(getHostID()).getSqlstatements().getSQL("JDBUserReport.isValid"));
        stmt.setString(1, getReportID());
        stmt.setFetchSize(1);
        rs = stmt.executeQuery();

        if (rs.next()) {
            result = true;
            setErrorMessage("Report ID [" + getReportID() + "] exists");
        } else {
            setErrorMessage("Invalid User Report ID");
        }
        rs.close();
        stmt.close();
    } catch (SQLException e) {
        setErrorMessage(e.getMessage());
    }

    logger.debug("isValidUserReport :" + result);

    return result;
}

From source file:com.commander4j.db.JDBUserReport.java

public boolean runReport() {
    PreparedStatement prepStatement;
    boolean result = true;

    try {//  w ww  .jav  a2 s . c  o  m
        prepStatement = Common.hostList.getHost(getHostID()).getConnection(getSessionID())
                .prepareStatement(getSQL(), ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
        prepStatement.setFetchSize(25);

        if (isParamDateRequired()) {
            prepStatement.setTimestamp(1, getParamFromDate());
            prepStatement.setTimestamp(2, getParamToDate());
        }

        if (getDestination().equals("SYSTEM")) {
            for (int x = 0; x < systemParams.size(); x++) {
                String type = systemParams.get(x).parameterType;

                if (type.toLowerCase().equals("string")) {
                    prepStatement.setString(systemParams.get(x).parameterPosition,
                            systemParams.get(x).parameterStringValue);
                }
                if (type.toLowerCase().equals("integer")) {
                    prepStatement.setInt(systemParams.get(x).parameterPosition,
                            systemParams.get(x).parameterIntegerValue);
                }
                if (type.toLowerCase().equals("long")) {
                    prepStatement.setLong(systemParams.get(x).parameterPosition,
                            systemParams.get(x).parameterLongValue);
                }
                if (type.toLowerCase().equals("timestamp")) {
                    prepStatement.setTimestamp(systemParams.get(x).parameterPosition,
                            systemParams.get(x).parameterTimestampValue);
                }
            }
        }

        ResultSet tempResult = prepStatement.executeQuery();

        boolean dataReturned = true;
        if (!tempResult.next()) {
            dataReturned = false;
        }
        tempResult.beforeFirst();
        if (dataReturned) {
            if (getDestination().equals("EXCEL")) {
                generateExcel(tempResult);
            }

            if (getDestination().equals("JASPER_REPORTS")) {
                generateJasper(prepStatement);
            }
            if (getDestination().equals("PDF")) {
                generatePDF(prepStatement);
            }
            if (getDestination().equals("ACCESS")) {
                generateAccess(tempResult);
            }

            if (getDestination().equals("CSV")) {
                generateCSV(tempResult);
            }

            if (getDestination().equals("SYSTEM")) {
                generateSYSTEM(tempResult);
            }

            if (isPreviewRequired()) {
                try {
                    Desktop.getDesktop().open(new File(getExportFilename()));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (isEmailEnabled()) {

                String emailaddresses = getEmailAddresses();

                if (isEmailPromptEnabled()) {
                    emailaddresses = JUtility.replaceNullStringwithBlank(
                            JOptionPane.showInputDialog(lang.get("lbl_Email_Addresses")));
                }

                StringConverter stringConverter = new StringConverter();
                ArrayConverter arrayConverter = new ArrayConverter(String[].class, stringConverter);
                arrayConverter.setDelimiter(';');
                arrayConverter.setAllowedChars(new char[] { '@', '_' });

                String[] emailList = (String[]) arrayConverter.convert(String[].class, emailaddresses);

                if (emailList.length > 0) {
                    String shortFilename = JUtility.getFilenameFromPath(getExportFilename());
                    mail.postMail(emailList,
                            "Commande4j User Report requested by "
                                    + Common.userList.getUser(Common.sessionID).getUserId() + " from ["
                                    + Common.hostList.getHost(getHostID()).getSiteDescription() + "] on "
                                    + JUtility.getClientName(),
                            "See attached report.\n", shortFilename, getExportFilename());
                    com.commander4j.util.JWait.milliSec(2000);
                }
            }

        } else {
            result = false;
            setErrorMessage("No data returned by query.");
        }

    } catch (Exception ex) {
        setErrorMessage(ex.getMessage());
        result = false;
    }

    return result;
}

From source file:com.commander4j.thread.AutoLabellerThread.java

public void run() {
    logger.debug("AutoLabeller Thread running");
    setSessionID(JUnique.getUniqueID());
    JDBUser user = new JDBUser(getHostID(), getSessionID());
    user.setUserId("interface");
    user.setPassword("interface");
    user.setLoginPassword("interface");
    Common.userList.addUser(getSessionID(), user);
    Common.sd.setData(getSessionID(), "silentExceptions", "Yes", true);

    Boolean dbconnected = false;//  www .  j a va 2  s  .  co m

    if (Common.hostList.getHost(hostID).isConnected(sessionID) == false) {

        dbconnected = Common.hostList.getHost(hostID).connect(sessionID, hostID);

    } else {
        dbconnected = true;
    }

    if (dbconnected) {

        JDBViewAutoLabellerPrinter alp = new JDBViewAutoLabellerPrinter(getHostID(), getSessionID());
        LinkedList<JDBViewAutoLabellerPrinter> autolabellerList = new LinkedList<JDBViewAutoLabellerPrinter>();

        int noOfMessages = 0;

        while (true) {

            JWait.milliSec(500);

            if (allDone) {
                if (dbconnected) {
                    Common.hostList.getHost(hostID).disconnect(getSessionID());
                }
                return;
            }

            autolabellerList.clear();
            autolabellerList = alp.getModifiedPrinterLines();
            noOfMessages = autolabellerList.size();

            if (noOfMessages > 0) {
                for (int x = 0; x < noOfMessages; x++) {
                    JWait.milliSec(100);

                    JDBViewAutoLabellerPrinter autolabview = autolabellerList.get(x);

                    messageProcessedOK = true;
                    messageError = "";

                    if (autolabview.getPrinterObj().isEnabled()) {
                        logger.debug("Line             =" + autolabview.getAutoLabellerObj().getLine());
                        logger.debug("Line Description =" + autolabview.getAutoLabellerObj().getDescription());
                        logger.debug("Printer ID       =" + autolabview.getPrinterObj().getPrinterID());
                        logger.debug("Printer Enabled  =" + autolabview.getPrinterObj().isEnabled());
                        logger.debug("Export Path      =" + autolabview.getPrinterObj().getExportRealPath());
                        logger.debug("Export Enabled   =" + autolabview.getPrinterObj().isExportEnabled());
                        logger.debug("Export Format    =" + autolabview.getPrinterObj().getExportFormat());
                        logger.debug("Direct Print     =" + autolabview.getPrinterObj().isDirectPrintEnabled());
                        logger.debug("Printer Type     =" + autolabview.getPrinterObj().getPrinterType());
                        logger.debug("Printer IP       =" + autolabview.getPrinterObj().getIPAddress());
                        logger.debug("Printer Port     =" + autolabview.getPrinterObj().getPort());
                        logger.debug("Process Order    =" + autolabview.getLabelDataObj().getProcessOrder());
                        logger.debug("Material         =" + autolabview.getLabelDataObj().getMaterial());
                        logger.debug("Module ID        =" + autolabview.getModuleObj().getModuleId());
                        logger.debug("Module Type      =" + autolabview.getModuleObj().getType());

                        if (autolabview.getPrinterObj().isExportEnabled()) {
                            String exportPath = JUtility.replaceNullStringwithBlank(
                                    JUtility.formatPath(autolabview.getPrinterObj().getExportRealPath()));
                            if (exportPath.equals("") == false) {
                                if (exportPath.substring(exportPath.length() - 1)
                                        .equals(File.separator) == false) {
                                    exportPath = exportPath + File.separator;
                                }
                            } else {
                                exportPath = Common.interface_output_path + "Auto Labeller" + File.separator;
                            }

                            String exportFilename = exportPath
                                    + JUtility.removePathSeparators(autolabview.getAutoLabellerObj().getLine())
                                    + "_"
                                    + JUtility.removePathSeparators(autolabview.getPrinterObj().getPrinterID())
                                    + "." + autolabview.getPrinterObj().getExportFormat();

                            String exportFilenameTemp = exportFilename + ".out";

                            logger.debug("Export Filename  =" + exportFilename);

                            /* ================CSV================ */

                            if (autolabview.getPrinterObj().getExportFormat().equals("CSV")) {
                                try {
                                    PreparedStatement stmt = null;
                                    ResultSet rs;
                                    String labelType = autolabview.getLabelDataObj().getLabelType();
                                    stmt = Common.hostList.getHost(getHostID()).getConnection(getSessionID())
                                            .prepareStatement(
                                                    Common.hostList.getHost(getHostID()).getSqlstatements()
                                                            .getSQL("DBVIEW_AUTO_LABELLER_PRINTER.getProperties"
                                                                    + "_" + labelType));
                                    stmt.setString(1, autolabview.getAutoLabellerObj().getLine());
                                    stmt.setString(2, autolabview.getPrinterObj().getPrinterID());
                                    stmt.setFetchSize(50);

                                    rs = stmt.executeQuery();

                                    logger.debug("Writing CSV");

                                    CSVWriter writer = new CSVWriter(new FileWriter(exportFilenameTemp),
                                            CSVWriter.DEFAULT_SEPARATOR, CSVWriter.DEFAULT_QUOTE_CHARACTER,
                                            CSVWriter.DEFAULT_ESCAPE_CHARACTER, CSVWriter.DEFAULT_LINE_END);

                                    writer.writeAll(rs, true);

                                    rs.close();

                                    stmt.close();

                                    writer.close();

                                    File fromFile = new File(exportFilenameTemp);
                                    File toFile = new File(exportFilename);

                                    FileUtils.deleteQuietly(toFile);
                                    FileUtils.moveFile(fromFile, toFile);

                                    fromFile = null;
                                    toFile = null;

                                } catch (Exception e) {
                                    messageProcessedOK = false;
                                    messageError = e.getMessage();
                                }
                            }

                            /* ================XML================ */

                            if (autolabview.getPrinterObj().getExportFormat().equals("XML")) {
                                try {
                                    PreparedStatement stmt = null;
                                    ResultSet rs;

                                    stmt = Common.hostList.getHost(getHostID()).getConnection(getSessionID())
                                            .prepareStatement(Common.hostList.getHost(getHostID())
                                                    .getSqlstatements()
                                                    .getSQL("DBVIEW_AUTO_LABELLER_PRINTER.getProperties"));
                                    stmt.setString(1, autolabview.getAutoLabellerObj().getLine());
                                    stmt.setString(2, autolabview.getPrinterObj().getPrinterID());
                                    stmt.setFetchSize(50);

                                    rs = stmt.executeQuery();
                                    ResultSetMetaData rsmd = rs.getMetaData();
                                    int colCount = rsmd.getColumnCount();

                                    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                                    DocumentBuilder builder = factory.newDocumentBuilder();
                                    Document document = builder.newDocument();

                                    Element message = (Element) document.createElement("message");

                                    Element hostUniqueID = addElement(document, "hostRef",
                                            Common.hostList.getHost(getHostID()).getUniqueID());
                                    message.appendChild(hostUniqueID);

                                    Element messageRef = addElement(document, "messageRef",
                                            autolabview.getAutoLabellerObj().getUniqueID());
                                    message.appendChild(messageRef);

                                    Element messageType = addElement(document, "interfaceType",
                                            "Auto Labeller Data");
                                    message.appendChild(messageType);

                                    Element messageInformation = addElement(document, "messageInformation",
                                            "Unique ID=" + autolabview.getAutoLabellerObj().getUniqueID());
                                    message.appendChild(messageInformation);

                                    Element messageDirection = addElement(document, "interfaceDirection",
                                            "Output");
                                    message.appendChild(messageDirection);

                                    Element messageDate = addElement(document, "messageDate",
                                            JUtility.getISOTimeStampStringFormat(JUtility.getSQLDateTime()));
                                    message.appendChild(messageDate);

                                    if (rs.first()) {

                                        Element labelData = (Element) document.createElement("LabelData");

                                        Element row = document.createElement("Row");
                                        labelData.appendChild(row);
                                        for (int i = 1; i <= colCount; i++) {
                                            String columnName = rsmd.getColumnName(i);
                                            Object value = rs.getObject(i);
                                            Element node = document.createElement(columnName);
                                            node.appendChild(document.createTextNode(value.toString()));
                                            row.appendChild(node);
                                        }

                                        message.appendChild(labelData);

                                        document.appendChild(message);

                                        JXMLDocument xmld = new JXMLDocument();
                                        xmld.setDocument(document);

                                        // ===============================

                                        DOMImplementationLS DOMiLS = null;
                                        FileOutputStream FOS = null;

                                        // testing the support for DOM
                                        // Load and Save
                                        if ((document.getFeature("Core", "3.0") != null)
                                                && (document.getFeature("LS", "3.0") != null)) {
                                            DOMiLS = (DOMImplementationLS) (document.getImplementation())
                                                    .getFeature("LS", "3.0");

                                            // get a LSOutput object
                                            LSOutput LSO = DOMiLS.createLSOutput();

                                            FOS = new FileOutputStream(exportFilename);
                                            LSO.setByteStream((OutputStream) FOS);

                                            // get a LSSerializer object
                                            LSSerializer LSS = DOMiLS.createLSSerializer();

                                            // do the serialization
                                            LSS.write(document, LSO);

                                            FOS.close();
                                        }

                                        // ===============================

                                    }
                                    rs.close();
                                    stmt.close();

                                } catch (Exception e) {
                                    messageError = e.getMessage();
                                }

                            }

                            if (autolabview.getPrinterObj().getExportFormat().equals("LQF")) {

                            }
                        }

                        if (autolabview.getPrinterObj().isDirectPrintEnabled()) {

                        }

                    }

                    if (messageProcessedOK == true) {
                        autolabview.getAutoLabellerObj().setModified(false);
                        autolabview.getAutoLabellerObj().update();
                    } else {
                        logger.debug(messageError);
                    }

                    autolabview = null;
                }
            }
        }
    }
}

From source file:edu.jhuapl.openessence.datasource.jdbc.JdbcOeDataSource.java

public void detailsQuery(final QueryManipulationStore queryManipStore, final RowCallbackHandler rcbh,
        final Integer fzparm) throws OeDataSourceException {

    if (jdbcTemplate == null) {
        throw new OeDataSourceException("No JDBC Template configured");
    }//from www.  ja  v a2s . c  o m

    if (superResultMap == null) {
        throw new OeDataSourceException(
                "There are no result dimensions for this datasource. Please check 'WARN log' and your groovy configuration for datasource name : "
                        + this.getClass().getCanonicalName());
    }

    fixResultDimensions(queryManipStore);

    fixAccumDimensions(queryManipStore);

    // helper method to override/apply additional filters
    updateQueryManipStore(queryManipStore);

    final Collection<Dimension> results = queryManipStore.getResults();
    if (!CollectionUtils.isEmpty(results)) {
        // now check if each result dimension is okay.
        for (final Dimension d : results) {
            if (d != null) {
                final DimensionBean bean = superResultMap.get(d.getId());
                if (resultFilterIds.size() > 0) {
                    if (bean == null && !resultFilterIds.contains(d.getId())) {
                        throw new OeDataSourceException("Unrecognized result dimension " + d.getId());
                    }
                } else {
                    if (bean == null) {
                        throw new OeDataSourceException("Unrecognized result dimension " + d.getId());
                    }
                }
            } else {
                throw new OeDataSourceException(
                        "There was a potential typo either in the Groovy datasource definition file or the dimension Id that was requested for a dimension in that definition file. Check 'WARN log' and dimension Id spellings for this datasource: "
                                + this.getClass().getCanonicalName());
            }
        }
    } else {
        throw new OeDataSourceException("Results must be specified.");
    }

    final Collection<Filter> filters = queryManipStore.getWhereClauseFilters();
    if (filters == null) {
        throw new OeDataSourceException("Filters cannot be null");
    }
    checkFilters(filters);

    final Collection<OrderByFilter> sorters = queryManipStore.getOrderByFilters();
    if (!CollectionUtils.isEmpty(sorters)) {
        for (final OrderByFilter orderby : sorters) {
            if (getResultDimension(orderby.getFilterId()) == null) {
                throw new OeDataSourceException("Result dimensions must contain all sorting values");
            }
        }
    }

    final List<Object> arguments = getArguments(filters);
    queryManipStore.setArguments(arguments);

    final int fz = (fzparm != null ? fzparm : jdbcTemplate.getFetchSize());
    jdbcTemplate.query(new DetailsPreparedStatementCreator(queryManipStore) {
        @Override
        public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
            PreparedStatement ps = super.createPreparedStatement(con);
            ps.setFetchSize(fz);
            return ps;
        }
    }, rcbh);
}

From source file:com.commander4j.db.JDBDespatch.java

public Boolean isPalletBatchStatusOK(String despatchNo) {
    Boolean result = true;/*from   w  w  w  . j  av  a 2  s. c o m*/
    String temp = Common.hostList.getHost(getHostID()).getSqlstatements()
            .getSQL("JDBDespatch.checkPalletBatchStatus");

    // Replace Despatch No

    temp = StringUtils.replace(temp, "%1", "'" + despatchNo + "'");

    // Replace Valid Pallet Status List

    String ps = lt.getPermittedPalletStatus();

    String[] split = StringUtils.split(ps, '^');

    String l = "";

    for (int cur = 0; cur < split.length; cur++) {
        l = l + "'" + split[cur] + "'";

        if (cur < (split.length - 1)) {
            l = l + ",";
        }
    }

    temp = StringUtils.replace(temp, "%2", l);

    // Replace Valid Batch Status List

    ps = lt.getPermittedBatchStatus();

    split = StringUtils.split(ps, '^');

    l = "";

    for (int cur = 0; cur < split.length; cur++) {
        l = l + "'" + split[cur] + "'";

        if (cur < (split.length - 1)) {
            l = l + ",";
        }
    }

    temp = StringUtils.replace(temp, "%3", l);

    PreparedStatement stmt = null;
    ResultSet rs;

    try {
        stmt = Common.hostList.getHost(getHostID()).getConnection(getSessionID()).prepareStatement(temp);
        stmt.setFetchSize(50);

        rs = stmt.executeQuery();

        rs.last();
        int rows = rs.getRow();
        rs.beforeFirst();

        if (rows > 0) {
            result = false;
        }

        rs.close();

        stmt.close();
    } catch (SQLException e) {
        setErrorMessage(e.getMessage());
    }

    return result;
}

From source file:com.toxind.benchmark.thrid.ibatis.sqlmap.engine.execution.SqlExecutor.java

/**
 * Long form of the method to execute a query
 * //  w  ww.  jav a2 s .co  m
 * @param statementScope
 *            - the request scope
 * @param conn
 *            - the database connection
 * @param sql
 *            - the SQL statement to execute
 * @param parameters
 *            - the parameters for the statement
 * @param skipResults
 *            - the number of results to skip
 * @param maxResults
 *            - the maximum number of results to return
 * @param callback
 *            - the row handler for the query
 * @throws SQLException
 *             - if the query fails
 */
public void executeQuery(StatementScope statementScope, Connection conn, String sql, Object[] parameters,
        int skipResults, int maxResults, RowHandlerCallback callback) throws SQLException {
    ErrorContext errorContext = statementScope.getErrorContext();
    errorContext.setActivity("executing query");
    errorContext.setObjectId(sql);
    PreparedStatement ps = null;
    ResultSet rs = null;
    setupResultObjectFactory(statementScope);
    try {
        errorContext.setMoreInfo("Check the SQL Statement (preparation failed).");
        Integer rsType = statementScope.getStatement().getResultSetType();
        if (rsType != null) {
            ps = prepareStatement(statementScope.getSession(), conn, sql, rsType);
        } else {
            ps = prepareStatement(statementScope.getSession(), conn, sql);
        }
        setStatementTimeout(statementScope.getStatement(), ps);
        Integer fetchSize = statementScope.getStatement().getFetchSize();
        if (fetchSize != null) {
            ps.setFetchSize(fetchSize.intValue());
        }
        errorContext.setMoreInfo("Check the parameters (set parameters failed).");
        statementScope.getParameterMap().setParameters(statementScope, ps, parameters);
        errorContext.setMoreInfo("Check the statement (query failed).");

        // ========================== print
        if (log.isInfoEnabled()) {
            int count = ps.getParameterMetaData().getParameterCount();
            for (int i = 0; i < count; i++) {
                sql = sql.replaceFirst("\\?",
                        parameters[i].getClass().getName().equals("java.lang.String")
                                ? "'" + parameters[i].toString() + "'"
                                : parameters[i].toString());
            }
            String[] unPrintSql = { "select * from dw_websql_sqlcommand a where a.ds_id ",
                    "select count(1) from dw_websql_sqlcommand ", "select sql_id , user_code , submit_sql ,",
                    "select * from dw_websql_sqlcommand" };

            printSql(sql, unPrintSql);
        }
        // =========================== print

        ps.execute();
        errorContext.setMoreInfo("Check the results (failed to retrieve results).");

        // Begin ResultSet Handling
        rs = handleMultipleResults(ps, statementScope, skipResults, maxResults, callback);
        // End ResultSet Handling
    } finally {
        try {
            closeResultSet(rs);
        } finally {
            closeStatement(statementScope.getSession(), ps);
        }
    }

}

From source file:com.commander4j.db.JDBDespatch.java

public LinkedList<JDBEquipmentList> getEquipment() {
    LinkedList<JDBEquipmentList> result = new LinkedList<JDBEquipmentList>();
    PreparedStatement stmt = null;
    ResultSet rs;// w  w w  .j a va 2 s .  com
    String temp = "";

    try {
        temp = Common.hostList.getHost(getHostID()).getSqlstatements().getSQL("JDBDespatch.equipment");

        stmt = Common.hostList.getHost(getHostID()).getConnection(getSessionID()).prepareStatement(temp);
        stmt.setFetchSize(25);
        stmt.setString(1, getDespatchNo());

        rs = stmt.executeQuery();
        result.clear();

        while (rs.next()) {
            result.addLast(new JDBEquipmentList(rs.getString("equipment_type"), rs.getInt("total")));
        }

        rs.close();
        stmt.close();
    } catch (SQLException e) {
        setErrorMessage(e.getMessage());
    }

    return result;
}

From source file:com.commander4j.db.JDBDespatch.java

public int getDespatchPalletCount() {
    int result = 0;

    setTotalPallets(0);//from w w  w  . j  a  v  a 2  s .  c o  m

    PreparedStatement stmt;
    ResultSet rs;
    setErrorMessage("");
    logger.debug("getDespatchPalletCount");

    try {
        stmt = Common.hostList.getHost(getHostID()).getConnection(getSessionID()).prepareStatement(
                Common.hostList.getHost(getHostID()).getSqlstatements().getSQL("JDBDespatch.count"));
        stmt.setFetchSize(50);
        stmt.setString(1, getDespatchNo());
        rs = stmt.executeQuery();

        if (rs.next()) {
            result = rs.getInt("pallet_count");
            setTotalPallets(result);
        } else {
            result = -1;
            setErrorMessage("Invalid Despatch No");
        }
        rs.close();
        stmt.close();
    } catch (SQLException e) {
        setErrorMessage(e.getMessage());
    }

    return result;
}

From source file:com.flexive.core.storage.genericSQL.GenericTreeStorageSpreaded.java

/**
 * {@inheritDoc}/*  w ww  .  j  av  a  2  s . c  o m*/
 */
@Override
public void checkTree(Connection con, FxTreeMode mode) throws FxApplicationException {
    PreparedStatement stmt = null;
    try {
        // 1 - ID, 2 - LFT, 3 - RGT, 4 - CHILDCOUNT, 5 - DEPTH, 6 - PARENT
        final String sql = "SELECT t.id, t.LFT, t.RGT, t.CHILDCOUNT, t.DEPTH, t.PARENT " + "FROM "
                + getTable(mode) + " t";
        stmt = con.prepareStatement(sql);
        stmt.setFetchSize(10000);
        final ResultSet rs = stmt.executeQuery();

        // collect nodes, build lookup tables
        final Map<Long, CheckedNodeInfo> nodeMap = Maps.newHashMap(); // node ID -> node info
        final Multimap<Long, CheckedNodeInfo> childMap = HashMultimap.create(); // node ID -> children
        final Multimap<BigInteger, CheckedNodeInfo> leftNodeInfos = HashMultimap.create(1000, 1);
        final Multimap<BigInteger, CheckedNodeInfo> rightNodeInfos = HashMultimap.create(1000, 1);
        while (rs.next()) {
            final CheckedNodeInfo info = new CheckedNodeInfo(rs.getLong(1), rs.getLong(6), getNodeBounds(rs, 2),
                    getNodeBounds(rs, 3), rs.getInt(4), rs.getInt(5));
            nodeMap.put(info.id, info);
            childMap.put(info.parentId, info);
            leftNodeInfos.put(info.left, info);
            rightNodeInfos.put(info.right, info);
        }

        // process all nodes
        for (CheckedNodeInfo node : nodeMap.values()) {

            // check node boundaries
            if (node.left.compareTo(node.right) > 0) {
                throw new FxTreeException(LOG, "ex.tree.check.failed", mode,
                        "#" + node.id + ": left boundary greater than right.");
            }

            // check node bounds of children
            BigInteger min = MAX_RIGHT;
            BigInteger max = BigInteger.ZERO;
            final Collection<CheckedNodeInfo> children = childMap.get(node.id);
            for (CheckedNodeInfo child : children) {
                if (child.left.compareTo(min) < 0) {
                    min = child.left;
                }
                if (child.right.compareTo(max) > 0) {
                    max = child.right;
                }
            }
            if (max.compareTo(node.right) > 0) {
                throw new FxTreeException(LOG, "ex.tree.check.failed", mode,
                        "#" + node.id + " out of bounds (right)");
            }
            if (min.compareTo(node.left) < 0) {
                throw new FxTreeException(LOG, "ex.tree.check.failed", mode,
                        "#" + node.id + " out of bounds (left)");
            }

            // Check stored child count
            if (node.directChildCount != children.size()) {
                throw new FxTreeException(LOG, "ex.tree.check.failed", mode,
                        "#" + node.id + " invalid direct child count [" + node.directChildCount + "!="
                                + children.size() + "]");
            }

            // Check depth
            if (node.id != FxTreeNode.ROOT_NODE && node.depth != nodeMap.get(node.parentId).depth + 1) {
                throw new FxTreeException(LOG, "ex.tree.check.failed", mode, "#" + node.id + " invalid depth: "
                        + node.depth + ", parent depth=" + nodeMap.get(node.parentId).depth);
            }
        }

        checkUniqueBounds(mode, leftNodeInfos, "left");
        checkUniqueBounds(mode, rightNodeInfos, "right");

        if (LOG.isDebugEnabled())
            LOG.debug(
                    "Successfully checked [" + childMap.size() + "] tree nodes in mode [" + mode.name() + "]!");
    } catch (SQLException e) {
        throw new FxTreeException(LOG, e, "ex.tree.check.failed", mode, e.getMessage());
    } finally {
        Database.closeObjects(GenericTreeStorageSpreaded.class, stmt);
    }
}

From source file:com.commander4j.db.JDBDespatch.java

public boolean isValidDespatchNo() {

    PreparedStatement stmt;
    ResultSet rs;//from  w w  w.ja  va 2  s . c om
    boolean result = false;

    try {
        stmt = Common.hostList.getHost(getHostID()).getConnection(getSessionID()).prepareStatement(
                Common.hostList.getHost(getHostID()).getSqlstatements().getSQL("JDBDespatch.isValidDespatch"));
        stmt.setString(1, getDespatchNo());
        stmt.setFetchSize(1);
        rs = stmt.executeQuery();

        if (rs.next()) {
            result = true;
        } else {
            setErrorMessage("Invalid Despatch No [" + getDespatchNo() + "]");
        }

        rs.close();
        stmt.close();
    } catch (SQLException e) {
        setErrorMessage(e.getMessage());
    }

    return result;
}