Example usage for org.apache.commons.dbutils DbUtils rollbackAndCloseQuietly

List of usage examples for org.apache.commons.dbutils DbUtils rollbackAndCloseQuietly

Introduction

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

Prototype

public static void rollbackAndCloseQuietly(Connection conn) 

Source Link

Document

Performs a rollback on the Connection then closes it, avoid closing if null and hide any SQLExceptions that occur.

Usage

From source file:jp.co.golorp.emarf.sql.Connections.java

/**
 * ?/*from  w  w  w  .j av  a 2 s  .  com*/
 */
public static void rollback() {
    Connection cn = threadLocalConnection.get();
    LOG.debug("rollback connection.");
    DbUtils.rollbackAndCloseQuietly(cn);
}

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

/**
 * @see io.apiman.gateway.engine.IRegistry#registerClient(io.apiman.gateway.engine.beans.Client, io.apiman.gateway.engine.async.IAsyncResultHandler)
 */// w w  w. ja  v a2s.c  om
@Override
public void registerClient(Client client, IAsyncResultHandler<Void> handler) {
    Connection conn = null;
    try {
        conn = ds.getConnection();
        conn.setAutoCommit(false);
        QueryRunner run = new QueryRunner();

        // Validate the client and populate the api map with apis found during validation.
        validateClient(client, conn);

        // Remove any old data first, then (re)insert
        run.update(conn, "DELETE FROM gw_clients WHERE org_id = ? AND id = ? AND version = ?", //$NON-NLS-1$
                client.getOrganizationId(), client.getClientId(), client.getVersion());

        String bean = mapper.writeValueAsString(client);
        run.update(conn, "INSERT INTO gw_clients (api_key, org_id, id, version, bean) VALUES (?, ?, ?, ?, ?)", //$NON-NLS-1$
                client.getApiKey(), client.getOrganizationId(), client.getClientId(), client.getVersion(),
                bean);

        DbUtils.commitAndClose(conn);
        handler.handle(AsyncResultImpl.create((Void) null));
    } catch (Exception re) {
        DbUtils.rollbackAndCloseQuietly(conn);
        handler.handle(AsyncResultImpl.create(re, Void.class));
    }
}

From source file:nl.b3p.catalog.arcgis.ArcSDE9xJDBCHelper.java

@Override
public void saveMetadata(ArcSDEJDBCDataset dataset, String metadata) throws Exception {
    Connection c = getConnection();
    PreparedStatement ps = null;/*  www .j  av a 2s . com*/
    try {
        c.setAutoCommit(false);

        // gebruik geen DbUtils; setBinaryStream() werkt niet met setObject()
        // welke DbUtils gebruikt

        String sql = "update " + getTableName(TABLE_USERMETADATA) + " set xml = ? where name = ? and owner = ?";
        sql += databaseNameSQL(dataset);
        ps = c.prepareStatement(sql);
        byte[] xml = metadata.getBytes(ENCODING);
        ps.setBinaryStream(1, new ByteArrayInputStream(xml), xml.length);
        ps.setString(2, dataset.getName());
        ps.setString(3, dataset.getOwner());
        if (dataset.getDatabaseName() != null) {
            ps.setString(4, dataset.getDatabaseName());
        }
        int rowsAffected = ps.executeUpdate();
        ps.close();
        ps = null;

        if (rowsAffected > 1) {
            throw new Exception("Updating metadata should affect maximum one row; got rows affected count of "
                    + rowsAffected);
        }

        if (rowsAffected == 0) {
            // try to insert new row

            QueryRunner runner = new QueryRunner();

            // determine highest id
            Object id = runner.query(c, "select coalesce(max(id)+1,1) from " + getTableName(TABLE_USERMETADATA),
                    new ScalarHandler());

            Integer datasetType = determineDatasetType(c, dataset);

            // weer setBinaryStream nodig
            ps = c.prepareStatement("insert into " + getTableName(TABLE_USERMETADATA)
                    + " (id, databasename, owner, name, datasettype, xml) values(?,?,?,?,?,?)");
            ps.setObject(1, id);
            ps.setObject(2, dataset.getDatabaseName());
            ps.setString(3, dataset.getOwner());
            ps.setString(4, dataset.getName());
            ps.setObject(5, datasetType);
            ps.setBinaryStream(6, new ByteArrayInputStream(xml), xml.length);
            ps.executeUpdate();
            ps.close();
            ps = null;
        }

        DbUtils.commitAndClose(c);
    } catch (Exception e) {
        DbUtils.rollbackAndCloseQuietly(c);
        throw e;
    } finally {
        DbUtils.closeQuietly(ps);
    }
}

From source file:org.gaixie.jibu.JibuTestSupport.java

/**
 * ????//w w  w  .  j a v a2  s .  c om
 * ??
 */
protected void clearTable() {
    Connection conn = null;
    try {
        conn = ConnectionUtils.getConnection();
        QueryRunner run = new QueryRunner();
        run.update(conn, "DELETE from schema_changes");
        DbUtils.commitAndClose(conn);
    } catch (SQLException e) {
        DbUtils.rollbackAndCloseQuietly(conn);
        System.out.println(e.getMessage());
    }
}

From source file:org.gaixie.jibu.security.dao.SchemaCreate.java

/**
 * ?? dbscripts ? type???? sql /*w w  w  . j a va  2s.c o m*/
 * <p>
 * @param type ? jibu.properties ?
 */
public void create(String type) {
    Connection conn = null;
    try {
        conn = ConnectionUtils.getConnection();
        DatabaseMetaData dbm = conn.getMetaData();

        ResultSet rs = dbm.getTables(null, null, "USERBASE", null);
        if (rs.next())
            throw new SQLException("Schema has been created!");

        String dpn = dbm.getDatabaseProductName();
        if (!"Apache Derby".equals(dpn))
            throw new SQLException("Database is not Apache Derby!");
        QueryRunner run = new QueryRunner();
        URL url = this.getClass().getResource("/dbscripts/" + type + "/");
        File dir = new File(url.toURI());
        File[] files = dir.listFiles();
        Arrays.sort(files);
        for (File file : files) {
            if (file.isFile()) {
                handleFile(run, conn, "/dbscripts/" + type + "/" + file.getName());
            }
        }
        DbUtils.commitAndClose(conn);
    } catch (SQLException se) {
        DbUtils.rollbackAndCloseQuietly(conn);
        logger.warn("Schema create failed: " + se.getMessage());
    } catch (IOException ie) {
        DbUtils.rollbackAndCloseQuietly(conn);
        logger.warn("Read SQL Scripts failed: " + ie.getMessage());
    } catch (URISyntaxException e) {
        DbUtils.rollbackAndCloseQuietly(conn);
        logger.warn("Get SQL Scripts Directory failed: " + e.getMessage());
    }
}

From source file:org.gaixie.jibu.security.service.AuthorityServiceTest.java

@After
public void tearDown() {
    Connection conn = null;/*from w  w w.  j  av  a2 s .c o m*/
    try {
        conn = ConnectionUtils.getConnection();
        QueryRunner run = new QueryRunner();
        run.update(conn, "DELETE from role_authority_map ");
        run.update(conn, "DELETE from user_role_map");
        run.update(conn, "DELETE from roles");
        run.update(conn, "DELETE from authorities ");
        run.update(conn, "DELETE from userbase");
        DbUtils.commitAndClose(conn);
    } catch (SQLException e) {
        DbUtils.rollbackAndCloseQuietly(conn);
        System.out.println(e.getMessage());
    }
}

From source file:org.gaixie.jibu.security.service.impl.AuthorityServiceImpl.java

/**
 * {@inheritDoc}//from   w  w  w  .jav  a2s . c  o  m
 * <p>
 * ? Cache  authorities  value
 * @see #getAll()
 */
public void add(Authority auth) throws JibuException {
    Connection conn = null;
    try {
        conn = ConnectionUtils.getConnection();
        authDAO.save(conn, auth);
        DbUtils.commitAndClose(conn);
        Cache cache = CacheUtils.getAuthCache();
        cache.remove("authorities");
    } catch (SQLException e) {
        DbUtils.rollbackAndCloseQuietly(conn);
        throw new JibuException(e.getMessage());
    }
}

From source file:org.gaixie.jibu.security.service.impl.AuthorityServiceImpl.java

/**
 * {@inheritDoc}//from w  ww. j a va 2  s.c om
 * <p>
 * ? Cache  authorities  value
 * @see #getAll()
 */
public void delete(Authority auth) throws JibuException {
    Connection conn = null;
    try {
        conn = ConnectionUtils.getConnection();
        authDAO.delete(conn, auth);
        DbUtils.commitAndClose(conn);
        Cache cache = CacheUtils.getAuthCache();
        cache.remove("authorities");
    } catch (SQLException e) {
        DbUtils.rollbackAndCloseQuietly(conn);
        throw new JibuException(e.getMessage());
    }
}

From source file:org.gaixie.jibu.security.service.impl.AuthorityServiceImpl.java

/**
 * {@inheritDoc}/*ww w .  j  a  v  a 2s .  c  om*/
 * <p>
 * ? Cache  authorities  value 
 * key = auth.getValue() ?
 * @see #getAll()
 */
public void update(Authority auth) throws JibuException {
    Connection conn = null;
    try {
        conn = ConnectionUtils.getConnection();
        Authority old = authDAO.get(conn, auth.getId());
        authDAO.update(conn, auth);
        DbUtils.commitAndClose(conn);
        Cache cache = CacheUtils.getAuthCache();
        cache.remove("authorities");
        cache.remove(old.getValue());
    } catch (SQLException e) {
        DbUtils.rollbackAndCloseQuietly(conn);
        throw new JibuException(e.getMessage());
    }
}

From source file:org.gaixie.jibu.security.service.impl.LoginServiceImpl.java

public Token generateToken(String username) {
    Connection conn = null;/*from w  ww .  ja va  2 s  . c  om*/
    Token token = null;
    try {
        conn = ConnectionUtils.getConnection();
        User user = userDAO.get(conn, username);
        if (user == null)
            return null;

        Random randomGenerator = new Random();
        long randomLong = randomGenerator.nextLong();

        //            Date date = new Date();
        Calendar calendar = Calendar.getInstance();
        //calendar.setTime(date);
        calendar.add(calendar.DAY_OF_MONTH, +1);
        long time = calendar.getTimeInMillis();
        Timestamp ts = new Timestamp(time);
        String key = MD5.encodeString(Long.toString(randomLong) + time, null);
        token = new Token(key, "password", ts, user.getId());

        tokenDAO.save(conn, token);
        DbUtils.commitAndClose(conn);
    } catch (SQLException e) {
        DbUtils.rollbackAndCloseQuietly(conn);
        logger.error(e.getMessage());
        return null;
    } finally {
        DbUtils.closeQuietly(conn);
    }
    return token;
}