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.pushinginertia.commons.domain.usertype.MapAsJsonUserType.java

License:Open Source License

static Map<String, Object> deserialize(final String columnValue) throws HibernateException {
    final ObjectMapper mapper = new ObjectMapper();
    final JsonFactory f = new JsonFactory();
    try {//ww w  .  java  2s .  co  m
        final JsonParser jp = f.createJsonParser(columnValue);
        // advance stream to first token
        jp.nextToken();
        if (jp.isExpectedStartArrayToken()) {
            // if the token is START_ARRAY, advance once more to the object within it
            // this handles encoded strings with a single map inside an array
            jp.nextToken();
        }
        return mapper.readValue(jp, Map.class);
    } catch (final IOException e) {
        throw new HibernateException("Failed to parse JSON-encoded map: " + columnValue, e);
    }
}

From source file:com.seethayya.shoppingcart.util.GenericEnumUserType.java

License:Apache License

@Override
public void setParameterValues(Properties parameters) {
    String enumClassName = parameters.getProperty("enumClass");

    try {/*from w w w  .  j ava 2s  .  c  om*/
        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 = (AbstractSingleColumnStandardBasicType<? extends Object>) new TypeResolver()
            .heuristicType(identifierType.getName(), parameters);

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

    sqlTypes = new int[] { ((AbstractSingleColumnStandardBasicType<?>) 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.seethayya.shoppingcart.util.GenericEnumUserType.java

License:Apache License

@Override
public Object nullSafeGet(ResultSet rs, String[] names, SessionImplementor session, Object owner)
        throws HibernateException, SQLException {
    Object identifier = type.get(rs, names[0], session);
    if (rs.wasNull()) {
        return null;
    }//  w  w w.j  a  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.seethayya.shoppingcart.util.GenericEnumUserType.java

License:Apache License

@Override
public void nullSafeSet(PreparedStatement st, Object value, int index, SessionImplementor session)
        throws HibernateException, SQLException {
    try {/*from www.  j  a  v a2s  .  c o m*/
        if (value == null) {
            st.setNull(index, ((AbstractSingleColumnStandardBasicType<?>) type).sqlType());
        } else {
            Object identifier = identifierMethod.invoke(value, new Object[0]);
            type.nullSafeSet(st, identifier, index, session);
        }
    } catch (Exception e) {
        throw new HibernateException("Exception while invoking identifierMethod '" + identifierMethod.getName()
                + "' of " + "enumeration class '" + enumClass + "'", e);
    }
}

From source file:com.xpn.xwiki.internal.store.hibernate.HibernateStore.java

License:Open Source License

/**
 * Ends a transaction and close the session.
 *
 * @param commit should we commit or not
 *///from   w ww.  j  a va 2s.c o  m
public void endTransaction(boolean commit) {
    Session session = null;
    try {
        session = getCurrentSession();
        Transaction transaction = getCurrentTransaction();
        setCurrentSession(null);
        setCurrentTransaction(null);

        if (transaction != null) {
            this.logger.debug("Releasing hibernate transaction [{}]", transaction);

            if (commit) {
                transaction.commit();
            } else {
                transaction.rollback();
            }
        }
    } catch (HibernateException e) {
        // Ensure the original cause will get printed.
        throw new HibernateException(
                "Failed to commit or rollback transaction. Root cause [" + getExceptionMessage(e) + "]", e);
    } finally {
        closeSession(session);
    }
}

From source file:com.xpn.xwiki.store.DBCPConnectionProvider.java

License:Open Source License

public void configure(Properties props) throws HibernateException {
    try {//  w w  w  .ja  va2s. c o  m
        log.debug("Configure DBCPConnectionProvider");

        // DBCP properties used to create the BasicDataSource
        Properties dbcpProperties = new Properties();

        // DriverClass & url
        String jdbcDriverClass = props.getProperty(Environment.DRIVER);
        String jdbcUrl = props.getProperty(Environment.URL);
        dbcpProperties.put("driverClassName", jdbcDriverClass);
        dbcpProperties.put("url", jdbcUrl);

        // Username / password. Only put username and password if they're not null. This allows
        // external authentication support (OS authenticated). It'll thus work if the hibernate
        // config does not specify a username and/or password.
        String username = props.getProperty(Environment.USER);
        if (username != null) {
            dbcpProperties.put("username", username);
        }
        String password = props.getProperty(Environment.PASS);
        if (password != null) {
            dbcpProperties.put("password", password);
        }

        // Isolation level
        String isolationLevel = props.getProperty(Environment.ISOLATION);
        if ((isolationLevel != null) && (isolationLevel.trim().length() > 0)) {
            dbcpProperties.put("defaultTransactionIsolation", isolationLevel);
        }

        // Turn off autocommit (unless autocommit property is set)
        String autocommit = props.getProperty(AUTOCOMMIT);
        if ((autocommit != null) && (autocommit.trim().length() > 0)) {
            dbcpProperties.put("defaultAutoCommit", autocommit);
        } else {
            dbcpProperties.put("defaultAutoCommit", String.valueOf(Boolean.FALSE));
        }

        // Pool size
        String poolSize = props.getProperty(Environment.POOL_SIZE);
        if ((poolSize != null) && (poolSize.trim().length() > 0) && (Integer.parseInt(poolSize) > 0)) {
            dbcpProperties.put("maxActive", poolSize);
        }

        // Copy all "driver" properties into "connectionProperties"
        Properties driverProps = ConnectionProviderFactory.getConnectionProperties(props);
        if (driverProps.size() > 0) {
            StringBuffer connectionProperties = new StringBuffer();
            for (Iterator iter = driverProps.keySet().iterator(); iter.hasNext();) {
                String key = (String) iter.next();
                String value = driverProps.getProperty(key);
                connectionProperties.append(key).append('=').append(value);
                if (iter.hasNext()) {
                    connectionProperties.append(';');
                }
            }
            dbcpProperties.put("connectionProperties", connectionProperties.toString());
        }

        // Copy all DBCP properties removing the prefix
        for (Iterator iter = props.keySet().iterator(); iter.hasNext();) {
            String key = String.valueOf(iter.next());
            if (key.startsWith(PREFIX)) {
                String property = key.substring(PREFIX.length());
                String value = props.getProperty(key);
                dbcpProperties.put(property, value);
            }
        }

        // Backward-compatibility
        if (props.getProperty(DBCP_PS_MAXACTIVE) != null) {
            dbcpProperties.put("poolPreparedStatements", String.valueOf(Boolean.TRUE));
            dbcpProperties.put("maxOpenPreparedStatements", props.getProperty(DBCP_PS_MAXACTIVE));
        }

        // Some debug info
        if (log.isDebugEnabled()) {
            log.debug("Creating a DBCP BasicDataSource with the following DBCP factory properties:");
            StringWriter sw = new StringWriter();
            dbcpProperties.list(new PrintWriter(sw, true));
            log.debug(sw.toString());
        }

        // Let the factory create the pool
        ds = (BasicDataSource) 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. "
                + "There is an error in the hibernate configuration file, please review it.";
        log.fatal(message, e);
        if (ds != null) {
            try {
                ds.close();
            } catch (Exception e2) {
                // ignore
            }
            ds = null;
        }
        throw new HibernateException(message, e);
    }
    log.debug("Configure DBCPConnectionProvider complete");
}

From source file:com.xpn.xwiki.store.DBCPConnectionProvider.java

License:Open Source License

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

From source file:com.xpn.xwiki.store.HibernateStoreTest.java

License:Open Source License

@Test
public void testEndTransactionWhenSQLBatchUpdateExceptionThrown() throws Exception {
    SQLException sqlException2 = new SQLException("sqlexception2");
    sqlException2.setNextException(new SQLException("nextexception2"));

    SQLException sqlException1 = new SQLException("sqlexception1");
    sqlException1.initCause(sqlException2);
    sqlException1.setNextException(new SQLException("nextexception1"));

    doThrow(new HibernateException("exception1", sqlException1)).when(transaction).commit();

    try {/*from  w  ww . j a  va  2  s.  co  m*/
        mocker.getComponentUnderTest().endTransaction(true);
        fail("Should have thrown an exception here");
    } catch (HibernateException e) {
        assertEquals("Failed to commit or rollback transaction. Root cause [\n"
                + "SQL next exception = [java.sql.SQLException: nextexception1]\n"
                + "SQL next exception = [java.sql.SQLException: nextexception2]]", e.getMessage());
    }
}

From source file:com.xpn.xwiki.store.XWikiHibernateStoreTest.java

License:Open Source License

@org.junit.Test
public void testEndTransactionWhenSQLBatchUpdateExceptionThrown() throws Exception {
    XWikiHibernateStore store = new XWikiHibernateStore("whatever");

    final Transaction mockTransaction = getMockery().mock(Transaction.class);

    SQLException sqlException2 = new SQLException("sqlexception2");
    sqlException2.setNextException(new SQLException("nextexception2"));

    final SQLException sqlException1 = new SQLException("sqlexception1");
    sqlException1.initCause(sqlException2);
    sqlException1.setNextException(new SQLException("nextexception1"));

    getMockery().checking(new Expectations() {
        {//from www .  ja va2 s. c o  m
            oneOf(mockTransaction).commit();
            will(throwException(new HibernateException("exception1", sqlException1)));
        }
    });

    store.setTransaction(mockTransaction, getContext());

    try {
        store.endTransaction(getContext(), true);
        Assert.fail("Should have thrown an exception here");
    } catch (HibernateException e) {
        Assert.assertEquals("Failed to commit or rollback transaction. Root cause [\n"
                + "SQL next exception = [java.sql.SQLException: nextexception1]\n"
                + "SQL next exception = [java.sql.SQLException: nextexception2]]", e.getMessage());
    }
}

From source file:conf.DBCPConnectionProvider.java

License:Apache License

public void configure(Properties props) throws HibernateException {
    try {/*from w  w  w .  ja v a  2  s  . c  om*/
        log.debug("Configure DBCPConnectionProvider");

        // DBCP properties used to create the BasicDataSource
        Properties dbcpProperties = new Properties();

        // DriverClass & url
        String jdbcDriverClass = props.getProperty(Environment.DRIVER);
        String jdbcUrl = props.getProperty(Environment.URL);
        dbcpProperties.put("driverClassName", jdbcDriverClass);
        dbcpProperties.put("url", jdbcUrl);

        // Username / password
        String username = props.getProperty(Environment.USER);
        String password = props.getProperty(Environment.PASS);
        dbcpProperties.put("username", username);
        dbcpProperties.put("password", password);

        // Isolation level
        String isolationLevel = props.getProperty(Environment.ISOLATION);
        if ((isolationLevel != null) && (isolationLevel.trim().length() > 0)) {
            dbcpProperties.put("defaultTransactionIsolation", isolationLevel);
        }

        // Turn off autocommit (unless autocommit property is set)
        String autocommit = props.getProperty(AUTOCOMMIT);
        if ((autocommit != null) && (autocommit.trim().length() > 0)) {
            dbcpProperties.put("defaultAutoCommit", autocommit);
        } else {
            dbcpProperties.put("defaultAutoCommit", String.valueOf(Boolean.FALSE));
        }

        // Pool size
        String poolSize = props.getProperty(Environment.POOL_SIZE);
        if ((poolSize != null) && (poolSize.trim().length() > 0) && (Integer.parseInt(poolSize) > 0)) {
            dbcpProperties.put("maxActive", poolSize);
        }

        // Copy all "driver" properties into "connectionProperties"
        Properties driverProps = ConnectionProviderFactory.getConnectionProperties(props);
        if (driverProps.size() > 0) {
            StringBuffer connectionProperties = new StringBuffer();
            for (Iterator iter = driverProps.keySet().iterator(); iter.hasNext();) {
                String key = (String) iter.next();
                String value = driverProps.getProperty(key);
                connectionProperties.append(key).append('=').append(value);
                if (iter.hasNext()) {
                    connectionProperties.append(';');
                }
            }
            dbcpProperties.put("connectionProperties", connectionProperties.toString());
        }

        // Copy all DBCP properties removing the prefix
        for (Iterator iter = props.keySet().iterator(); iter.hasNext();) {
            String key = String.valueOf(iter.next());
            if (key.startsWith(PREFIX)) {
                String property = key.substring(PREFIX.length());
                String value = props.getProperty(key);
                dbcpProperties.put(property, value);
            }
        }

        // Backward-compatibility
        if (props.getProperty(DBCP_PS_MAXACTIVE) != null) {
            dbcpProperties.put("poolPreparedStatements", String.valueOf(Boolean.TRUE));
            dbcpProperties.put("maxOpenPreparedStatements", props.getProperty(DBCP_PS_MAXACTIVE));
        }

        // Some debug info
        if (log.isDebugEnabled()) {
            log.debug("Creating a DBCP BasicDataSource with the following DBCP factory properties:");
            StringWriter sw = new StringWriter();
            dbcpProperties.list(new PrintWriter(sw, true));
            log.debug(sw.toString());
        }

        // Let the factory create the pool
        ds = (BasicDataSource) 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.fatal(message, e);
        if (ds != null) {
            try {
                ds.close();
            } catch (Exception e2) {
                // ignore
            }
            ds = null;
        }
        throw new HibernateException(message, e);
    }
    log.debug("Configure DBCPConnectionProvider complete");
}