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.xpn.xwiki.store.migration.hibernate.R54600TranslationDataMigration.java

License:Open Source License

@Override
public void hibernateMigrate() throws DataMigrationException, XWikiException {
    getStore().executeWrite(getXWikiContext(), new HibernateCallback<Object>() {
        @Override/*from  w w  w  . ja v a2 s  .c om*/
        public Object doInHibernate(Session session) throws HibernateException, XWikiException {
            session.doWork(new R54600Work());
            return Boolean.TRUE;
        }
    });
}

From source file:com.xpn.xwiki.store.migration.hibernate.R72000XWIKI12153DataMigration.java

License:Open Source License

@Override
public void hibernateMigrate() throws DataMigrationException, XWikiException {
    getStore().executeWrite(getXWikiContext(), new HibernateCallback<Object>() {
        @Override//www  . ja va 2  s. c  om
        public Object doInHibernate(Session session) throws HibernateException, XWikiException {
            session.doWork(new R72000Work());
            return Boolean.TRUE;
        }
    });
}

From source file:contac.servicio.reportes.ManagerGeneradorReporteServiceBusinessImpl.java

License:Open Source License

@Override
public JasperPrint generateReport(Map parameters, JasperReport report)
        throws ManagerGeneradorReporteServiceBusinessException, RemoteException {

    //Iniciar servicio de autenticacion
    boolean transaction = initBusinessService(Roles.ROLCONTACUSER.toString());

    try {/*from ww  w.j av a 2  s  .  c  om*/

        final Map p_parameters = parameters;
        final JasperReport p_report = report;

        final JasperPrint[] printReport = { null };

        Session session = PersistenceManagementServiceFactory.getEntityManager().unwrap(Session.class);
        session.doWork(new Work() {
            @Override
            public void execute(Connection connection) throws SQLException {
                try {
                    JRXReportGenerated reportGenerated = new JRXReportGenerated(p_report, p_parameters,
                            connection);
                    printReport[0] = JRPrintReport.fillReport(reportGenerated);
                } catch (Exception e) {
                    logger.error(e.getMessage(), e);
                    throw new SQLException(e);
                }

                connection.close();
            }
        });

        return printReport[0];

    } catch (PersistenceManagementServiceFactoryException e) {
        logger.error(e.getMessage(), e);
        throw new ManagerGeneradorReporteServiceBusinessException(e.getMessage(), e);
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        throw new ManagerGeneradorReporteServiceBusinessException(e.getMessage(), e);
    } finally {
        stopBusinessService(transaction);
    }
}

From source file:de.innovationgate.webgate.api.hsql.WGDatabaseImpl.java

License:Open Source License

public void close() throws WGAPIException {

    Session session = null;
    boolean sessionOpened = false;
    try {//from   w w w. ja va 2s  .c om
        session = getSessionStatus().getSession();
        if (session == null) {
            session = _sessionBuilder.openSession();
            sessionOpened = true;
        }

        session.doWork(new Work() {
            public void execute(Connection connection) throws SQLException {
                try {
                    connection.createStatement().execute("SHUTDOWN COMPACT");
                } catch (SQLException e) {
                    WGFactory.getLogger().error("Error shutting down HSQL database", e);
                }
            }
        });

    } catch (HibernateException e) {
        WGFactory.getLogger().error("Error shutting down HSQL database", e);
    } finally {

        if (session != null && sessionOpened) {
            try {
                session.close();
            } catch (HibernateException e) {
                WGFactory.getLogger().error("Error closing HSQL shutdown session", e);
            }
        }

    }

    if (_hsqlServer != null) {
        _hsqlServer.shutdown();
        _hsqlServer = null;
    }

    super.close();

}

From source file:de.innovationgate.webgate.api.jdbc.WGDatabaseImpl.java

License:Open Source License

/**
 * @throws WGUnavailableException //w  w  w .  j av  a 2 s . com
 * @throws WGAPIException 
 * @see de.innovationgate.webgate.api.WGDatabaseCore#openSession(String,
 *      String)
 */
public WGUserAccess openSession(AuthenticationSession authSession, Object pwd, boolean master)
        throws WGAPIException {

    try {

        // Hibernate login
        Session session = _sessionBuilder.openSession();
        // Connection conn = session.connection();
        // conn.setAutoCommit(true); //Problematic with DBCP?
        session.setFlushMode(FlushMode.COMMIT);
        if (_saveIsolationActive) {
            session.setDefaultReadOnly(true);
        }
        getSessionStatus().setSession(session);

        if (!session.isOpen()) {
            throw new WGUnavailableException(_db, "Unable to connect to hibernate session");
        }

        // special handling if loadbalancing is enabled
        if (hasFeature(WGDatabase.FEATURE_LOADBALANCE)) {

            // set all connections to readonly except master sessions and if
            // update is in progress
            final boolean readOnly = (master ? false : !isUpdateInProgress(authSession.getDistinguishedName()));

            try {
                session.doWork(new Work() {

                    public void execute(Connection connection) throws SQLException {
                        connection.setReadOnly(readOnly);
                    }
                });
            } catch (HibernateException e) {
                throw new WGBackendException("Unable to set readonly flag on connection.", e);
            }
        }

        if (getTransactionMode() != WGSessionContext.TRANSACTION_MODE_MANUAL) {
            session.beginTransaction();
        }

        if (master) {
            // Master login always has manager access
            return new WGUserAccess(WGDatabase.MASTER_USERNAME, WGDatabase.ACCESSLEVEL_MANAGER);
        }

        // Determine access
        WGUserDetails userDetails;
        try {
            userDetails = _db.defaultBuildUserDetails(authSession);
        } catch (WGBackendException e) {
            try {
                closeSession();
            } catch (WGBackendException e1) {
                WGFactory.getLogger().error(e1);
            }
            throw e;
        }
        if (userDetails.getAccessLevel() <= WGDatabase.ACCESSLEVEL_NOACCESS) {
            try {
                closeSession();
            } catch (WGBackendException e) {
                WGFactory.getLogger().error(e);
            }
        }

        return userDetails;

    } catch (HibernateException e) {
        try {
            closeSession();
        } catch (WGBackendException e1) {
            WGFactory.getLogger().error(e1);
        }
        throw new WGUnavailableException(_db, "Error opening hibernate session", e);
    }

}

From source file:de.iteratec.iteraplan.db.SqlScriptExecutor.java

License:Open Source License

public static void executeSqlStatements(final List<String> sqlStrings, HibernateTemplate hibernateTemplate) {

    final Work work = new Work() {

        public void execute(Connection connection) throws SQLException {
            executeSqlStatements(sqlStrings, connection);
        }//from w w w. ja  v  a2s .c  o  m
    };

    HibernateCallback<Object> callback = new HibernateCallback<Object>() {

        public Object doInHibernate(Session session) throws HibernateException, SQLException {
            session.doWork(work);
            return null;
        }
    };

    hibernateTemplate.execute(callback);
}

From source file:de.iteratec.iteraplan.presentation.problemreports.DatabaseProblemReportPart.java

License:Open Source License

static ProblemReportPart generateDatabaseReport(String filename, HttpServletRequest request) {
    DatabaseProblemReportPart reportPart = new DatabaseProblemReportPart(filename);
    PrintWriter dbWriter = reportPart.getWriter();

    ApplicationContext context = DefaultSpringApplicationContext.getSpringApplicationContext();
    Object sessionFactoryObject = context.getBean("sessionFactory");

    if (sessionFactoryObject instanceof SessionFactory) {
        SessionFactory sessionFactory = (SessionFactory) sessionFactoryObject;
        Session currentSession = sessionFactory.getCurrentSession();
        Map<String, ClassMetadata> allClassMetadata = sessionFactory.getAllClassMetadata();
        final Set<String> tableNames = Sets.newHashSet();
        for (ClassMetadata cm : allClassMetadata.values()) {
            if (cm instanceof AbstractEntityPersister) {
                AbstractEntityPersister aep = (AbstractEntityPersister) cm;
                tableNames.add(aep.getTableName());
            }/*from w  ww  .j a  v  a  2 s .c  o m*/
        }

        ByteArrayOutputStream dbInfoBuffer = new ByteArrayOutputStream();
        final PrintWriter dbInfoWriter = new PrintWriter(dbInfoBuffer);
        Work work = new Work() {

            @Override
            public void execute(Connection connection) throws SQLException {

                try {
                    DatabaseMetaData metaData = connection.getMetaData();
                    dbInfoWriter.println("Database Name: " + metaData.getDatabaseProductName() + "  "
                            + metaData.getDatabaseMajorVersion() + "." + metaData.getDatabaseMinorVersion());
                    dbInfoWriter.println("Database Product Version: " + metaData.getDatabaseProductVersion());
                    dbInfoWriter.println("JDBC URL: " + metaData.getURL());
                    dbInfoWriter.println("JDBC API: " + metaData.getJDBCMajorVersion() + "."
                            + metaData.getJDBCMinorVersion());
                    dbInfoWriter.println("JDBC-Driver Name: " + metaData.getDriverName() + "  "
                            + metaData.getDriverMajorVersion() + "." + metaData.getDriverMinorVersion());
                    dbInfoWriter.println("JDBC-Driver Version: " + metaData.getDriverVersion());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };

        try {
            TimeLimiter timeLimiter = new SimpleTimeLimiter();
            Session sessionProxy = timeLimiter.newProxy(currentSession, Session.class, TIMEOUT_IN_SECONDS,
                    TimeUnit.SECONDS);
            sessionProxy.doWork(work);
        } catch (UncheckedTimeoutException e) {
            dbInfoWriter.println("Couldn't gather database information from conncetion within "
                    + TIMEOUT_IN_SECONDS + " seconds.");
        } catch (Exception e) {
            dbInfoWriter.println("Couldn't gather database information from connection.");
        }

        dbInfoWriter.close();
        dbWriter.print(dbInfoBuffer);
    }

    dbWriter.close();
    return reportPart;
}

From source file:de.tudarmstadt.ukp.clarin.webanno.api.dao.RepositoryServiceDbData.java

License:Apache License

@Override
public String getDatabaseDriverName() {
    final StringBuilder sb = new StringBuilder();
    Session session = entityManager.unwrap(Session.class);
    session.doWork(new Work() {
        @Override/*from  w  ww  . j ava 2s  . co m*/
        public void execute(Connection aConnection) throws SQLException {
            sb.append(aConnection.getMetaData().getDriverName());
        }
    });

    return sb.toString();
}

From source file:de.tudarmstadt.ukp.csniper.webapp.project.ProjectRepository.java

License:Apache License

/**
 * Gets the maximum column length.<br>
 * Why is this method located here? For convenience reasons - we already have access to
 * projectRepository on the relevant pages (EvaluationPage, AnnotationTypePage).
 * //from   w  w w  .ja  v  a 2  s .co m
 * @param aColumn
 *            the column for which the maximum length shall be returned
 * @return the maximum length of the specified column in the specified table
 */
@Transactional
public int getDbColumnLength(String aEntityName, String aColumn) {
    BigInteger length = new BigInteger("255");

    final List<String> query = new ArrayList<String>();
    query.add("SELECT CHARACTER_MAXIMUM_LENGTH");
    query.add("FROM INFORMATION_SCHEMA.COLUMNS");

    Session session = entityManager.unwrap(Session.class);
    session.doWork(new Work() {
        @Override
        public void execute(Connection aConnection) throws SQLException {
            query.add("WHERE table_schema = '" + aConnection.getCatalog() + "'");
        }
    });

    query.add("AND table_name = '" + aEntityName + "'");
    query.add("AND column_name = '" + aColumn + "'");

    try {
        length = (BigInteger) entityManager.createNativeQuery(StringUtils.join(query, " ")).getSingleResult();
    } catch (NoResultException e) {
        // log.debug("No results for query: " + StringUtils.join(query, " "));
    }

    if (length.compareTo(BigInteger.valueOf(Integer.MAX_VALUE)) > 0) {
        return Integer.MAX_VALUE;
    } else {
        return length.intValue();
    }
}

From source file:edu.cads.testestimation.userinterface.TestEstimationFrame.java

private void getSystemNameCount() {
    Session session = null;
    //private int systemCount;
    UnitTestingResults unitTestingResults = null;
    try {/*www  .  j  a  va  2s. c  o m*/
        session = HibernateUtil.getSessionFactory().openSession();
        session.doWork(new Work() {

            public void execute(Connection connection) throws SQLException {
                CallableStatement call = connection
                        .prepareCall("{ ? = call MOROCHENETS_OLEXIY.GET_SYSTEM_COUNT() }");
                call.registerOutParameter(1, OracleTypes.CURSOR);
                call.execute();
                ResultSet resultSet = (ResultSet) call.getObject(1);
                while (resultSet.next()) {

                    systemCount = resultSet.getInt("Count(*)");
                    System.out.println("systemCount" + systemCount);

                }
            }
        });
    } catch (Exception e) {
        JOptionPane.showMessageDialog(null, e.getMessage(), " I/O", JOptionPane.OK_OPTION);
    } finally {
        if (session != null && session.isOpen()) {
            session.close();
        }
    }

}