Example usage for org.hibernate HibernateException HibernateException

List of usage examples for org.hibernate HibernateException HibernateException

Introduction

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

Prototype

public HibernateException(String message, Throwable cause) 

Source Link

Document

Constructs a HibernateException using the given message and underlying cause.

Usage

From source file:com.abiquo.abiserver.business.hibernate.pojohb.userType.GenericEnumUserType.java

License:Open Source License

public Object nullSafeGet(ResultSet rs, String[] names, Object owner) throws HibernateException, SQLException {
    Object identifier = type.get(rs, names[0]);
    if (rs.wasNull()) {
        return null;
    }/*from   ww w  .ja va 2  s.  com*/

    try {
        return valueOfMethod.invoke(enumClass, new Object[] { identifier });
    } catch (Exception e) {
        throw new HibernateException("Exception while invoking valueOf method '" + valueOfMethod.getName()
                + "' of " + "enumeration class '" + enumClass + "'", e);
    }
}

From source file:com.abiquo.abiserver.business.hibernate.pojohb.userType.GenericEnumUserType.java

License:Open Source License

public void nullSafeSet(PreparedStatement st, Object value, int index) throws HibernateException, SQLException {
    try {/*from w w w. ja  v  a2 s  .co m*/
        if (value == null) {
            st.setNull(index, type.sqlType());
        } else {
            Object identifier = identifierMethod.invoke(value, new Object[0]);
            type.set(st, identifier, index);
        }
    } catch (Exception e) {
        throw new HibernateException("Exception while invoking identifierMethod '" + identifierMethod.getName()
                + "' of " + "enumeration class '" + enumClass + "'", e);
    }
}

From source file:com.amalto.core.storage.DBCPConnectionProvider.java

License:Open Source License

@Override
public void configure(Map props) {
    try {/*from  ww  w . ja  va2  s  . c om*/
        if (log.isDebugEnabled()) {
            log.debug("Configure DBCPConnectionProvider");
        }
        // DBCP properties used to create the BasicDataSource
        Properties dbcpProperties = new Properties();
        // DriverClass & url
        String jdbcDriverClass = (String) props.get(Environment.DRIVER);
        String jdbcUrl = (String) props.get(Environment.URL);
        dbcpProperties.put("driverClassName", jdbcDriverClass);
        dbcpProperties.put("url", jdbcUrl);
        // Username / password
        String username = (String) props.get(Environment.USER);
        String password = (String) props.get(Environment.PASS);
        dbcpProperties.put("username", username);
        dbcpProperties.put("password", password);
        // Isolation level
        String isolationLevel = (String) props.get(Environment.ISOLATION);
        if ((isolationLevel != null) && (isolationLevel.trim().length() > 0)) {
            dbcpProperties.put("defaultTransactionIsolation", isolationLevel);
        }
        // Turn off autocommit
        dbcpProperties.put("defaultAutoCommit", String.valueOf(Boolean.FALSE));
        // Pool size
        String poolSize = (String) props.get(Environment.POOL_SIZE);
        if ((poolSize != null) && (poolSize.trim().length() > 0) && (Integer.parseInt(poolSize) > 0)) {
            dbcpProperties.put("maxActive", poolSize);
        }
        // Copy all DBCP properties removing the prefix
        for (Object o : props.entrySet()) {
            Map.Entry entry = (Map.Entry) o;
            String key = (String) entry.getKey();
            if (key.startsWith(PREFIX)) {
                String property = key.substring(PREFIX.length());
                String value = (String) entry.getValue();
                dbcpProperties.put(property, value);
            }
        }
        // Some debug info
        if (log.isDebugEnabled()) {
            StringWriter sw = new StringWriter();
            dbcpProperties.list(new PrintWriter(sw, true));
            log.debug(sw.toString());
        }
        // Let the factory create the pool
        ds = BasicDataSourceFactory.createDataSource(dbcpProperties);
        // The BasicDataSource has lazy initialization borrowing a connection will start the DataSource and make
        // sure it is configured correctly.
        Connection conn = ds.getConnection();
        conn.close();
        // Log pool statistics before continuing.
        logStatistics();
    } catch (Exception e) {
        String message = "Could not create a DBCP pool";
        log.error(message, e);
        if (ds != null) {
            try {
                ds.close();
            } catch (Exception e2) {
                log.debug("Unable to close DBCP after failed initialization.", e);
            }
            ds = null;
        }
        throw new HibernateException(message, e);
    }
    if (log.isDebugEnabled()) {
        log.debug("Configure DBCPConnectionProvider complete");
    }
}

From source file:com.atomikos.icatch.jta.hibernate3.AtomikosConnectionProvider.java

License:Apache License

public void configure(Properties props) throws HibernateException {
    if (dataSource != null) {
        return;//from w  w w.j av  a 2  s .  c o  m
    }

    if ("true".equalsIgnoreCase(props.getProperty(PROPERTY_NONXA))) {
        dataSource = new AtomikosNonXADataSourceBean();
    } else {
        dataSource = new AtomikosDataSourceBean();
    }

    Properties atomikosProperties = filterOutHibernateProperties(props);
    LOGGER.logInfo("configuring AtomikosConnectionProvider with properties: " + atomikosProperties);

    try {
        PropertyUtils.setProperties(dataSource, atomikosProperties);
    } catch (PropertyException ex) {
        throw new HibernateException("cannot create Atomikos DataSource", ex);
    }

    try {
        dataSource.init();
    } catch (AtomikosSQLException ex) {
        throw new HibernateException("cannot initialize Atomikos DataSource", ex);
    }
}

From source file:com.autentia.intra.util.GenericEnumUserType.java

License:Open Source License

public void setParameterValues(Properties parameters) {
    String enumClassName = parameters.getProperty("enumClassName");
    try {//  w  ww  .j a va  2  s  . c o  m
        enumClass = Class.forName(enumClassName).asSubclass(Enum.class);
    } catch (ClassNotFoundException cfne) {
        throw new HibernateException("Enum class not found", cfne);
    }

    String identifierMethodName = parameters.getProperty("identifierMethod", DEFAULT_IDENTIFIER_METHOD_NAME);

    try {
        identifierMethod = enumClass.getMethod(identifierMethodName, new Class[0]);
        identifierType = identifierMethod.getReturnType();
    } catch (Exception e) {
        throw new HibernateException("Failed to obtain identifier method", e);
    }

    type = (NullableType) TypeFactory.basic(identifierType.getName());

    if (type == null)
        throw new HibernateException("Unsupported identifier type " + identifierType.getName());

    sqlTypes = new int[] { type.sqlType() };

    String valueOfMethodName = parameters.getProperty("valueOfMethod", DEFAULT_VALUE_OF_METHOD_NAME);

    try {
        valueOfMethod = enumClass.getMethod(valueOfMethodName, new Class[] { identifierType });
    } catch (Exception e) {
        throw new HibernateException("Failed to obtain valueOf method", e);
    }
}

From source file:com.autentia.intra.util.GenericEnumUserType.java

License:Open Source License

public Object nullSafeGet(ResultSet rs, String[] names, Object owner) throws HibernateException, SQLException {
    Object identifier = type.get(rs, names[0]);
    if (identifier == null) {
        return null;
    }/*from   w w  w.ja v a  2 s  .c o  m*/

    try {
        return valueOfMethod.invoke(enumClass, new Object[] { identifier });
    } catch (Exception e) {
        throw new HibernateException("Exception while invoking valueOf method '" + valueOfMethod.getName()
                + "' of " + "enumeration class '" + enumClass + "'", e);
    }
}

From source file:com.crm.util.TomcatJDBCConnectionProvider.java

@Override
public void configure(Map props) throws HibernateException {
    try {/* ww w. j  av  a 2s  . c o m*/
        log.debug("Configure TomcatJDBCConnectionProvider");

        // Tomcat JDBC connection pool properties used to create theDataSource
        tomcatJdbcPoolProperties = new PoolProperties();

        // DriverClass & url
        String jdbcDriverClass = (String) props.get(Environment.DRIVER);
        String jdbcUrl = (String) props.get(Environment.URL);
        tomcatJdbcPoolProperties.setDriverClassName(jdbcDriverClass);
        tomcatJdbcPoolProperties.setUrl(jdbcUrl);

        //tomcatJdbcPoolProperties.setJmxEnabled(true); thats the default

        // Username / password
        String username = (String) props.get(Environment.USER);
        String password = (String) props.get(Environment.PASS);
        tomcatJdbcPoolProperties.setUsername(username);
        tomcatJdbcPoolProperties.setPassword(password);

        // Isolation level
        String isolationLevel = (String) props.get(Environment.ISOLATION);
        if ((isolationLevel != null) && (isolationLevel.trim().length() > 0)) {
            tomcatJdbcPoolProperties.setDefaultTransactionIsolation(Integer.parseInt(isolationLevel));
        }

        //            // Turn off autocommit (unless autocommit property is set)
        //          Unfortunately since hibernate3 autocommit defaults to true but usually you don't need if it, when working outside a EJB-container
        //            String autocommit = props.getProperty(Environment.AUTOCOMMIT);
        //            if ((autocommit != null) && (autocommit.trim().length() > 0)) {
        //                tomcatJdbcPoolProperties.setDefaultAutoCommit(Boolean.parseBoolean(autocommit));
        //            } else {
        //                tomcatJdbcPoolProperties.setDefaultAutoCommit(false);
        //            }

        // Pool size
        String poolSize = (String) props.get(Environment.POOL_SIZE);
        if ((poolSize != null) && (poolSize.trim().length() > 0)) {
            tomcatJdbcPoolProperties.setMaxActive(Integer.parseInt(poolSize));
        }

        // Copy all "driver" properties into "connectionProperties"
        // ConnectionProviderInitiator.
        Properties driverProps = ConnectionProviderInitiator.getConnectionProperties(props);
        if (driverProps.size() > 0) {
            StringBuffer connectionProperties = new StringBuffer();
            for (Iterator iter = driverProps.entrySet().iterator(); iter.hasNext();) {
                Map.Entry entry = (Map.Entry) iter.next();
                String key = (String) entry.getKey();
                String value = (String) entry.getValue();
                connectionProperties.append(key).append('=').append(value);
                if (iter.hasNext()) {
                    connectionProperties.append(';');
                }
            }
            tomcatJdbcPoolProperties.setConnectionProperties(connectionProperties.toString());
        }

        // Copy all Tomcat JDBCPool properties removing the prefix
        for (Iterator iter = props.entrySet().iterator(); iter.hasNext();) {
            Map.Entry entry = (Map.Entry) iter.next();
            String key = (String) entry.getKey();
            if (key.startsWith(PREFIX)) {
                String property = key.substring(PREFIX.length());
                String value = (String) entry.getValue();
                Method[] methods = PoolConfiguration.class.getMethods();
                int i;
                for (i = 0; i < methods.length; i++) {
                    if (methods[i].getName().equalsIgnoreCase("set" + property)) {
                        Method m = methods[i];
                        Object parameter = convertIntoTypedValue(m.getParameterTypes()[0], value);
                        try {
                            m.invoke(tomcatJdbcPoolProperties, new Object[] { parameter });
                        } catch (Exception e) {
                            i = methods.length;
                        }
                        break;
                    }
                }
                if (i >= methods.length) {
                    log.error("Unable to parse property " + key + " with value: " + value);
                    throw new RuntimeException("Unable to parse property " + key + " with value: " + value);
                }
            }
        }

        // Let the factory create the pool
        ds = new DataSource();
        ds.setPoolProperties(tomcatJdbcPoolProperties);
        ds.createPool();

        if (ds.getPoolProperties().isJmxEnabled()) {
            MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
            ObjectName objectname = null;
            try {
                objectname = new ObjectName("ConnectionPool:name=" + tomcatJdbcPoolProperties.getName());
                if (!mBeanServer.isRegistered(objectname)) {
                    mBeanServer.registerMBean(ds.getPool().getJmxPool(), objectname);

                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        // Log pool statistics before continuing.
        logStatistics();
    } catch (Exception e) {
        String message = "Could not create a TomcatJDBC pool";
        log.error(message, e);
        if (ds != null) {
            try {
                ds.close();
            } catch (Exception e2) {
                // ignore
            }
            ds = null;
        }
        throw new HibernateException(message, e);
    }
    log.debug("Configure TomcatJDBCConnectionProvider complete");
}

From source file:com.crm.util.TomcatJDBCConnectionProvider.java

public void close() throws HibernateException {
    log.debug("Close TomcatJDBCConnectionProvider");
    logStatistics();/*from  w ww.  j  a va 2s . co  m*/
    try {
        if (ds != null) {
            ds.close();
            ds = null;
        } else {
            log.warn("Cannot close TomcatJDBCConnectionProvider, pool (not initialized)");
        }
    } catch (Exception e) {
        throw new HibernateException("Could not close DBCP pool", e);
    }
    log.debug("Close TomcatJDBCConnectionProvider complete");
}

From source file:com.daarons.DAO.ImportExportDAOJpaHibernateImpl.java

License:Apache License

@Override
public boolean importDB(File folder) {
    try {//from   w  w  w  .  j a  v  a 2s .  co m
        //all accounts must be deleted before importing due to derby's 
        //import procedure
        deleteAccounts();

        em = SpringConfig.getApplicationContext().getBean(LocalContainerEntityManagerFactoryBean.class)
                .getObject().createEntityManager();
        session = em.unwrap(Session.class);
        session.doWork((Connection connection) -> {
            String[] tables = { "ACCOUNT", "STUDENT", "SESSION", "NOTE", "REVIEW" };

            try {
                for (int i = 0; i < 5; i++) {
                    PreparedStatement ps = connection
                            .prepareStatement("CALL SYSCS_UTIL.SYSCS_IMPORT_TABLE (?,?,?,?,?,?,?)");
                    ps.setString(1, null);
                    ps.setString(2, tables[i]);
                    ps.setString(3, folder.getPath() + File.separator + tables[i] + ".dat");
                    ps.setString(4, "`");
                    ps.setString(5, null);
                    ps.setString(6, "UTF-8");
                    ps.setString(7, "1");
                    ps.execute();
                }
            } catch (Exception e) {
                throw new HibernateException("Import failed.", e);
            } finally {
                connection.close();
            }
        });
    } catch (Exception e) {
        log.error("Import failed", e);
        return false;
    } finally {
        em.close();
    }
    return true;
}

From source file:com.daarons.DAO.ImportExportDAOJpaHibernateImpl.java

License:Apache License

@Override
public boolean exportDB(File folder) {
    try {//from www  . ja  v  a  2s  . co  m
        em = SpringConfig.getApplicationContext().getBean(LocalContainerEntityManagerFactoryBean.class)
                .getObject().createEntityManager();
        session = em.unwrap(Session.class);
        session.doWork((Connection connection) -> {
            String[] tables = { "ACCOUNT", "STUDENT", "SESSION", "NOTE", "REVIEW" };
            try {
                for (int i = 0; i < tables.length; i++) {
                    PreparedStatement ps = connection
                            .prepareStatement("CALL SYSCS_UTIL.SYSCS_EXPORT_TABLE (?,?,?,?,?,?)");
                    ps.setString(1, null);
                    ps.setString(2, tables[i]);
                    ps.setString(3, folder.getPath() + File.separator + tables[i] + ".dat");
                    ps.setString(4, "`");
                    ps.setString(5, null);
                    ps.setString(6, "UTF-8");
                    ps.execute();
                }
            } catch (Exception e) {
                throw new HibernateException("Export failed", e);
            } finally {
                connection.close();
            }
        });
    } catch (Exception e) {
        log.error("Couldn't export", e);
        return false;
    } finally {
        em.close();
    }
    return true;
}