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(Throwable cause) 

Source Link

Document

Constructs a HibernateException using the given message and underlying cause.

Usage

From source file:de.tudresden.inf.rn.mobilis.server.HibernateUtil.java

License:Apache License

public static void commitTransaction() throws HibernateException {
    try {/* w w w .j a v a2  s .  c  o m*/
        Transaction t = transactionThreadLocal.get();
        if (t != null && !t.wasCommitted() && !t.wasRolledBack()) {
            t.commit();
            transactionThreadLocal.set(null);
        }
    } catch (Exception e) {
        HibernateUtil.rollBackTransaction();
        throw new HibernateException(e);
    }
}

From source file:de.xirp.db.XConnectionProvider.java

License:Open Source License

/**
 * The connection pool is closed by this method.
 * //w  w  w  . j  a v a  2 s  . com
 * @throws HibernateException
 *             if an exception occurs while closing the pool.
 * @see org.hibernate.connection.ConnectionProvider#close()
 * @see org.apache.commons.pool.impl.GenericObjectPool
 */
public void close() throws HibernateException {
    try {
        connectionPool.close();
    } catch (Exception e) {
        throw new HibernateException(e);
    }
}

From source file:dk.teachus.backend.dao.hibernate.PasswordUserType.java

License:Apache License

public void nullSafeSet(PreparedStatement st, Object value, int index) throws HibernateException, SQLException {
    if (value != null) {
        if (value instanceof String == false) {
            throw new HibernateException("Value must be instance of string");
        }// ww  w.j  a v  a  2 s.  c o m

        String stringValue = (String) value;

        // Encrypt the value with sha1
        try {
            // Bad way of figuring out if we should encrypt or not.
            // Please think of something smarter, but for now I guess it's ok
            Matcher matcher = SHA1_PATTERN.matcher(stringValue);
            if (matcher.matches()) {
                st.setString(index, stringValue);
            } else {
                String sha1Value = sha1(stringValue);
                st.setString(index, sha1Value);
            }
        } catch (NoSuchAlgorithmException e) {
            throw new HibernateException(e);
        } catch (UnsupportedEncodingException e) {
            throw new HibernateException(e);
        }
    } else {
        st.setNull(index, Types.VARCHAR);
    }
}

From source file:domain.model.compitoInClasse.CompitoInClasseStateUserType.java

public Object nullSafeGet(ResultSet aResultSet, String[] aStrings,
        org.hibernate.engine.spi.SessionImplementor aSessionImplementor, Object aObject)
        throws HibernateException, SQLException {

    //      String compitoStateString;
    //      CompitoInClasseStateEnum compitoStateEnum;
    //      Object ret;
    //      //w  w w .j  a  v  a2 s  .  c o  m
    //      compitoStateString = aResultSet.getString(aStrings[0]);
    //      compitoStateEnum = CompitoInClasseStateEnum.valueOf(compitoStateString);
    //      
    //      ret = null;
    //      if(!aResultSet.wasNull()){
    //         try {
    //            ret = CompitoInClasseStateFactory.getInstance().create(compitoStateEnum);
    //         } catch (IllegalArgumentException e) {
    //            throw new HibernateException("Impossibile istanziare CompitoState");
    //         }
    //      }
    //      
    //        return ret;

    String compitoStateString;

    Object ret;

    compitoStateString = aResultSet.getString(aStrings[0]);

    ret = null;
    if (!aResultSet.wasNull()) {
        try {
            ret = CompitoInClasseStateFactory.getInstance().create(compitoStateString);
        } catch (DomainCheckedException e) {
            throw new HibernateException(e.getMessage());
        }
    }

    return ret;

}

From source file:edu.amrita.aview.gclm.helpers.UserHelper.java

public static void updateUser(User user, Long updaterId) throws AViewException {
    //Fix for Bug id 2450 start
    //Check if this user is already a teacher with moderator privileges for any class.
    //If so, do not update the role to student.
    boolean canUpdate = true;
    //List<Class> classlst = null;      
    String errorMessage = null;/*from w  ww . j  a v a2  s . c  o m*/
    if (user.getRole().equals(Constant.STUDENT_ROLE)) {
        errorMessage = checkIfModerator(user);
    }

    user.setModifiedAuditData(updaterId, TimestampUtils.getCurrentTimestamp());

    if (errorMessage == null) {
        UserDAO.updateUser(user);
    } else {
        logger.debug(errorMessage + " :: error ::");
        throw (new HibernateException(errorMessage));
    }
    //Fix for Bug id 2450 end
}

From source file:edu.kit.ipd.sonar.server.HibernateDatabase.java

License:Open Source License

/**
 * Loads the Edges for the specified Node. This is an internal function! I
 * is used to load all edges that are connected to the specified node in
 * order to load the nodes from the data base and to interconnect nodes and
 * edges and add them to the graph data structure. This method also detects
 * inconsistencies in the data base in form of Edges that do not or no
 * longer belong to any nodes but have not been deleted from the data base.
 * @param g the Graph object to load the edges for
 * @param node the node object to load the edges for
 * @param s the active Hibernate session
 * @return the Graph with the edges added
 *///w  w  w.j  a v a 2s. c  om
private Graph loadEdgesForNode(final Graph g, final Node node, final Session s) {
    /* fetch current session */
    Session session = s;

    try {
        List edges = session.createQuery("select e from Edge as e where e.sourceNode=" + node.getId()
                + " OR e.destinationNode=" + node.getId()).list();

        logger.debug("Looking up edges for " + node.toString());

        /*
         * iterate over all edges that are associated with the specified
         * node
         */
        for (Iterator edgeIter = edges.iterator(); edgeIter.hasNext();) {

            Edge edge = (Edge) edgeIter.next();

            try {
                if (edge.getDestinationNode().getName() == null || edge.getSourceNode().getName() == null) {
                    logger.info("Database inconsistency detected.");
                }

                node.addEdge(edge);
                g.addEdge(edge);
                logger.debug(edge.toString() + " found in database and added to parent " + node.toString());

            } catch (Exception e) {
                if (e instanceof ObjectNotFoundException) {
                    logger.info("Database inconsistency detected" + "for an edge of Node " + node.toString());
                } else {
                    throw new HibernateException("Database is" + "inconsistent. This inconsistencs"
                            + "could not be handled by Sonar: " + e.getMessage());
                }
            } // try-catch

        } // for

    } catch (Exception e) {
        if (e instanceof ObjectNotFoundException) {
            logger.info("Database inconsistency detected for Node " + node.getName());
        } else {
            throw new HibernateException("Database is inconsistent."
                    + "This inconsistency could not be handled by Sonar: " + e.getMessage());
        }
    } // try-catch

    return g;

}

From source file:edu.kit.ipd.sonar.server.HibernateDatabase.java

License:Open Source License

/**
 * Retrieves the list of available users from the DB. These are all users
 * that can be accessed by Hibernate. Note that the number of users can
 * differ from the number of edges in the graph. Keep this in mind if you
 * are planning to do a Hibernate mapping with a 1-to-n relation between
 * users and nodes!//from  www .j  a  v a 2s  . co  m
 * @return array list of available users in the DB
 */
public ArrayList<User> getUserList() {
    Transaction tx = null;
    ArrayList<User> userlist = new ArrayList<User>();
    logger.debug("Starting userlist query.");

    Session session = HibernateUtil.getSessionFactory().openSession();

    try {
        tx = session.beginTransaction();
        List users = session.createQuery("select u from User as u").list();
        logger.trace("Userlist query sent to DB.");

        for (Iterator u = users.iterator(); u.hasNext();) {
            User usr = (User) u.next();
            logger.trace("User " + usr.toString() + " found in DB.");
            userlist.add(usr);
        }

    } catch (Exception e) {
        /* Acquire more info about the exception */
        if (e instanceof ObjectNotFoundException) {
            logger.error("Userlist could not be retrieved.: " + e.getMessage());
        } else {
            throw new HibernateException(
                    "Userlist query ended up with an" + "error that could not be handled: " + e.getMessage());
        }

    } finally {
        session.close();
    }
    return userlist;
}

From source file:edu.kit.ipd.sonar.server.HibernateUtil.java

License:Open Source License

/**
 * Starts Hibernate./*from   www  .ja  v  a2 s.  co m*/
 *
 * Be sure to startup Hibernate before acting on it! This is crucial!
 *
 * @param sonarCfg
 *            The Sonar configuration object.
 */
static void startup(final Configuration sonarCfg) {
    try {
        log.debug("Initializing Hibernate");

        if (!sonarCfg.hibernateEnabled()) {
            log.debug("Hibernate is not enabled in the configuration. " + "It will not be started.");
        } else {
            configuration = new org.hibernate.cfg.Configuration();
            configuration.configure(sonarCfg.getHibernateConfig());

            log.debug("Hibernate has been configured. Now try " + "building Session Factory");

            /* acquiring hibernate config is complete, restart sessions */
            rebuildSessionFactory(configuration);

            log.debug("Hibernate startup has been completed.");
        }
    } catch (Throwable ex) {
        log.error("Starting up Hibernate failed while building the " + "Session Factory: " + ex.getMessage());
        throw new HibernateException("SessionFactory could not be created: " + ex.getMessage());
    }

}

From source file:edu.kit.ipd.sonar.server.HibernateUtil.java

License:Open Source License

/**
 * Rebuilds session factory. Closes old session factory and creates a new
 * one depending on a new hibernate configuration file.
 *
 * @param config/*w  ww .  j  ava2  s.  co  m*/
 *            new configuration for the session factory
 */
static void rebuildSessionFactory(final org.hibernate.cfg.Configuration config) {
    log.debug("Rebuilding the Hibernate Session Factory from new Config");
    if (sessionFactory != null && !sessionFactory.isClosed()) {
        /* if still open, close current session factory */
        sessionFactory.close();
    }
    /* build a new session factory and update static config */
    try {
        sessionFactory = config.buildSessionFactory();
    } catch (Exception e) {
        if (e instanceof java.sql.SQLException) {
            log.error("Building Hibernate Session failed due to" + " an SQLExeption: " + e.getMessage());
        } else {
            log.error("Building Hibernate Session failed due to" + " some unexpected Behaviour: "
                    + e.getMessage());
        }
        throw new HibernateException("Database Conenction could not be" + "instantiated.");
    }

    configuration = config;
}

From source file:edu.psu.iam.cpr.core.database.DBTypes.java

License:Apache License

/**
 * Constructor //from w w  w  . j ava  2  s .  co m
 * Used to initialize the Enum.
 */
private DBTypes() {

    Session session = null;

    try {
        session = SessionFactoryUtil.getSessionFactory().openSession();
        session.getTransaction().begin();

        for (int i = 0; i < typeTableNames.length; ++i) {

            Map<String, Object> map = new HashMap<String, Object>();
            final String sqlQuery = "from " + typeTableNames[i];
            final Query query = session.createQuery(sqlQuery);

            switch (i) {
            case IDENTIFIER_TYPE:
                for (final Iterator<?> it = query.list().iterator(); it.hasNext();) {
                    Object obj = it.next();
                    map.put(((IdentifierType) obj).getTypeName(), obj);
                }
                break;
            }
            typeMaps.add(map);
        }

        session.getTransaction().commit();
    } catch (HibernateException e) {
        session.getTransaction().rollback();
        throw new HibernateException(e);
    }
}