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() 

Source Link

Document

Constructor for QueryRunner.

Usage

From source file:azkaban.trigger.JdbcTriggerLoader.java

private synchronized void addTrigger(Connection connection, Trigger t, EncodingType encType)
        throws TriggerLoaderException {

    QueryRunner runner = new QueryRunner();

    long id;/*from   ww  w  . j av  a2s . c o  m*/

    try {
        runner.update(connection, ADD_TRIGGER, DateTime.now().getMillis());
        connection.commit();
        id = runner.query(connection, LastInsertID.LAST_INSERT_ID, new LastInsertID());

        if (id == -1L) {
            logger.error("trigger id is not properly created.");
            throw new TriggerLoaderException("trigger id is not properly created.");
        }

        t.setTriggerId((int) id);
        updateTrigger(t);
        logger.info("uploaded trigger " + t.getDescription());
    } catch (SQLException e) {
        throw new TriggerLoaderException("Error creating trigger.", e);
    }

}

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

/**
 * Stores a "dataversion" record in the ES store.  There is only a single one of these.  The
 * return value of the add will include the version number of the entity.  This version
 * number is what we use to determine whether our cache is stale.
 *//*  w  w  w.  j  a  v  a  2s  .c o m*/
protected void updateDataVersion() {
    Connection conn = null;
    try {
        long newVersion = System.currentTimeMillis();

        conn = ds.getConnection();
        conn.setAutoCommit(false);
        QueryRunner run = new QueryRunner();

        run.update(conn, "DELETE FROM gw_dataversion"); //$NON-NLS-1$
        run.update(conn, "INSERT INTO gw_dataversion (version) VALUES (?)", //$NON-NLS-1$
                newVersion);

        DbUtils.commitAndClose(conn);
        dataVersion = newVersion;
    } catch (SQLException e) {
        dataVersion = -1;
    }
}

From source file:azkaban.executor.JdbcExecutorLoaderTest.java

@After
public void clearDB() {
    if (!testDBExists) {
        return;/*w  w  w .j av  a 2s.  co m*/
    }

    DataSource dataSource = DataSourceUtils.getMySQLDataSource(host, port, database, user, password,
            numConnections);
    Connection connection = null;
    try {
        connection = dataSource.getConnection();
    } catch (SQLException e) {
        e.printStackTrace();
        testDBExists = false;
        DbUtils.closeQuietly(connection);
        return;
    }

    QueryRunner runner = new QueryRunner();
    try {
        runner.update(connection, "DELETE FROM active_executing_flows");

    } catch (SQLException e) {
        e.printStackTrace();
        testDBExists = false;
        DbUtils.closeQuietly(connection);
        return;
    }

    try {
        runner.update(connection, "DELETE FROM execution_flows");
    } catch (SQLException e) {
        e.printStackTrace();
        testDBExists = false;
        DbUtils.closeQuietly(connection);
        return;
    }

    try {
        runner.update(connection, "DELETE FROM execution_jobs");
    } catch (SQLException e) {
        e.printStackTrace();
        testDBExists = false;
        DbUtils.closeQuietly(connection);
        return;
    }

    try {
        runner.update(connection, "DELETE FROM execution_logs");
    } catch (SQLException e) {
        e.printStackTrace();
        testDBExists = false;
        DbUtils.closeQuietly(connection);
        return;
    }

    try {
        runner.update(connection, "DELETE FROM executors");
    } catch (SQLException e) {
        e.printStackTrace();
        testDBExists = false;
        DbUtils.closeQuietly(connection);
        return;
    }

    try {
        runner.update(connection, "DELETE FROM executor_events");
    } catch (SQLException e) {
        e.printStackTrace();
        testDBExists = false;
        DbUtils.closeQuietly(connection);
        return;
    }

    DbUtils.closeQuietly(connection);
}

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

public void remove(Connection connection, String storeId, String destination)
        throws SQLException, JMSException {
    final QueryRunner runner = new QueryRunner();

    if (runner.update(connection,
            "delete from messages where messageid in (select messageid from stores where storeid=? and destination=?)",
            new Object[] { storeId, destination }) > 0) {
        runner.update(connection, "delete from stores where storeid=? and destination=?",
                new Object[] { storeId, destination });
    }//from   w  w  w.j a  va 2  s . co m
}

From source file:azkaban.executor.JdbcExecutorLoader.java

private void updateExecutableFlow(Connection connection, ExecutableFlow flow, EncodingType encType)
        throws ExecutorManagerException {
    final String UPDATE_EXECUTABLE_FLOW_DATA = "UPDATE execution_flows "
            + "SET status=?,update_time=?,start_time=?,end_time=?,enc_type=?,flow_data=? " + "WHERE exec_id=?";
    QueryRunner runner = new QueryRunner();

    String json = JSONUtils.toJSON(flow.toObject());
    byte[] data = null;
    try {/*from   www.  j a  v  a 2 s .  c o m*/
        byte[] stringData = json.getBytes("UTF-8");
        data = stringData;

        if (encType == EncodingType.GZIP) {
            data = GZIPUtils.gzipBytes(stringData);
        }
    } catch (IOException e) {
        throw new ExecutorManagerException("Error encoding the execution flow.");
    }

    try {
        runner.update(connection, UPDATE_EXECUTABLE_FLOW_DATA, flow.getStatus().getNumVal(),
                flow.getUpdateTime(), flow.getStartTime(), flow.getEndTime(), encType.getNumVal(), data,
                flow.getExecutionId());
        connection.commit();
    } catch (SQLException e) {
        throw new ExecutorManagerException("Error updating flow.", e);
    }
}

From source file:com.netflix.metacat.usermetadata.mysql.MySqlLookupService.java

/**
 * Returns the list of values of the lookup name.
 * @param name lookup name// w  ww  .  ja  v  a 2  s  . c  o  m
 * @return list of lookup values
 */
@Override
public Set<String> getValues(final String name) {
    final Connection connection = DBUtil.getReadConnection(getDataSource());
    try {
        return new QueryRunner().query(connection, SQL_GET_LOOKUP_VALUES_BY_NAME, rs -> {
            final Set<String> result = Sets.newHashSet();
            while (rs.next()) {
                result.add(rs.getString("value"));
            }
            return result;
        }, name);
    } catch (Exception e) {
        final String message = String.format("Failed to get the lookup values for name %s", name);
        log.error(message, e);
        throw new UserMetadataServiceException(message, e);
    } finally {
        DBUtil.closeReadConnection(connection);
    }
}

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

/**
 * Ensures that the api referenced by the Contract actually exists (is published).
 * @param contract/* w  ww  . ja va  2s. c om*/
 * @param connection
 * @throws RegistrationException
 */
private void validateContract(final Contract contract, Connection connection) throws RegistrationException {
    QueryRunner run = new QueryRunner();
    try {
        Api api = run.query(connection, "SELECT bean FROM gw_apis WHERE org_id = ? AND id = ? AND version = ?", //$NON-NLS-1$
                Handlers.API_HANDLER, contract.getApiOrgId(), contract.getApiId(), contract.getApiVersion());
        if (api == null) {
            String apiId = contract.getApiId();
            String orgId = contract.getApiOrgId();
            throw new RegistrationException(
                    Messages.i18n.format("JdbcRegistry.ApiNotFoundInOrg", apiId, orgId)); //$NON-NLS-1$
        }
    } catch (SQLException e) {
        throw new RegistrationException(Messages.i18n.format("JdbcRegistry.ErrorValidatingApp"), e); //$NON-NLS-1$
    }
}

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

public void doDispatch(UMOEvent event) throws Exception {
    monitoringController.updateStatus(connector, connectorType, Event.BUSY);

    if (logger.isDebugEnabled()) {
        logger.debug("Dispatch event: " + event);
    }//  w w w  . j  a  va 2  s . c om

    Connection connection = null;
    MessageObject messageObject = messageObjectController.getMessageObjectFromEvent(event);

    if (messageObject == null) {
        return;
    }

    try {
        // execute the database script if selected
        if (connector.isUseScript()) {
            Context context = Context.enter();
            Scriptable scope = new ImporterTopLevel(context);

            // load variables in JavaScript scope
            JavaScriptScopeUtil.buildScope(scope, messageObject, scriptLogger);

            // get the script from the cache and execute it
            Script compiledScript = compiledScriptCache.getCompiledScript(this.connector.getScriptId());

            if (compiledScript == null) {
                logger.warn("Database script could not be found in cache");
                messageObjectController.setError(messageObject, Constants.ERROR_406,
                        "Database script not found in cache", null, null);
            } else {
                compiledScript.exec(context, scope);
                String response = "Database write success";

                // the user could write Javascript that sets the response
                // for this connector
                // if that's the case, then let's save it
                if (messageObject.getResponseMap().containsKey(messageObject.getConnectorName())) {
                    response = (String) messageObject.getResponseMap().get(messageObject.getConnectorName());
                }

                messageObjectController.setSuccess(messageObject, response, null);
            }
        } else {
            // otherwise run the SQL insert/update/delete statement
            UMOEndpoint endpoint = event.getEndpoint();
            UMOEndpointURI endpointURI = endpoint.getEndpointURI();
            String writeStmt = endpointURI.getAddress();
            String str;

            if ((str = connector.getQuery(endpoint, writeStmt)) != null) {
                writeStmt = str;
            }

            writeStmt = JdbcUtils.stripSqlComments(writeStmt);

            if (writeStmt == null) {
                throw new IllegalArgumentException("Write statement should not be NULL");
            } else if (!writeStmt.toLowerCase().startsWith("insert")
                    && !writeStmt.toLowerCase().startsWith("update")
                    && !writeStmt.toLowerCase().startsWith("delete")) {
                throw new IllegalArgumentException(
                        "Write statement should be an INSERT, UPDATE, or DELETE SQL statement.");
            }

            List<String> paramNames = new ArrayList<String>();
            writeStmt = JdbcUtils.parseStatement(writeStmt, paramNames);
            Object[] paramValues = JdbcUtils.getParams(endpointURI, paramNames, messageObject);
            connection = connector.getConnection(messageObject);

            int numRows = -1;
            try {
                numRows = new QueryRunner().update(connection, writeStmt, paramValues);
            } catch (SQLException e) {
                // If the connection was closed, get a new connection and
                // try again
                if (connection.isClosed()) {
                    connection = connector.getConnection(messageObject);
                    numRows = new QueryRunner().update(connection, writeStmt, paramValues);
                } else {
                    throw e;
                }
            }

            JdbcUtils.commitAndClose(connection);
            messageObjectController.setSuccess(messageObject,
                    "Database write success, " + numRows + " rows updated", null);
            logger.debug("Event dispatched succesfuly");
        }
    } catch (Exception e) {
        logger.debug("Error dispatching event", e);
        JdbcUtils.rollbackAndClose(connection);
        alertController.sendAlerts(connector.getChannelId(), Constants.ERROR_406, "Error writing to database",
                e);
        messageObjectController.setError(messageObject, Constants.ERROR_406, "Error writing to database: ", e,
                null);
        connector.handleException(e);
    } finally {
        monitoringController.updateStatus(connector, connectorType, Event.DONE);
    }
}

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

public void remove(Connection connection, String storeId, Message message) throws SQLException, JMSException {
    final QueryRunner runner = new QueryRunner();

    if (runner.update(connection, "delete from stores where storeid=? and messageid=?",
            new Object[] { storeId, message.getJMSMessageID() }) > 0) {
        runner.update(connection, "delete from messages where messageid=?",
                new Object[] { message.getJMSMessageID() });
    } else {//from  w w  w  .ja v  a  2 s. co m
        throw new SQLException("No message id=" + message.getJMSMessageID() + " exists in store=" + storeId);
    }
}

From source file:com.netflix.metacat.usermetadata.mysql.MySqlTagService.java

/**
 * Returns the TagItem for the given <code>name</code>.
 * @param name tag name/*from   w ww. j  ava2 s  .c o m*/
 * @return TagItem
 */
public TagItem get(final String name) {
    TagItem result = null;
    final Connection connection = DBUtil.getReadConnection(getDataSource());
    try {
        final ResultSetHandler<TagItem> handler = new BeanHandler<>(TagItem.class);
        result = new QueryRunner().query(connection, SQL_GET_TAG_ITEM, handler, name);
        if (result != null) {
            result.setValues(getValues(result.getId()));
        }
    } catch (Exception e) {
        final String message = String.format("Failed to get the tag item for name %s", name);
        log.error(message, e);
        throw new UserMetadataServiceException(message, e);
    } finally {
        DBUtil.closeReadConnection(connection);
    }
    return result;
}