Example usage for org.hibernate Session doWork

List of usage examples for org.hibernate Session doWork

Introduction

In this page you can find the example usage for org.hibernate Session doWork.

Prototype

void doWork(Work work) throws HibernateException;

Source Link

Document

Controller for allowing users to perform JDBC related work using the Connection managed by this Session.

Usage

From source file:com.oliveira.pedidovenda.controller.RelatorioPedidoClienteBean.java

public void emitir() {
    Map<String, Object> parametros = new HashMap<>();
    parametros.put("numeropedido", this.numeroPedido);

    ExecutorRelatorio executor = new ExecutorRelatorio("/relatorios/rel_cliente_pedido.jasper", this.response,
            parametros, "Pedidos emitidos.pdf");

    Session session = manager.unwrap(Session.class);
    session.doWork(executor);

    if (executor.isRelatorioGerado()) {
        facesContext.responseComplete();
    } else {/* w  w w.ja va 2s.c o  m*/
        FacesUtil.addErrorMessage("A execuo do relatrio no retornou dados.");
    }
}

From source file:com.openkm.dao.HibernateUtil.java

License:Open Source License

/**
 * Load specific database import//from  w w  w .j a  va  2  s  .c  o  m
 */
public static void executeSentences(final Reader rd) {
    Session session = null;
    Transaction tx = null;

    try {
        session = sessionFactory.openSession();
        tx = session.beginTransaction();

        session.doWork(new Work() {
            @Override
            public void execute(Connection con) throws SQLException {
                try {
                    for (HashMap<String, String> error : LegacyDAO.executeScript(con, rd)) {
                        log.error("Error during script execution at line {}: {} [ {} ]",
                                new Object[] { error.get("ln"), error.get("msg"), error.get("sql") });
                    }
                } catch (IOException e) {
                    log.error(e.getMessage(), e);
                } finally {
                    IOUtils.closeQuietly(rd);
                }
            }
        });

        commit(tx);
    } catch (Exception e) {
        rollback(tx);
        log.error(e.getMessage(), e);
    }
}

From source file:com.openkm.dao.LegacyDAO.java

License:Open Source License

/**
 * * Execute SQL query//from  ww w .  j a v  a  2  s  . com
 */
public static List<List<String>> executeSQL(final String query) throws DatabaseException {
    ResultWorker worker = new ResultWorker();
    Session session = null;
    Transaction tx = null;

    try {
        session = HibernateUtil.getSessionFactory().openSession();
        tx = session.beginTransaction();
        worker.setSql(query);
        session.doWork(worker);
        HibernateUtil.commit(tx);
    } catch (Exception e) {
        HibernateUtil.rollback(tx);
        throw new DatabaseException(e.getMessage(), e);
    }

    return worker.getResults();
}

From source file:com.openkm.servlet.admin.DatabaseQueryServlet.java

License:Open Source License

/**
 * Execute JDBC query/*from  www .j  a  va 2s .  co  m*/
 */
private void executeJdbc(Session session, String qs, ServletContext sc, HttpServletRequest request,
        HttpServletResponse response) throws SQLException, ServletException, IOException {
    WorkerJdbc worker = new WorkerJdbc();
    worker.setQueryString(qs);
    session.doWork(worker);

    sc.setAttribute("showSql", null);
    sc.setAttribute("exception", null);
    sc.setAttribute("globalResults", worker.getGlobalResults());
    sc.getRequestDispatcher("/admin/database_query.jsp").forward(request, response);
}

From source file:com.openkm.servlet.admin.DatabaseQueryServlet.java

License:Open Source License

/**
 * Import into database/*from w  w  w.j a v  a 2 s  .co  m*/
 */
private void executeUpdate(Session session, byte[] data, ServletContext sc, HttpServletRequest request,
        HttpServletResponse response) throws SQLException, ServletException, IOException {
    log.debug("executeUpdate({}, {}, {})", new Object[] { session, request, response });
    List<DbQueryGlobalResult> globalResults = new ArrayList<DbQueryGlobalResult>();
    WorkerUpdate worker = new WorkerUpdate();
    worker.setData(data);
    session.doWork(worker);

    DbQueryGlobalResult gr = new DbQueryGlobalResult();
    gr.setColumns(null);
    gr.setResults(null);
    gr.setSql(null);
    gr.setRows(worker.getRows());
    gr.setErrors(worker.getErrors());
    globalResults.add(gr);

    sc.setAttribute("qs", null);
    sc.setAttribute("type", null);
    sc.setAttribute("showSql", null);
    sc.setAttribute("globalResults", globalResults);
    sc.getRequestDispatcher("/admin/database_query.jsp").forward(request, response);

    log.debug("executeUpdate: void");
}

From source file:com.openkm.servlet.admin.LanguageServlet.java

License:Open Source License

/**
 * Import a new language into database//w  ww.ja  va 2  s.c  om
 */
private void importLanguage(String userId, HttpServletRequest request, HttpServletResponse response,
        final byte[] data, Session dbSession) throws DatabaseException, IOException, SQLException {
    log.debug("importLanguage({}, {}, {}, {}, {})",
            new Object[] { userId, request, response, data, dbSession });
    // Because need to be final and an array can be modified being final
    final String[] insertLanguage = new String[1];

    dbSession.doWork(new Work() {
        @Override
        public void execute(Connection con) throws SQLException {
            Statement stmt = con.createStatement();
            InputStreamReader is = new InputStreamReader(new ByteArrayInputStream(data));
            BufferedReader br = new BufferedReader(is);
            String query;

            try {
                while ((query = br.readLine()) != null) {
                    // Used to get the inserted language id
                    if (query.indexOf("INSERT INTO OKM_LANGUAGE") >= 0) {
                        insertLanguage[0] = query;
                    }

                    stmt.executeUpdate(query);
                }
            } catch (IOException e) {
                throw new SQLException(e.getMessage(), e);
            }

            LegacyDAO.close(stmt);
        }
    });

    // Normalize imported language
    LanguageDAO.refresh();

    for (Language language : LanguageDAO.findAll()) {
        // Check for inserted language id
        if (insertLanguage[0].indexOf(language.getId()) > 0) {
            LanguageDAO.normalizeTranslation(language);
            break;
        }
    }

    // Clean language cache again
    LanguageDAO.refresh();

    log.debug("importLanguage: void");
}

From source file:com.openkm.servlet.admin.MimeTypeServlet.java

License:Open Source License

/**
 * Import mime types into database/*from w w  w  .jav a 2s .  c  om*/
 */
private void importMimeTypes(String userId, HttpServletRequest request, HttpServletResponse response,
        final byte[] data, Session dbSession) throws DatabaseException, IOException, SQLException {
    log.debug("import({}, {}, {}, {}, {})", new Object[] { userId, request, response, data, dbSession });

    WorkerUpdate worker = new DatabaseQueryServlet().new WorkerUpdate();
    worker.setData(data);
    dbSession.doWork(worker);
    log.debug("importMimeTypes: void");
}

From source file:com.peterphi.std.guice.hibernate.module.TransactionMethodInterceptor.java

License:Apache License

/**
 * Make the {@link java.sql.Connection} underlying this {@link Session} read/write
 *
 * @param session//from w  w  w  .  j av a  2 s. com
 */
private void makeReadWrite(final Session session) {
    session.doWork(SetJDBCConnectionReadOnlyWork.READ_WRITE);
}

From source file:com.peterphi.std.guice.hibernate.module.TransactionMethodInterceptor.java

License:Apache License

/**
 * Make the session (and the underlying {@link java.sql.Connection} read only
 *
 * @param session//from   ww w  . jav a  2 s  .  c o m
 */
private void makeReadOnly(final Session session) {
    session.setDefaultReadOnly(true);
    session.setFlushMode(FlushMode.MANUAL);

    // Make the Connection read only
    session.doWork(SetJDBCConnectionReadOnlyWork.READ_ONLY);
}

From source file:com.quartzdesk.executor.dao.AbstractDao.java

License:MIT License

/**
 * Checks if the specified table exists in the specified schema and returns true if
 * it exists, false otherwise. This method tries to look up the table using both
 * lower-case and upper-case schema and table names because some databases seems to
 * require the names to be in upper case (DB2, Oracle), whereas other databases require
 * the names to be in lower-case./*from   w w w.  j av  a2s  .  c  o m*/
 *
 * @param session    a Hibernate session.
 * @param schemaName an optional schema name where to look for the table name.
 * @param tableName  a table name.
 * @return true if the table exists, false otherwise.
 */
public boolean tableExists(Session session, final String schemaName, final String tableName) {
    final AtomicBoolean tableExists = new AtomicBoolean(false);

    session.doWork(new Work() {
        @Override
        public void execute(Connection connection) throws SQLException {
            log.debug("Checking if table '{}' exists.", tableName);

            DatabaseMetaData metaData = connection.getMetaData();

            // 1. attempt - try schema and table name in lower-case (does not work in DB2 and Oracle)
            ResultSet res = metaData.getTables(null,
                    schemaName == null ? null : schemaName.toLowerCase(Locale.US),
                    tableName.toLowerCase(Locale.US), new String[] { "TABLE" });

            tableExists.set(res.next());
            DbUtils.close(res);

            if (tableExists.get()) {
                log.debug("Table '{}' exists.", tableName);
            } else {
                // 2. attempt - try schema and table name in upper-case (required for DB2 and Oracle)
                res = metaData.getTables(null, schemaName == null ? null : schemaName.toUpperCase(Locale.US),
                        tableName.toUpperCase(Locale.US), new String[] { "TABLE" });

                tableExists.set(res.next());
                DbUtils.close(res);

                if (tableExists.get()) {
                    log.debug("Table '{}' exists.", tableName);
                } else {
                    log.debug("Table '{}' does not exist.", tableName);
                }
            }
        }
    });

    return tableExists.get();
}