Example usage for org.apache.commons.dbutils ResultSetHandler ResultSetHandler

List of usage examples for org.apache.commons.dbutils ResultSetHandler ResultSetHandler

Introduction

In this page you can find the example usage for org.apache.commons.dbutils ResultSetHandler ResultSetHandler.

Prototype

ResultSetHandler

Source Link

Usage

From source file:com.pinterest.deployservice.db.SingleResultSetHandlerFactory.java

public static <T> ResultSetHandler<T> newObjectHandler() {
    return new ResultSetHandler<T>() {
        @Override//w  w  w.j a  v  a2s. c  o m
        public T handle(ResultSet resultSet) throws SQLException {
            if (resultSet.next()) {
                return (T) resultSet.getObject(1);
            }
            return null;
        }
    };
}

From source file:com.pinterest.deployservice.db.SingleResultSetHandlerFactory.java

public static <T> ResultSetHandler<List<T>> newListObjectHandler() {
    return new ResultSetHandler<List<T>>() {
        @Override//ww  w .  j a  v  a 2 s  .  c  o  m
        public List<T> handle(ResultSet resultSet) throws SQLException {
            List<T> ret = new ArrayList<T>();
            while (resultSet.next()) {
                ret.add((T) resultSet.getObject(1));
            }
            return ret;
        }
    };
}

From source file:de.iritgo.aktario.jdbc.LoadUser.java

/**
 * Perform the command./*from w  w  w .j a v a  2  s  .  c  o m*/
 */
public void perform() {
    if (properties.get("id") == null) {
        Log.logError("persist", "LoadUser", "Missing unique id for the user to load");

        return;
    }

    long uniqueId = ((Long) properties.get("id")).longValue();

    JDBCManager jdbcManager = (JDBCManager) Engine.instance().getManager("persist.JDBCManager");
    DataSource dataSource = jdbcManager.getDefaultDataSource();

    try {
        QueryRunner query = new QueryRunner(dataSource);
        final User user = (User) query.query("select * from IritgoUser where id=?", new Long(uniqueId),
                new ResultSetHandler() {
                    public Object handle(ResultSet rs) throws SQLException {
                        if (rs.next()) {
                            User user = new User(rs.getString("name"), rs.getString("email"), rs.getInt("id"),
                                    rs.getString("password"), 0);

                            Server.instance().getUserRegistry().addUser(user);
                            Engine.instance().getBaseRegistry().add(user);

                            return user;
                        } else {
                            return null;
                        }
                    }
                });

        if (user == null) {
            Log.logError("persist", "LoadUser", "Unable to find user with id " + uniqueId);

            return;
        }

        Log.logVerbose("persist", "LoadUser",
                "Successfully loaded user " + user.getName() + ":" + user.getUniqueId());
    } catch (SQLException x) {
        Log.logError("persist", "LoadUser", "Error while loading the users: " + x);
    }
}

From source file:io.apiman.gateway.engine.jdbc.JdbcInitializer.java

/**
 * Do the initialization work.//  w  ww.j  a va2  s  .c o m
 */
@SuppressWarnings("nls")
private void doInit() {
    QueryRunner run = new QueryRunner(ds);
    Boolean isInitialized;

    try {
        isInitialized = run.query("SELECT * FROM gw_apis", new ResultSetHandler<Boolean>() {
            @Override
            public Boolean handle(ResultSet rs) throws SQLException {
                return true;
            }
        });
    } catch (SQLException e) {
        isInitialized = false;
    }

    if (isInitialized) {
        System.out.println("============================================");
        System.out.println("Apiman Gateway database already initialized.");
        System.out.println("============================================");
        return;
    }

    ClassLoader cl = JdbcInitializer.class.getClassLoader();
    URL resource = cl.getResource("ddls/apiman-gateway_" + dbType + ".ddl");
    try (InputStream is = resource.openStream()) {
        System.out.println("=======================================");
        System.out.println("Initializing apiman Gateway database.");
        DdlParser ddlParser = new DdlParser();
        List<String> statements = ddlParser.parse(is);
        for (String sql : statements) {
            System.out.println(sql);
            run.update(sql);
        }
        System.out.println("=======================================");
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.dianping.puma.parser.meta.DefaultTableMetaInfoFetcher.java

protected TableMetaInfo _refreshTableMeta(final String database, final String table) throws SQLException {
    initDsIfNeeded();/*  w  w  w  .  j a v  a  2s . c  o m*/

    QueryRunner runner = new QueryRunner(metaDs);

    Transaction t = Cat.newTransaction("SQL.meta", getKey(database, table));
    try {
        TableMetaInfo tableMetaInfo = runner.query(genTableMetaSql(database, table),
                new ResultSetHandler<TableMetaInfo>() {
                    @Override
                    public TableMetaInfo handle(ResultSet rs) throws SQLException {
                        TableMetaInfo result = new TableMetaInfo();
                        result.setDatabase(database);
                        result.setTable(table);
                        result.setColumns(new HashMap<Integer, String>());
                        result.setKeys(new ArrayList<String>());
                        result.setTypes(new HashMap<String, String>());
                        result.setSignedInfos(new HashMap<Integer, Boolean>());

                        while (rs.next()) {
                            int i = rs.getRow();
                            String column = rs.getString("Field");

                            result.getColumns().put(i, column);

                            if (rs.getString("Type").contains("unsigned")) {
                                result.getSignedInfos().put(i, false);
                            } else {
                                result.getSignedInfos().put(i, true);
                            }

                            if (rs.getString("Key").equalsIgnoreCase("pri")) {
                                result.getKeys().add(column);
                            }
                        }

                        return result;
                    }
                });

        t.setStatus("0");
        return tableMetaInfo;
    } catch (SQLException e) {
        t.setStatus("1");
        throw e;
    } finally {
        t.complete();
    }
}

From source file:hermes.store.schema.DefaultJDBCAdapter.java

public Collection<String> getStores(Connection connection) throws SQLException {
    final QueryRunner runner = new QueryRunner();
    final ArrayList<String> stores = new ArrayList<String>();

    Hermes.ui.getDefaultMessageSink().add("Getting message stores....");

    runner.query(connection, statements.getStoresStatement(), new ResultSetHandler() {
        public Object handle(ResultSet rs) throws SQLException {
            while (rs.next()) {
                stores.add(rs.getString(1));
            }/*from w ww  . ja v  a2s .c  om*/
            return stores;
        }
    });

    Hermes.ui.getDefaultMessageSink().add("Getting message stores.... done.");

    return stores;
}

From source file:gr.osmosis.rcpsamples.contact.db.derby.DerbyContactsDAO.java

public Contact[] selectContacts(int id) {
    // Create Query
    // and where statement
    String whereStatement = "";
    if (id > -1) {
        whereStatement = " WHERE ID = " + id;
    }/*from  w  w w .  j a  v a 2 s  .  co m*/

    StringBuffer sbSelect = new StringBuffer();
    sbSelect.append("SELECT * ");
    sbSelect.append(" FROM ");
    sbSelect.append(ContactsConstants.CONTACTS_TABLE_NAME);
    sbSelect.append(whereStatement);

    // Create a QueryRunner that will use connections from
    // the given DataSource
    DataSource d = DerbyDAOFactory.getDataSource();
    QueryRunner run = new QueryRunner(d);

    ResultSetHandler h = new ResultSetHandler() {
        public Object handle(ResultSet rs) throws SQLException {

            BasicRowProcessor p = new BasicRowProcessor();

            List l = p.toBeanList(rs, Contact.class);

            return l;
        }
    };
    Object result;
    ArrayList list;
    Contact[] c = null;
    try {
        result = run.query(sbSelect.toString(), h);

        list = (ArrayList) result;

        c = new Contact[list.toArray().length];
        list.toArray(c);

        System.out.print(result.toString());

    } catch (SQLException sex) {
        sex.printStackTrace();
    } catch (Exception ex) {
        ex.printStackTrace();
    }

    return c;
}

From source file:com.itdaoshi.discuz.dao.CdbUcMembersDAObject.java

@Override
protected Long getNextPrimaryID() {
    QueryRunner run = new QueryRunner();
    ResultSetHandler h = new ResultSetHandler() {
        public Object handle(ResultSet rs) throws SQLException {
            if (!rs.next()) {
                return null;
            }//from w w w  .ja v  a2 s. c  o m

            ResultSetMetaData meta = rs.getMetaData();
            int cols = meta.getColumnCount();
            Object[] result = new Object[cols];

            for (int i = 0; i < cols; i++) {
                result[i] = rs.getObject(i + 1);
            }

            return result;
        }
    };
    try {
        Object[] result = (Object[]) run.query(conn, "SELECT MAX(uid) FROM CDB_UC_MEMBERS ", h);
        return (Long) result[0] + 1;
        // do something with the result
    } catch (Exception e) {
        e.printStackTrace();

    }

    return null;
}

From source file:de.iritgo.aktario.jdbc.LoadAllObjects.java

/**
 * Perform the command.// w  w  w. ja  va  2 s.  co  m
 */
public void perform() {
    if (properties.getProperty("type") == null) {
        Log.logError("persist", "LoadObjects", "The type of the objects to load wasn't specified");

        return;
    }

    final String type = ((String) properties.getProperty("type"));

    final AbstractIObjectFactory factory = (AbstractIObjectFactory) Engine.instance().getIObjectFactory();

    IObject sample = null;

    try {
        sample = factory.newInstance(type);
    } catch (NoSuchIObjectException ignored) {
        Log.logError("persist", "LoadObjects", "Attemting to load objects of unknown type '" + type + "'");

        return;
    }

    if (!DataObject.class.isInstance(sample)) {
        Log.logError("persist", "LoadObjects", "Attemting to load objects that are not persitable");

        return;
    }

    final BaseRegistry registry = Engine.instance().getBaseRegistry();

    JDBCManager jdbcManager = (JDBCManager) Engine.instance().getManager("persist.JDBCManager");
    DataSource dataSource = jdbcManager.getDefaultDataSource();

    try {
        QueryRunner query = new QueryRunner(dataSource);

        ResultSetHandler resultSetHandler = properties.get("resultSetHandle") != null
                ? (ResultSetHandler) properties.get("resultSetHandler")
                : new ResultSetHandler() {
                    public Object handle(ResultSet rs) throws SQLException {
                        ResultSetMetaData meta = rs.getMetaData();

                        int numObjects = 0;

                        while (rs.next()) {
                            try {
                                DataObject object = (DataObject) factory.newInstance(type);

                                object.setUniqueId(rs.getLong("id"));

                                for (Iterator i = object.getAttributes().entrySet().iterator(); i.hasNext();) {
                                    Map.Entry attribute = (Map.Entry) i.next();

                                    if (attribute.getValue() instanceof IObjectList) {
                                        //                               loadList (
                                        //                                  dataSource, object,
                                        //                                  object.getIObjectListAttribute (
                                        //                                     (String) attribute.getKey ()));
                                    } else {
                                        object.setAttribute((String) attribute.getKey(),
                                                rs.getObject((String) attribute.getKey()));
                                    }
                                }

                                registry.add(object);
                                ++numObjects;
                            } catch (NoSuchIObjectException ignored) {
                            }
                        }

                        return new Integer(numObjects);
                    }
                };

        Object numObjects = query.query("select * from " + type, resultSetHandler);

        Log.logVerbose("persist", "LoadObjects",
                "Successfully loaded " + numObjects + " objects of type '" + type + "'");
    } catch (Exception x) {
        Log.logError("persist", "LoadObjects", "Error while loading objects of type '" + type + "': " + x);
    }
}

From source file:com.pymmasoftware.platform.login.loginmodule.DroolsLoginModule.java

@Override
public boolean login() throws LoginException {
    succeeded = false;//  ww  w  . j  av a 2 s  .com
    QueryRunner queryRunner = null;
    try {
        userPrincipal = null;
        roles = null;
        if (callbackHandler == null)
            throw new LoginException("No callback handler");

        NameCallback nameCallback = new NameCallback("Username");
        PasswordCallback passwordCallback = new PasswordCallback("Password", false);

        Callback[] callbacks = new Callback[] { nameCallback, passwordCallback };
        try {
            callbackHandler.handle(callbacks);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (UnsupportedCallbackException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        username = nameCallback.getName();
        password = new String(passwordCallback.getPassword());

        queryRunner = new QueryRunner(dataSource);

        // Create a ResultSetHandler implementation to convert the
        // first row into an Object[].
        ResultSetHandler<DroolsPrincipal> h = new ResultSetHandler<DroolsPrincipal>() {
            public DroolsPrincipal handle(ResultSet rs) throws SQLException {
                if (!rs.next()) {
                    return null;
                }

                ResultSetMetaData meta = rs.getMetaData();
                String userName = rs.getString("username");

                DroolsPrincipal droolsPrincipal = new DroolsPrincipal(userName);
                droolsPrincipal.setId(rs.getInt("id"));

                return droolsPrincipal;
            }
        };
        ResultSetHandler<List<String>> hh = new ResultSetHandler<List<String>>() {
            public List<String> handle(ResultSet rs) throws SQLException {
                if (!rs.next()) {
                    return null;
                }
                List<String> droolsGroups = new ArrayList<>();
                boolean goOne = true;
                while (goOne) {
                    String groupName = rs.getString("groups");

                    droolsGroups.add(groupName);
                    if (rs.next() == false) {
                        goOne = false;
                    }
                }
                return droolsGroups;
            }
        };

        String sqlname = "select * from guvnorusers where username = ? and password = ? ";
        DroolsPrincipal user = queryRunner.query(sqlname, h, username, password);
        if (user == null) {
            succeeded = false;
            throw new FailedLoginException("The username or The password is incorrect");
        } else {

            userPrincipal = user;
            String sqlname2 = "select groups from guvnorgroups gr,guvnorusers_groups gr_user "
                    + "where gr.id = gr_user.groups_id  " + "and gr_user.guvnorusers_id= ?";
            List<String> droolsGroups = queryRunner.query(sqlname2, hh, user.getId());
            if (droolsGroups != null) {
                int i = droolsGroups.size();
                roles = new String[i];
                i = 0;
                for (String droolsGroup : droolsGroups) {
                    roles[i] = droolsGroup;
                    i++;
                }
            }
            succeeded = true;
            return true;
        }

    } catch (Exception e) {
        throw new LoginException(e.getMessage());
    } finally {
        queryRunner = null;
    }

}