Example usage for javax.sql.rowset CachedRowSet populate

List of usage examples for javax.sql.rowset CachedRowSet populate

Introduction

In this page you can find the example usage for javax.sql.rowset CachedRowSet populate.

Prototype

public void populate(ResultSet data) throws SQLException;

Source Link

Document

Populates this CachedRowSet object with data from the given ResultSet object.

Usage

From source file:com.mirth.connect.server.userutil.DatabaseConnection.java

/**
 * Executes an INSERT/UPDATE statement on the database and returns a CachedRowSet containing any
 * generated keys.//  www.  jav a2 s  . c om
 * 
 * @param expression
 *            The statement to be executed.
 * @return A CachedRowSet containing any generated keys.
 * @throws SQLException
 */
public CachedRowSet executeUpdateAndGetGeneratedKeys(String expression) throws SQLException {
    Statement statement = null;

    try {
        statement = connection.createStatement();
        logger.debug("executing update:\n" + expression);
        statement.executeUpdate(expression, Statement.RETURN_GENERATED_KEYS);
        CachedRowSet crs = new MirthCachedRowSet();
        crs.populate(statement.getGeneratedKeys());
        return crs;
    } catch (SQLException e) {
        throw e;
    } finally {
        DbUtils.closeQuietly(statement);
    }
}

From source file:com.mirth.connect.server.userutil.DatabaseConnection.java

/**
 * Executes a query on the database and returns a CachedRowSet.
 * //from   www  . j a va 2 s .  c  o  m
 * @param expression
 *            The query expression to be executed.
 * @return The result of the query, as a CachedRowSet.
 * @throws SQLException
 */
public CachedRowSet executeCachedQuery(String expression) throws SQLException {
    Statement statement = null;

    try {
        statement = connection.createStatement();
        logger.debug("executing query:\n" + expression);
        ResultSet result = statement.executeQuery(expression);
        CachedRowSet crs = new MirthCachedRowSet();
        crs.populate(result);
        DbUtils.closeQuietly(result);
        return crs;
    } catch (SQLException e) {
        throw e;
    } finally {
        DbUtils.closeQuietly(statement);
    }
}

From source file:com.mirth.connect.server.userutil.DatabaseConnection.java

/**
 * Executes a prepared query on the database and returns a CachedRowSet.
 * /*from  w w  w. j a  v a  2 s.com*/
 * @param expression
 *            The prepared statement to be executed.
 * @param parameters
 *            The parameters for the prepared statement.
 * @return The result of the query, as a CachedRowSet.
 * @throws SQLException
 */
public CachedRowSet executeCachedQuery(String expression, List<Object> parameters) throws SQLException {
    PreparedStatement statement = null;

    try {
        statement = connection.prepareStatement(expression);
        logger.debug("executing prepared statement:\n" + expression);

        ListIterator<Object> iterator = parameters.listIterator();

        while (iterator.hasNext()) {
            int index = iterator.nextIndex() + 1;
            Object value = iterator.next();
            logger.debug("adding parameter: index=" + index + ", value=" + value);
            statement.setObject(index, value);
        }

        ResultSet result = statement.executeQuery();
        CachedRowSet crs = new MirthCachedRowSet();
        crs.populate(result);
        DbUtils.closeQuietly(result);
        return crs;
    } catch (SQLException e) {
        throw e;
    } finally {
        DbUtils.closeQuietly(statement);
    }
}

From source file:com.mirth.connect.server.userutil.DatabaseConnection.java

/**
 * Executes a prepared INSERT/UPDATE statement on the database and returns a CachedRowSet
 * containing any generated keys./* www.j a va 2s .  co  m*/
 * 
 * @param expression
 *            The prepared statement to be executed.
 * @param parameters
 *            The parameters for the prepared statement.
 * @return A CachedRowSet containing any generated keys.
 * @throws SQLException
 */
public CachedRowSet executeUpdateAndGetGeneratedKeys(String expression, List<Object> parameters)
        throws SQLException {
    PreparedStatement statement = null;

    try {
        statement = connection.prepareStatement(expression, Statement.RETURN_GENERATED_KEYS);
        logger.debug("executing prepared statement:\n" + expression);

        ListIterator<Object> iterator = parameters.listIterator();

        while (iterator.hasNext()) {
            int index = iterator.nextIndex() + 1;
            Object value = iterator.next();
            logger.debug("adding parameter: index=" + index + ", value=" + value);
            statement.setObject(index, value);
        }

        statement.executeUpdate();
        CachedRowSet crs = new MirthCachedRowSet();
        crs.populate(statement.getGeneratedKeys());
        return crs;
    } catch (SQLException e) {
        throw e;
    } finally {
        DbUtils.closeQuietly(statement);
    }
}

From source file:com.telefonica.iot.cygnus.backends.mysql.MySQLBackendImpl.java

private CachedRowSet select(String dbName, String tableName, String selection)
        throws CygnusRuntimeError, CygnusPersistenceError {
    Statement stmt = null;//w ww .j a  v  a2  s.  c  o m

    // get a connection to the given database
    Connection con = driver.getConnection(dbName);

    try {
        stmt = con.createStatement();
    } catch (SQLException e) {
        closeMySQLObjects(con, stmt);
        throw new CygnusRuntimeError("Querying error", "SQLException", e.getMessage());
    } // try catch

    try {
        // to-do: refactor after implementing
        // https://github.com/telefonicaid/fiware-cygnus/issues/1371
        String query = "select " + selection + " from `" + tableName + "` order by recvTime";
        LOGGER.debug("Executing MySQL query '" + query + "'");
        ResultSet rs = stmt.executeQuery(query);
        // A CachedRowSet is "disconnected" from the source, thus can be
        // used once the statement is closed
        @SuppressWarnings("restriction")
        CachedRowSet crs = new CachedRowSetImpl();

        crs.populate(rs); // FIXME: close Resultset Objects??
        closeMySQLObjects(con, stmt);
        return crs;
    } catch (SQLException e) {
        closeMySQLObjects(con, stmt);
        throw new CygnusPersistenceError("Querying error", "SQLException", e.getMessage());
    } // try catch
}

From source file:net.sf.jasperreports.engine.query.JRJdbcQueryExecuter.java

@Override
public JRDataSource createDatasource() throws JRException {
    JRResultSetDataSource dataSource = null;

    createStatement();//from ww w. j  a va  2  s  .  com

    if (statement != null) {
        try {
            ResultSet queryResult;
            if (isProcedureCall) {
                queryResult = procedureCallHandler.execute();
            } else {
                queryResult = statement.executeQuery();
            }

            if (isCachedRowSet) {
                CachedRowSet cachedRowSet;
                try {
                    Class<? extends CachedRowSet> clazz = (Class<? extends CachedRowSet>) Class
                            .forName(CACHED_ROWSET_CLASS);
                    Constructor<? extends CachedRowSet> constructor = clazz.getConstructor();
                    cachedRowSet = constructor.newInstance();
                } catch (Exception e) {
                    throw new JRException(e);
                }

                cachedRowSet.populate(queryResult);
                closeStatement();
                resultSet = cachedRowSet;
            } else {
                resultSet = queryResult;
            }

            dataSource = new JRResultSetDataSource(getJasperReportsContext(), resultSet);
            dataSource.setTimeZone(fieldsTimeZone, fieldsTimeZoneOverride);

            TimeZone reportTimeZone = (TimeZone) getParameterValue(JRParameter.REPORT_TIME_ZONE, true);
            dataSource.setReportTimeZone(reportTimeZone);
        } catch (SQLTimeoutException e) {
            throw new JRException(EXCEPTION_MESSAGE_KEY_QUERY_STATEMENT_TIMEOUT_LIMIT_EXCEEDED,
                    new Object[] { dataset.getName() }, e);
        } catch (SQLException e) {
            throw new JRException(EXCEPTION_MESSAGE_KEY_QUERY_STATEMENT_EXECUTE_ERROR,
                    new Object[] { dataset.getName() }, e);
        }
    }

    return dataSource;
}

From source file:com.jaspersoft.jasperserver.remote.dbservices.impl.MetaDataServiceImpl.java

/**
 * This method invokes a method ( a total of around 170 odd ) on the DatabaseMetaData object based on 
 * method name and parameters. If the result is a Resultset a CachedRowSet object is populated with 
 * its results and returned. Else all other types are returned as is.
 * @param request/*w w w .j  a v  a2 s  .  co m*/
 * @return
 */

public byte[] getDBMetaData(Resource resource, CachedRowSetWrapper crw) {
    long startTime = System.currentTimeMillis();
    byte[] ret = new byte[0];
    Connection conn = null;
    Method method = null;
    CachedRowSet crs = null;
    Object result = null;
    try {
        if (logger.isDebugEnabled()) {
            logger.debug("Enter getDBMetaData .. Start Time" + System.currentTimeMillis());
        }
        if (crw.getParameters() != null) {
            for (int i = 0; i < crw.getParameters().length; i++) {
                Object param = crw.getParameters()[i];

                //if(param instanceof String && ((String) param).length() == 0){
                if (param instanceof String && StringUtil.isEmpty((String) param)) {
                    crw.getParameters()[i] = null; // make it null
                }
            }
        }
        conn = QueryUtil.getConnection(resource);
        DatabaseMetaData dm = conn.getMetaData();
        method = QueryUtil.findMethod(dm, crw.getRequestId(), crw.getParameters());
        if (null != method) {
            result = method.invoke(dm, crw.getParameters());
            if (null != result) {
                if (result instanceof java.sql.ResultSet) { // got a resultset
                    crs = RowSetProvider.newFactory().createCachedRowSet();
                    crs.populate((ResultSet) result);
                    ((java.sql.ResultSet) result).close(); // close the resultset
                    result = crs;
                }
                if (result instanceof Serializable) {
                    ret = JasperSerializationUtil.serialize((Serializable) result);
                } else {
                    logger.warn("Cannot serialize object" + result.getClass().getName());
                }
            } // if
        } else {
            throw new RemoteException(crw.getRequestId() + " method name is not supported.");
        }
    } catch (Exception ex) {
        logger.error(ex.getMessage(), ex);
        throw new RemoteException("Meta Data fail." + ex.getMessage());
    } finally {
        try {
            if (conn != null)
                conn.close();
            if (crs != null)
                crs.close();
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            throw new RemoteException("Meta Data fail." + ex.getMessage());
        }
        if (logger.isDebugEnabled()) {
            long elapsedTime = System.currentTimeMillis() - startTime;
            logger.debug("Exit getDBMetaData .. Total Time Spent: " + elapsedTime);
        }
    }
    return ret;
}

From source file:com.mirth.connect.connectors.jdbc.DatabaseReceiverQuery.java

@Override
public Object poll() throws DatabaseReceiverException, InterruptedException {
    ResultSet resultSet = null;//  ww w  .j  av  a2  s .c om
    int attempts = 0;
    String channelId = connector.getChannelId();
    String channelName = connector.getChannel().getName();
    int maxRetryCount = NumberUtils
            .toInt(replacer.replaceValues(connectorProperties.getRetryCount(), channelId, channelName), 0);
    int retryInterval = NumberUtils
            .toInt(replacer.replaceValues(connectorProperties.getRetryInterval(), channelId, channelName), 0);
    boolean done = false;
    boolean contextFactoryChanged = false;

    try {
        contextFactoryChanged = checkContextFactory();
    } catch (Exception e) {
        throw new DatabaseReceiverException(e);
    }

    while (!done && !connector.isTerminated()) {
        CachedRowSet cachedRowSet = null;

        try {
            /*
             * If the keepConnectionOpen option is not enabled, we open the database
             * connection(s) here. They will be closed in afterPoll(). Always reset the
             * connection if the connector's context factory has changed.
             */
            if (contextFactoryChanged || !connectorProperties.isKeepConnectionOpen()) {
                initSelectConnection();

                if (connectorProperties.getUpdateMode() == DatabaseReceiverProperties.UPDATE_EACH) {
                    initUpdateConnection();
                }
            }

            int objectIndex = 1;

            /*
             * Using the list of placeholder keys found in the select statement (selectParams),
             * get the corresponding values from JdbcUtils.getParameters() which uses a
             * TemplateValueReplacer to to look up values from a default context based on the
             * given channel id
             */
            for (Object param : JdbcUtils.getParameters(selectParams, connector.getChannelId(),
                    connector.getChannel().getName(), null, null, null)) {
                selectStatement.setObject(objectIndex++, param);
            }

            resultSet = selectStatement.executeQuery();

            // if we are not caching the ResultSet, return it immediately
            if (connectorProperties.isCacheResults()) {
                // if we are caching the ResultSet, convert it into a CachedRowSet and return it
                cachedRowSet = new CachedRowSetImpl();
                cachedRowSet.populate(resultSet);
                DbUtils.closeQuietly(resultSet);
                resultSet = cachedRowSet;
            }

            done = true;
        } catch (SQLException e) {
            DbUtils.closeQuietly(resultSet);
            DbUtils.closeQuietly(cachedRowSet);

            if (attempts++ < maxRetryCount && !connector.isTerminated()) {
                logger.error("An error occurred while polling for messages, retrying after " + retryInterval
                        + " ms...", e);

                // Wait the specified amount of time before retrying
                Thread.sleep(retryInterval);

                if (connectorProperties.isKeepConnectionOpen()
                        && !JdbcUtils.isValidConnection(selectConnection)) {
                    try {
                        initSelectConnection();
                    } catch (SQLException e1) {
                    }
                }
            } else {
                throw new DatabaseReceiverException(e);
            }
        }
    }

    return resultSet;
}

From source file:org.aludratest.cloud.impl.app.LogDatabase.java

/**
 * Runs and populates the given query against the internal Derby database.
 * /*from  w w  w .  ja  v a2 s .  c  o  m*/
 * @param query
 *            SQL query to execute, usually starts with <code>SELECT</code>.
 * 
 * @return A cached row set containing the full results of the query.
 * 
 * @throws SQLException
 *             If a database exception occurs, e.g. invalid query.
 */
public CachedRowSet populateQuery(String query) throws SQLException {
    Connection connection = getConnection();
    Statement stmt = null;
    try {
        stmt = connection.createStatement();
        LOG.debug("Executing QUERY: " + query);
        ResultSet rs = stmt.executeQuery(query);
        LOG.debug("Query execution complete.");

        try {
            CachedRowSet rowSet = (CachedRowSet) Class.forName("com.sun.rowset.CachedRowSetImpl").newInstance();
            rowSet.populate(rs);
            rowSet.beforeFirst();
            return rowSet;
        } catch (SQLException se) {
            throw se;
        } catch (Exception e) {
            throw new SQLException(e);
        }
    } finally {
        closeQuietly(stmt);
        closeQuietly(connection);
    }
}

From source file:org.wso2.carbon.automation.test.utils.dbutils.MySqlDatabaseManager.java

/**
 * @param sql/*from  w  w  w .  jav  a2  s.  com*/
 * @return
 * @throws java.sql.SQLException
 */
public ResultSet executeQuery(String sql) throws SQLException {
    ResultSet rs;
    Statement st = null;
    CachedRowSet cachedRowSet;
    try {
        st = connection.createStatement();
        log.debug(sql);
        rs = st.executeQuery(sql);
        cachedRowSet = new CachedRowSetImpl();
        cachedRowSet.populate(rs);
    } finally {
        if (st != null) {
            st.close();
        }
    }
    return cachedRowSet;
}