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:fr.keyconsulting.oliphant.NotifyListener.java

License:Open Source License

public static void attachListener(Configuration config) {
    NotifyListener listener = new NotifyListener();

    listener.config = config;/* w  w  w . j  a v a2 s. c  om*/

    PostLoadEventListener[] originalPostLoadListeners = config.getEventListeners().getPostLoadEventListeners();
    int originalPostLoadListenersSize = java.lang.reflect.Array.getLength(originalPostLoadListeners);
    PostLoadEventListener[] postLoadEventListeners = new PostLoadEventListener[originalPostLoadListenersSize
            + 1];
    postLoadEventListeners[0] = listener;
    System.arraycopy(originalPostLoadListeners, 0, postLoadEventListeners, 1, originalPostLoadListenersSize);
    config.getEventListeners().setPostLoadEventListeners(postLoadEventListeners);

    PersistEventListener[] originalPersistEventListeners = config.getEventListeners()
            .getPersistEventListeners();
    int originalPersistEventListenersSize = java.lang.reflect.Array.getLength(originalPersistEventListeners);
    PersistEventListener[] persistEventListeners = new PersistEventListener[originalPersistEventListenersSize
            + 1];
    persistEventListeners[0] = listener;
    System.arraycopy(originalPersistEventListeners, 0, persistEventListeners, 1,
            originalPersistEventListenersSize);
    config.getEventListeners().setPersistEventListeners(persistEventListeners);

    FlushEntityEventListener[] originalFlushEntityEventListeners = config.getEventListeners()
            .getFlushEntityEventListeners();
    int originalFlushEntityEventListenersSize = java.lang.reflect.Array
            .getLength(originalFlushEntityEventListeners);
    FlushEntityEventListener[] flushEntityEventListeners = new FlushEntityEventListener[originalFlushEntityEventListenersSize
            + 1];
    flushEntityEventListeners[0] = listener;
    System.arraycopy(originalFlushEntityEventListeners, 0, flushEntityEventListeners, 1,
            originalFlushEntityEventListenersSize);
    config.getEventListeners().setFlushEntityEventListeners(flushEntityEventListeners);

    PreUpdateEventListener[] originalPreUpdateEventListeners = config.getEventListeners()
            .getPreUpdateEventListeners();
    int originalPreUpdateEventListenersSize = java.lang.reflect.Array
            .getLength(originalPreUpdateEventListeners);
    PreUpdateEventListener[] preUpdateEventListeners = new PreUpdateEventListener[originalPreUpdateEventListenersSize
            + 1];
    preUpdateEventListeners[0] = listener;
    System.arraycopy(originalPreUpdateEventListeners, 0, preUpdateEventListeners, 1,
            originalPreUpdateEventListenersSize);
    config.getEventListeners().setPreUpdateEventListeners(preUpdateEventListeners);
    try {
        Class specListClass = Class.forName(config.getProperty("oliphant.specific_listener"));
        listener.specificNotifyListener = (SpecificNotifyListener) specListClass.newInstance();
        listener.specificNotifyListener.prepare(config);
    } catch (ClassNotFoundException e) {
        throw new HibernateException(e);
    } catch (InstantiationException e) {
        throw new HibernateException(e);
    } catch (IllegalAccessException e) {
        throw new HibernateException(e);
    }
    String allowStaleString = config.getProperty("oliphant.allow_stale_load");
    if ((allowStaleString != null) && (allowStaleString.equals("false"))) {
        listener.allowStaleLoad = false;
    }
}

From source file:fr.keyconsulting.oliphant.postgresql.PostgreSQLListenerAuxiliary.java

License:Open Source License

public String sqlCreateString(Dialect dialect, Mapping mapping, String defaultCatalog, String defaultSchema) {
    StringBuilder sb = new StringBuilder();

    for (Iterator i = config.getClassMappings(); i.hasNext();) {
        PersistentClass c = (PersistentClass) i.next();
        Table table = c.getTable();/*www. java2s .c  om*/
        if (table.getPrimaryKey().getColumnSpan() > 1) {
            throw new HibernateException(
                    "Oliphant does not support primary keys that span multiple columns. Objects of class "
                            + c.getClassName() + " will not be monitored for changes.");
        }
        String tableName = table.getName().toLowerCase();

        String idColName = table.getPrimaryKey().getColumn(0).getName();

        Iterator verCols = c.getVersion().getColumnIterator();
        if (!verCols.hasNext()) {
            throw new HibernateException(
                    "Oliphant does not support version properties that span multiple columns. Objects of class "
                            + c.getClassName() + " will not be monitored for changes.");
        }
        Column verCol = (Column) verCols.next();
        String verColName = verCol.getName();
        if (verCols.hasNext()) {
            throw new HibernateException("Oliphant does not support non versioned entities. Objects of class "
                    + c.getClassName() + " will not be monitored for changes.");
        }
        sb.append("CREATE OR REPLACE FUNCTION oliphant_" + tableName + "() RETURNS TRIGGER AS $$\n");
        sb.append("   DECLARE\n");
        sb.append("      VERSION TEXT;\n");
        sb.append("   BEGIN\n");
        sb.append("      IF TG_OP = 'UPDATE' THEN\n");
        sb.append("         VERSION := NEW." + verColName + ";\n");
        sb.append("      ELSIF TG_OP = 'DELETE' THEN\n");
        sb.append("         VERSION := -1;\n");
        sb.append("      END IF;\n");
        sb.append("      PERFORM send_notify('oliphant', '" + tableName + "#' || encode(text(OLD." + idColName
                + ")::bytea,'base64') || '###' || encode(text(VERSION)::bytea,'base64')); RETURN NULL;\n");
        sb.append("   END;\n");
        sb.append("$$ LANGUAGE 'plpgsql';\n");
        sb.append("\n");
        sb.append("CREATE TRIGGER oliphant_" + tableName + "_trg\n");
        sb.append("   AFTER DELETE OR UPDATE ON " + tableName + "\n");
        sb.append("   FOR EACH ROW EXECUTE PROCEDURE oliphant_" + tableName + "();\n");
        sb.append("\n");
    }

    return sb.toString();
}

From source file:fr.keyconsulting.oliphant.postgresql.PostgreSQLNotifyListener.java

License:Open Source License

public void setUp() {
    try {//from  ww w.j  a  v  a  2  s .  c o m
        conn = DriverManager.getConnection(config.getProperty("hibernate.connection.url"),
                config.getProperty("hibernate.connection.username"),
                config.getProperty("hibernate.connection.password"));
        pgConn = (PGConnection) conn;
        Statement stmt = conn.createStatement();
        stmt.execute("LISTEN oliphant");
        stmt.close();
    } catch (SQLException sqle) {
        throw new HibernateException(sqle);
    }
}

From source file:fr.keyconsulting.oliphant.postgresql.PostgreSQLNotifyListener.java

License:Open Source License

public List<Notification> getLatestUpdates() {
    List<Notification> notifs = new ArrayList<Notification>();

    try {/*from ww w .  j a  va2 s.c  o  m*/
        // issue a dummy query to contact the backend and receive any pending notifications.
        Statement stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery("SELECT 1");
        rs.close();
        stmt.close();

        PGNotification notifications[] = pgConn.getNotifications();
        if (notifications != null) {
            for (int i = 0; i < notifications.length; i++) {
                LOG.debug("Notif from PostgreSQL : " + notifications[i].getParameter());
                notifs.add(new Notification(notifications[i].getParameter().split("###")));
            }
        }
    } catch (SQLException sqle) {
        throw new HibernateException(sqle);
    }

    return notifs;
}

From source file:fr.keyconsulting.oliphant.postgresql.PostgreSQLNotifyListener.java

License:Open Source License

public void tearDown() {
    try {//from ww w. jav  a 2s  . c om
        conn.close();
    } catch (SQLException sqle) {
        throw new HibernateException(sqle);
    }
}

From source file:gov.nih.nci.caarray.util.CaArrayAuditLogInterceptor.java

License:BSD License

/**
 * {@inheritDoc}//from w  w  w.  j  ava  2s . co  m
 */
@Override
public void onCollectionUpdate(Object collection, Serializable key) {
    if (!(collection instanceof PersistentCollection)) {
        return;
    }

    PersistentCollection pc = (PersistentCollection) collection;
    Object owner = pc.getOwner();
    if (!(processor.isAuditableEntity(owner))) {
        return;
    }
    if (audits.get() == null) {
        audits.set(new HashSet<AuditLogHelper>());
    }

    String role = pc.getRole();

    Serializable oldSerial = pc.getStoredSnapshot();
    Object oldV = null;
    if (oldSerial != null && pc instanceof PersistentSet) {
        // PersistentSet seems to build a strange map where the key is also the value.
        oldV = ((Map) oldSerial).keySet();
    } else {
        oldV = oldSerial;
    }
    Object newV = pc.getValue();

    int idx = role.lastIndexOf('.');
    String className = role.substring(0, idx);
    String property = role.substring(idx + 1);
    Map<String, String> tabColMA = getColumnTableName(className, property);

    AuditLogRecord record = getOrCreateRecord(owner, key, className, tabColMA.get(TABLE_NAME),
            AuditType.UPDATE);
    Getter getter;
    try {
        getter = getIdGetter(Class.forName(className));
    } catch (ClassNotFoundException ex) {
        throw new HibernateException(ex);
    }
    AuditLogHelper helper = new AuditLogHelper(record, owner, getter);
    audits.get().add(helper);
    helper.getDetails().add(new DetailHelper(property, tabColMA.get(COLUMN_NAME), oldV, newV));
}

From source file:gov.nih.nci.common.util.StringClobType.java

License:Open Source License

/**
 * Writes an instance of the mapped class to a prepared statement
 * @param st - PreparedStatement//from  w  w w. j  a v a2 s.c o m
 * @param value
 * @param index
 */
public void nullSafeSet(PreparedStatement st, Object value, int index) throws HibernateException, SQLException {
    //         st.setClob(index, Hibernate.createClob((String) value));
    DatabaseMetaData dbMetaData = st.getConnection().getMetaData();
    if (value == null) {
        st.setNull(index, sqlTypes()[0]);
    } else if (ORACLE_DRIVER_NAME.equals(dbMetaData.getDriverName())) {
        if ((dbMetaData.getDriverMajorVersion() >= ORACLE_DRIVER_MAJOR_VERSION)
                && (dbMetaData.getDriverMinorVersion() >= ORACLE_DRIVER_MINOR_VERSION)) {
            try {
                // Code compliments of Scott Miller
                // support oracle clobs without requiring oracle libraries
                // at compile time
                // Note this assumes that if you are using the Oracle Driver.
                // then you have access to the oracle.sql.CLOB class

                // First get the oracle clob class
                Class oracleClobClass = Class.forName("oracle.sql.CLOB");

                // Get the oracle connection class for checking
                Class oracleConnectionClass = Class.forName("oracle.jdbc.OracleConnection");

                // now get the static factory method
                Class partypes[] = new Class[3];
                partypes[0] = Connection.class;
                partypes[1] = Boolean.TYPE;
                partypes[2] = Integer.TYPE;
                Method createTemporaryMethod = oracleClobClass.getDeclaredMethod("createTemporary", partypes);
                // now get ready to call the factory method
                Field durationSessionField = oracleClobClass.getField("DURATION_SESSION");
                Object arglist[] = new Object[3];
                Connection conn = st.getConnection();

                // Make sure connection object is right type
                if (!oracleConnectionClass.isAssignableFrom(conn.getClass())) {
                    if (conn.getClass().getName().startsWith("org.jboss")) {
                        conn = ((WrappedConnection) conn).getUnderlyingConnection();
                    }

                    if (!oracleConnectionClass.isAssignableFrom(conn.getClass())) {
                        throw new HibernateException(
                                "JDBC connection object must be a oracle.jdbc.OracleConnection. "
                                        + "Connection class is " + conn.getClass().getName());
                    }
                }

                arglist[0] = conn;
                arglist[1] = Boolean.TRUE;
                arglist[2] = durationSessionField.get(null); //null is valid because of static field

                // Create our CLOB
                Object tempClob = createTemporaryMethod.invoke(null, arglist); //null is valid because of static method

                // get the open method
                partypes = new Class[1];
                partypes[0] = Integer.TYPE;
                Method openMethod = oracleClobClass.getDeclaredMethod("open", partypes);

                // prepare to call the method
                Field modeReadWriteField = oracleClobClass.getField("MODE_READWRITE");
                arglist = new Object[1];
                arglist[0] = modeReadWriteField.get(null); //null is valid because of static field

                // call open(CLOB.MODE_READWRITE);
                openMethod.invoke(tempClob, arglist);

                // get the getCharacterOutputStream method
                Method getCharacterOutputStreamMethod = oracleClobClass
                        .getDeclaredMethod("getCharacterOutputStream", null);

                // call the getCharacterOutpitStream method
                Writer tempClobWriter = (Writer) getCharacterOutputStreamMethod.invoke(tempClob, null);

                // write the string to the clob
                tempClobWriter.write((String) value);
                tempClobWriter.flush();
                tempClobWriter.close();

                // get the close method
                Method closeMethod = oracleClobClass.getDeclaredMethod("close", null);

                // call the close method
                closeMethod.invoke(tempClob, null);

                // add the clob to the statement
                st.setClob(index, (Clob) tempClob);
            } catch (ClassNotFoundException e) {
                // could not find the class with reflection
                throw new HibernateException("Unable to find a required class.\n" + e.getMessage());
            } catch (NoSuchMethodException e) {
                // could not find the metho with reflection
                throw new HibernateException("Unable to find a required method.\n" + e.getMessage());
            } catch (NoSuchFieldException e) {
                // could not find the field with reflection
                throw new HibernateException("Unable to find a required field.\n" + e.getMessage());
            } catch (IllegalAccessException e) {
                throw new HibernateException("Unable to access a required method or field.\n" + e.getMessage());
            } catch (InvocationTargetException e) {
                throw new HibernateException(e.getMessage());
            } catch (IOException e) {
                throw new HibernateException(e.getMessage());
            }
        } else {
            throw new HibernateException("No CLOBS support. Use driver version " + ORACLE_DRIVER_MAJOR_VERSION
                    + ", minor " + ORACLE_DRIVER_MINOR_VERSION);
        }
    } else {
        String str = (String) value;
        StringReader r = new StringReader(str);
        st.setCharacterStream(index, r, str.length());
    }

}

From source file:gov.nih.nci.iso21090.hibernate.tuple.IsoConstantTuplizerHelper.java

License:BSD License

@SuppressWarnings("PMD.CyclomaticComplexity")
private void setConstantValues(Object parent, Object property, String propertyName, ComplexNode complexNode,
        boolean processParts) {

    if (complexNode == null && property == null) {
        setNullFlavor(parent, propertyName);
        return;//  w w w.j a  v a 2s.  c  o  m
    } else if (complexNode == null && property != null) {
        setNullFlavor(property);
        return;
    }

    if (property == null) {
        setNullFlavor(parent, complexNode);
        return;
    } else if (Any.class.isAssignableFrom(property.getClass()) && ((Any) property).getNullFlavor() != null) {
        return;
    } else if (DSet.class.isAssignableFrom(property.getClass())
            && (((DSet) property).getItem() == null || ((DSet) property).getItem().size() == 0)) {
        setNullFlavor(parent, complexNode);
        return;
    } else {
        for (Node node : complexNode.getInnerNodes()) {
            if ((node instanceof ConstantNode) && !(NULL_FLAVOR_ATTRIBUTE.equals(node.getName()))) {
                setValue(property, node.getName(), ((ConstantNode) node).getInstance());
            }
        }

        for (Node node : complexNode.getInnerNodes()) {

            if (node instanceof ComplexNode) {

                if (!node.getName().startsWith("part_")) {
                    Object existingObject = getPropertyObject(property, node.getName());
                    if (existingObject == null) {
                        setNullFlavor(property, (ComplexNode) node);
                    } else {

                        if (Any.class.isAssignableFrom(existingObject.getClass())) {
                            setConstantValues(property, existingObject, node.getName(), (ComplexNode) node,
                                    processParts);
                        } else if (Set.class.isAssignableFrom(existingObject.getClass())) {
                            for (Object obj : (Set) existingObject) {
                                setConstantValues(property, obj, node.getName(), (ComplexNode) node,
                                        processParts);
                            }
                        }
                    }
                } else if (processParts) {
                    List partList = (List) getPropertyObject(property, "part");
                    Integer index = Integer.parseInt(node.getName().substring("part_".length()));

                    if (partList != null) {
                        if (partList.size() < index) {
                            throw new HibernateException("Can not set constant as part.size()<part[index]");
                        }
                        setConstantValues(property, partList.get(index), node.getName(), (ComplexNode) node,
                                processParts);
                    }
                }
            }
        }
        setNullFlavor(property);
    }
}

From source file:gov.nih.nci.iso21090.hibernate.tuple.IsoConstantTuplizerHelper.java

License:BSD License

private Object getPropertyObject(Object parent, String propertyName) {
    try {/*  w w  w .  j  av  a2 s  .  c  om*/

        Field propertyField = findFieldInClass(parent.getClass(), propertyName);
        propertyField.setAccessible(true);
        return propertyField.get(parent);

    } catch (SecurityException e) {
        throw new HibernateException(e);
    } catch (IllegalAccessException e) {
        throw new HibernateException(e);
    }
}

From source file:gov.nih.nci.iso21090.hibernate.tuple.IsoConstantTuplizerHelper.java

License:BSD License

private void setValue(Object parent, String propertyName, Object instance) {
    try {/*  w w w  .j  ava  2 s .c  o  m*/

        Field propertyField = findFieldInClass(parent.getClass(), propertyName);
        propertyField.setAccessible(true);
        Object converteValue = convertValue(instance, propertyField.getType());
        propertyField.set(parent, converteValue);

    } catch (SecurityException e) {
        throw new HibernateException(e);
    } catch (IllegalAccessException e) {
        throw new HibernateException(e);
    } catch (IllegalArgumentException e) {
        throw new HibernateException(e);
    }
}