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

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

Introduction

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

Prototype

public QueryRunner(DataSource ds) 

Source Link

Document

Constructor for QueryRunner that takes a DataSource to use.

Usage

From source file:com.pinterest.arcee.db.DBImageDAOImpl.java

@Override
public void delete(String amiId) throws Exception {
    new QueryRunner(dataSource).update(DELETE_AMI, amiId);
}

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

@Override
public void update(TokenRolesBean bean, String userName, String resourceId, Resource.Type resourceType)
        throws Exception {
    SetClause setClause = bean.genSetClause();
    String clause = String.format(UPDATE_TEMPLATE, setClause.getClause());
    setClause.addValue(userName);//from   w  ww.jav a  2  s . c  o m
    setClause.addValue(resourceId);
    setClause.addValue(resourceType.toString());
    new QueryRunner(dataSource).update(clause, setClause.getValueArray());
}

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

/**
 * Process the next item in the queue./*from  w w  w.j av a 2  s  .com*/
 */
@SuppressWarnings("nls")
protected void processQueue() {
    try {
        RequestMetric metric = queue.take();
        QueryRunner run = new QueryRunner(ds);

        Calendar cal = Calendar.getInstance();
        cal.setTimeZone(TimeZone.getTimeZone("UTC"));
        cal.setTime(metric.getRequestStart());

        long rstart = cal.getTimeInMillis();
        long rend = metric.getRequestEnd().getTime();
        long duration = metric.getRequestDuration();
        cal.set(Calendar.MILLISECOND, 0);
        cal.set(Calendar.SECOND, 0);
        long minute = cal.getTimeInMillis();
        cal.set(Calendar.MINUTE, 0);
        long hour = cal.getTimeInMillis();
        cal.set(Calendar.HOUR_OF_DAY, 0);
        long day = cal.getTimeInMillis();
        cal.set(Calendar.DAY_OF_WEEK, cal.getFirstDayOfWeek());
        long week = cal.getTimeInMillis();
        cal.set(Calendar.DAY_OF_MONTH, 1);
        long month = cal.getTimeInMillis();
        String api_org_id = metric.getApiOrgId();
        String api_id = metric.getApiId();
        String api_version = metric.getApiVersion();
        String client_org_id = metric.getClientOrgId();
        String client_id = metric.getClientId();
        String client_version = metric.getClientVersion();
        String plan = metric.getPlanId();
        String user_id = metric.getUser();
        String rtype = null;
        if (metric.isFailure()) {
            rtype = "failure";
        } else if (metric.isError()) {
            rtype = "error";
        }
        long bytes_up = metric.getBytesUploaded();
        long bytes_down = metric.getBytesDownloaded();

        // Now insert a row for the metric.
        run.update("INSERT INTO gw_requests (" + "rstart, rend, duration, month, week, day, hour, minute, "
                + "api_org_id, api_id, api_version, " + "client_org_id, client_id, client_version, plan, "
                + "user_id, resp_type, bytes_up, bytes_down) VALUES (" + "?, ?, ?, ?, ?, ?, ?, ?," + "?, ?, ?,"
                + "?, ?, ?, ?," + "?, ?, ?, ?)", rstart, rend, duration, month, week, day, hour, minute,
                api_org_id, api_id, api_version, client_org_id, client_id, client_version, plan, user_id, rtype,
                bytes_up, bytes_down);
    } catch (InterruptedException ie) {
        // This means that the thread was stopped.
    } catch (Exception e) {
        // TODO better logging of this unlikely error
        System.err.println("Error adding metric to database:"); //$NON-NLS-1$
        e.printStackTrace();
        return;
    }
}

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;
    }//w w  w. j  av a  2 s.c  o  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.xeiam.yank.Yank.java

/**
 * Executes a given INSERT SQL prepared statement. Returns the auto-increment id of the inserted row.
 *
 * @param sql The query to execute/* w  ww .j a v  a2 s . c o m*/
 * @param params The replacement parameters
 * @return the auto-increment id of the inserted row, or null if no id is available
 */
public static Long insert(String sql, Object[] params) {

    Long returnLong = null;

    try {
        ResultSetHandler<Long> rsh = new InsertedIDResultSetHandler();
        returnLong = new QueryRunner(YANK_POOL_MANAGER.getDataSource()).insert(sql, rsh, params);
    } catch (SQLException e) {
        handleSQLException(e);
    }

    return returnLong == null ? 0 : returnLong;
}

From source file:com.fluke.data.processor.ReatimeDBReader.java

public List<String> getAllEquity() throws SQLException {
    String sql = "select distinct equity from realtime";
    QueryRunner run = new QueryRunner(DatabaseProperty.getDataSource());
    ResultSetHandler rsh = new ColumnListHandler();
    return (List<String>) run.query(sql, rsh);
}

From source file:com.pinterest.arcee.db.DBNewInstanceReportDAOImpl.java

@Override
public void addNewInstanceReport(String hostId, Long launchTime, Collection<String> envIds) throws Exception {
    StringBuilder names = new StringBuilder("(host_id,env_id,launch_time)");

    StringBuilder sb = new StringBuilder();
    for (String envId : envIds) {
        sb.append("('");
        sb.append(hostId);/*w  ww.j av a 2 s.c o m*/
        sb.append("','");
        sb.append(envId);
        sb.append("',");
        sb.append(launchTime);
        sb.append("),");
    }
    sb.setLength(sb.length() - 1);
    new QueryRunner(dataSource).update(String.format(ADD_NEW_REPORTS, names, sb.toString()), launchTime);
}

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

/**
 * Perform the command.//from   w w w .ja  v  a  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.pinterest.arcee.db.DBSpotAutoScalingDAOImpl.java

@Override
public void deleteAutoScalingGroupFromCluster(String autoScalingGroup) throws Exception {
    new QueryRunner(dataSource).update(DELETE_ASG_BY_NAME, autoScalingGroup);
}

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

@Override
public void removeHostCapacity(String envId, String host) throws Exception {
    new QueryRunner(dataSource).update(DELETE_HOST, host, envId);
}