Search in sources :

Example 71 with PersistenceException

use of javax.persistence.PersistenceException in project hibernate-orm by hibernate.

the class ListenerFactoryStandardImpl method buildListener.

@Override
@SuppressWarnings("unchecked")
public <T> Listener<T> buildListener(Class<T> listenerClass) {
    ListenerImpl listenerImpl = listenerInstances.get(listenerClass);
    if (listenerImpl == null) {
        try {
            T listenerInstance = listenerClass.newInstance();
            listenerImpl = new ListenerImpl(listenerInstance);
        } catch (Exception e) {
            throw new PersistenceException("Unable to create instance of " + listenerClass.getName() + " as a JPA callback listener", e);
        }
        ListenerImpl existing = listenerInstances.putIfAbsent(listenerClass, listenerImpl);
        if (existing != null) {
            listenerImpl = existing;
        }
    }
    return (Listener<T>) listenerImpl;
}
Also used : Listener(org.hibernate.jpa.event.spi.jpa.Listener) PersistenceException(javax.persistence.PersistenceException) PersistenceException(javax.persistence.PersistenceException)

Example 72 with PersistenceException

use of javax.persistence.PersistenceException in project hibernate-orm by hibernate.

the class PersistenceXmlParser method validate.

private void validate(Document document) {
    // todo : add ability to disable validation...
    final Validator validator;
    final String version = document.getDocumentElement().getAttribute("version");
    if ("2.1".equals(version)) {
        validator = v21Schema().newValidator();
    } else if ("2.0".equals(version)) {
        validator = v2Schema().newValidator();
    } else if ("1.0".equals(version)) {
        validator = v1Schema().newValidator();
    } else {
        throw new PersistenceException("Unrecognized persistence.xml version [" + version + "]");
    }
    List<SAXException> errors = new ArrayList<SAXException>();
    validator.setErrorHandler(new ErrorHandlerImpl(errors));
    try {
        validator.validate(new DOMSource(document));
    } catch (SAXException e) {
        errors.add(e);
    } catch (IOException e) {
        throw new PersistenceException("Unable to validate persistence.xml", e);
    }
    if (errors.size() != 0) {
        //report all errors in the exception
        StringBuilder errorMessage = new StringBuilder();
        for (SAXException error : errors) {
            errorMessage.append(extractInfo(error)).append('\n');
        }
        throw new PersistenceException("Invalid persistence.xml.\n" + errorMessage.toString());
    }
}
Also used : DOMSource(javax.xml.transform.dom.DOMSource) PersistenceException(javax.persistence.PersistenceException) ArrayList(java.util.ArrayList) IOException(java.io.IOException) Validator(javax.xml.validation.Validator) SAXException(org.xml.sax.SAXException)

Example 73 with PersistenceException

use of javax.persistence.PersistenceException in project hibernate-orm by hibernate.

the class PersistenceXmlParser method loadUrl.

private Document loadUrl(URL xmlUrl) {
    final String resourceName = xmlUrl.toExternalForm();
    try {
        URLConnection conn = xmlUrl.openConnection();
        //avoid JAR locking on Windows and Tomcat
        conn.setUseCaches(false);
        try {
            InputStream inputStream = conn.getInputStream();
            try {
                final InputSource inputSource = new InputSource(inputStream);
                try {
                    DocumentBuilder documentBuilder = documentBuilderFactory().newDocumentBuilder();
                    try {
                        Document document = documentBuilder.parse(inputSource);
                        validate(document);
                        return document;
                    } catch (SAXException e) {
                        throw new PersistenceException("Unexpected error parsing [" + resourceName + "]", e);
                    } catch (IOException e) {
                        throw new PersistenceException("Unexpected error parsing [" + resourceName + "]", e);
                    }
                } catch (ParserConfigurationException e) {
                    throw new PersistenceException("Unable to generate javax.xml.parsers.DocumentBuilder instance", e);
                }
            } finally {
                try {
                    inputStream.close();
                } catch (Exception ignored) {
                }
            }
        } catch (IOException e) {
            throw new PersistenceException("Unable to obtain input stream from [" + resourceName + "]", e);
        }
    } catch (IOException e) {
        throw new PersistenceException("Unable to access [" + resourceName + "]", e);
    }
}
Also used : InputSource(org.xml.sax.InputSource) DocumentBuilder(javax.xml.parsers.DocumentBuilder) InputStream(java.io.InputStream) PersistenceException(javax.persistence.PersistenceException) IOException(java.io.IOException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) Document(org.w3c.dom.Document) URLConnection(java.net.URLConnection) IOException(java.io.IOException) SAXParseException(org.xml.sax.SAXParseException) PersistenceException(javax.persistence.PersistenceException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) SAXException(org.xml.sax.SAXException) XsdException(org.hibernate.internal.util.xml.XsdException) SAXException(org.xml.sax.SAXException)

Example 74 with PersistenceException

use of javax.persistence.PersistenceException in project hibernate-orm by hibernate.

the class CallbackBuilderLegacyImpl method resolveCallbacks.

public Callback[] resolveCallbacks(XClass beanClass, CallbackType callbackType, ReflectionManager reflectionManager) {
    List<Callback> callbacks = new ArrayList<Callback>();
    //used to track overridden methods
    List<String> callbacksMethodNames = new ArrayList<String>();
    List<Class> orderedListeners = new ArrayList<Class>();
    XClass currentClazz = beanClass;
    boolean stopListeners = false;
    boolean stopDefaultListeners = false;
    do {
        Callback callback = null;
        List<XMethod> methods = currentClazz.getDeclaredMethods();
        for (final XMethod xMethod : methods) {
            if (xMethod.isAnnotationPresent(callbackType.getCallbackAnnotation())) {
                Method method = reflectionManager.toMethod(xMethod);
                final String methodName = method.getName();
                if (!callbacksMethodNames.contains(methodName)) {
                    //overridden method, remove the superclass overridden method
                    if (callback == null) {
                        callback = new EntityCallback(method, callbackType);
                        Class returnType = method.getReturnType();
                        Class[] args = method.getParameterTypes();
                        if (returnType != Void.TYPE || args.length != 0) {
                            throw new RuntimeException("Callback methods annotated on the bean class must return void and take no arguments: " + callbackType.getCallbackAnnotation().getName() + " - " + xMethod);
                        }
                        method.setAccessible(true);
                        log.debugf("Adding %s as %s callback for entity %s", methodName, callbackType.getCallbackAnnotation().getSimpleName(), beanClass.getName());
                        //superclass first
                        callbacks.add(0, callback);
                        callbacksMethodNames.add(0, methodName);
                    } else {
                        throw new PersistenceException("You can only annotate one callback method with " + callbackType.getCallbackAnnotation().getName() + " in bean class: " + beanClass.getName());
                    }
                }
            }
        }
        if (!stopListeners) {
            getListeners(currentClazz, orderedListeners);
            stopListeners = currentClazz.isAnnotationPresent(ExcludeSuperclassListeners.class);
            stopDefaultListeners = currentClazz.isAnnotationPresent(ExcludeDefaultListeners.class);
        }
        do {
            currentClazz = currentClazz.getSuperclass();
        } while (currentClazz != null && !(currentClazz.isAnnotationPresent(Entity.class) || currentClazz.isAnnotationPresent(MappedSuperclass.class)));
    } while (currentClazz != null);
    //handle default listeners
    if (!stopDefaultListeners) {
        List<Class> defaultListeners = (List<Class>) reflectionManager.getDefaults().get(EntityListeners.class);
        if (defaultListeners != null) {
            int defaultListenerSize = defaultListeners.size();
            for (int i = defaultListenerSize - 1; i >= 0; i--) {
                orderedListeners.add(defaultListeners.get(i));
            }
        }
    }
    for (Class listener : orderedListeners) {
        Callback callback = null;
        if (listener != null) {
            XClass xListener = reflectionManager.toXClass(listener);
            callbacksMethodNames = new ArrayList<String>();
            List<XMethod> methods = xListener.getDeclaredMethods();
            for (final XMethod xMethod : methods) {
                if (xMethod.isAnnotationPresent(callbackType.getCallbackAnnotation())) {
                    final Method method = reflectionManager.toMethod(xMethod);
                    final String methodName = method.getName();
                    if (!callbacksMethodNames.contains(methodName)) {
                        //overridden method, remove the superclass overridden method
                        if (callback == null) {
                            callback = new ListenerCallback(jpaListenerFactory.buildListener(listener), method, callbackType);
                            Class returnType = method.getReturnType();
                            Class[] args = method.getParameterTypes();
                            if (returnType != Void.TYPE || args.length != 1) {
                                throw new PersistenceException("Callback methods annotated in a listener bean class must return void and take one argument: " + callbackType.getCallbackAnnotation().getName() + " - " + method);
                            }
                            if (!method.isAccessible()) {
                                method.setAccessible(true);
                            }
                            log.debugf("Adding %s as %s callback for entity %s", methodName, callbackType.getCallbackAnnotation().getSimpleName(), beanClass.getName());
                            // listeners first
                            callbacks.add(0, callback);
                        } else {
                            throw new PersistenceException("You can only annotate one callback method with " + callbackType.getCallbackAnnotation().getName() + " in bean class: " + beanClass.getName() + " and callback listener: " + listener.getName());
                        }
                    }
                }
            }
        }
    }
    return callbacks.toArray(new Callback[callbacks.size()]);
}
Also used : ArrayList(java.util.ArrayList) XMethod(org.hibernate.annotations.common.reflection.XMethod) Method(java.lang.reflect.Method) XClass(org.hibernate.annotations.common.reflection.XClass) EntityListeners(javax.persistence.EntityListeners) Callback(org.hibernate.jpa.event.spi.jpa.Callback) XMethod(org.hibernate.annotations.common.reflection.XMethod) ExcludeDefaultListeners(javax.persistence.ExcludeDefaultListeners) PersistenceException(javax.persistence.PersistenceException) XClass(org.hibernate.annotations.common.reflection.XClass) ArrayList(java.util.ArrayList) List(java.util.List) ExcludeSuperclassListeners(javax.persistence.ExcludeSuperclassListeners)

Example 75 with PersistenceException

use of javax.persistence.PersistenceException in project hibernate-orm by hibernate.

the class EntityManagerFactoryBuilderImpl method generateSchema.

@Override
public void generateSchema() {
    // Metamodel will clean this up...
    try {
        SessionFactoryBuilder sfBuilder = metadata().getSessionFactoryBuilder();
        populate(sfBuilder, standardServiceRegistry);
        SchemaManagementToolCoordinator.process(metadata, standardServiceRegistry, configurationValues, DelayedDropRegistryNotAvailableImpl.INSTANCE);
    } catch (Exception e) {
        throw persistenceException("Error performing schema management", e);
    }
    // release this builder
    cancel();
}
Also used : SessionFactoryBuilder(org.hibernate.boot.SessionFactoryBuilder) PersistenceException(javax.persistence.PersistenceException) EntityNotFoundException(javax.persistence.EntityNotFoundException)

Aggregations

PersistenceException (javax.persistence.PersistenceException)125 Test (org.junit.Test)66 Session (org.hibernate.Session)50 Transaction (org.hibernate.Transaction)29 EntityManager (javax.persistence.EntityManager)17 IOException (java.io.IOException)12 StaleObjectStateException (org.hibernate.StaleObjectStateException)10 ArrayList (java.util.ArrayList)9 List (java.util.List)9 ConstraintViolationException (org.hibernate.exception.ConstraintViolationException)9 SQLGrammarException (org.hibernate.exception.SQLGrammarException)8 TransactionRequiredException (javax.persistence.TransactionRequiredException)7 MessagesEvent (com.openmeap.event.MessagesEvent)5 EntityNotFoundException (javax.persistence.EntityNotFoundException)5 OptimisticLockException (javax.persistence.OptimisticLockException)5 TestForIssue (org.hibernate.testing.TestForIssue)5 GlobalSettings (com.openmeap.model.dto.GlobalSettings)4 NoResultException (javax.persistence.NoResultException)4 LockOptions (org.hibernate.LockOptions)4 StaleStateException (org.hibernate.StaleStateException)4