Example usage for javax.persistence PersistenceException PersistenceException

List of usage examples for javax.persistence PersistenceException PersistenceException

Introduction

In this page you can find the example usage for javax.persistence PersistenceException PersistenceException.

Prototype

public PersistenceException(String message, Throwable cause) 

Source Link

Document

Constructs a new PersistenceException exception with the specified detail message and cause.

Usage

From source file:org.batoo.jpa.jdbc.AbstractColumn.java

private Object readLob(Object value) {
    try {//from  ww w.  j ava 2s. co  m
        if (value instanceof Clob) {
            final Clob clob = (Clob) value;

            if (this.javaType == String.class) {
                final StringWriter w = new StringWriter();
                IOUtils.copy(clob.getAsciiStream(), w);
                value = w.toString();
            } else {
                final CharArrayWriter w = new CharArrayWriter((int) clob.length());
                IOUtils.copy(clob.getCharacterStream(), w);
                value = w.toCharArray();
            }
        } else if (value instanceof byte[]) {
            if (this.javaType == String.class) {
                final StringWriter w = new StringWriter();
                IOUtils.copy(new ByteArrayInputStream((byte[]) value), w);
                value = w.toString();
            } else if (this.javaType == char[].class) {
                final byte[] byteArray = (byte[]) value;

                final char[] charArray = new char[byteArray.length];

                for (int i = 0; i < charArray.length; i++) {
                    charArray[i] = (char) byteArray[i];
                }

                value = charArray;
            } else if (this.javaType != byte[].class) {
                final ObjectInputStream is = new ObjectInputStream(new ByteArrayInputStream((byte[]) value));
                try {
                    return is.readObject();
                } finally {
                    is.close();
                }
            }
        } else if (value instanceof String) {
            return value;
        } else {
            final Blob blob = (Blob) value;

            if (this.javaType == byte[].class) {
                final ByteArrayOutputStream os = new ByteArrayOutputStream();

                IOUtils.copy(blob.getBinaryStream(), os);

                value = os.toByteArray();
            } else {

                final ObjectInputStream is = new ObjectInputStream(blob.getBinaryStream());
                try {
                    value = is.readObject();
                } finally {
                    is.close();
                }
            }
        }
        return value;
    } catch (final Exception e) {
        throw new PersistenceException("Cannot read sql data", e);
    }
}

From source file:org.batoo.jpa.jdbc.ValueConverter.java

private static Object readLob(Object value, Class<?> javaType) {
    try {/*ww  w.  j  ava2  s  .  c o m*/
        if (value instanceof Clob) {
            final Clob clob = (Clob) value;

            if (javaType == String.class) {
                final StringWriter w = new StringWriter();
                IOUtils.copy(clob.getAsciiStream(), w);
                value = w.toString();
            } else {
                final CharArrayWriter w = new CharArrayWriter((int) clob.length());
                IOUtils.copy(clob.getCharacterStream(), w);
                value = w.toCharArray();
            }
        } else if (value instanceof byte[]) {
            if (javaType == String.class) {
                final StringWriter w = new StringWriter();
                IOUtils.copy(new ByteArrayInputStream((byte[]) value), w);
                value = w.toString();
            } else if (javaType == char[].class) {
                final byte[] byteArray = (byte[]) value;

                final char[] charArray = new char[byteArray.length];

                for (int i = 0; i < charArray.length; i++) {
                    charArray[i] = (char) byteArray[i];
                }

                value = charArray;
            } else if (javaType != byte[].class) {
                final ObjectInputStream is = new ObjectInputStream(new ByteArrayInputStream((byte[]) value));
                try {
                    return is.readObject();
                } finally {
                    is.close();
                }
            }
        } else if (value instanceof String) {
            return value;
        } else {
            final Blob blob = (Blob) value;

            if (javaType == byte[].class) {
                final ByteArrayOutputStream os = new ByteArrayOutputStream();

                IOUtils.copy(blob.getBinaryStream(), os);

                value = os.toByteArray();
            } else {

                final ObjectInputStream is = new ObjectInputStream(blob.getBinaryStream());
                try {
                    value = is.readObject();
                } finally {
                    is.close();
                }
            }
        }
        return value;
    } catch (final Exception e) {
        throw new PersistenceException("Cannot read sql data", e);
    }
}

From source file:org.batoo.jpa.jdbc.ValueConverter.java

/**
 * convert java objects to jdbc friendly
 * //ww w  .  j a  v a2 s  . c  o  m
 * @param value
 *            jdbc raw value
 * @param javaType
 *            type of value
 * @param temporalType
 *            temporal type
 * @param enumType
 *            enum type
 * @param lob
 *            is Lob
 * @return jdbc friendly value
 * @since 2.0.1
 */
public static Object toJdbc(Object value, Class<?> javaType, TemporalType temporalType, EnumType enumType,
        boolean lob) {
    if (value == null) {
        return null;
    }

    if (temporalType != null) {
        switch (temporalType) {
        case DATE:
            if (value instanceof java.sql.Date) {
                return value;
            }

            if (value instanceof Date) {
                return new java.sql.Date(((Date) value).getTime());
            }

            return new java.sql.Date(((Calendar) value).getTimeInMillis());
        case TIME:
            if (value instanceof java.sql.Time) {
                return value;
            }

            if (value instanceof Date) {
                return new java.sql.Time(((Date) value).getTime());
            }

            return new java.sql.Time(((Calendar) value).getTimeInMillis());
        case TIMESTAMP:
            if (value instanceof java.sql.Timestamp) {
                return value;
            }

            if (value instanceof Date) {
                return new java.sql.Timestamp(((Date) value).getTime());
            }

            return new java.sql.Timestamp(((Calendar) value).getTimeInMillis());
        }
    }

    if (Number.class.isAssignableFrom(javaType)) {
        return ReflectHelper.convertNumber((Number) value, javaType);
    }

    if (enumType != null) {
        final Enum<?> enumValue = (Enum<?>) value;
        if (enumType == EnumType.ORDINAL) {
            return enumValue.ordinal();
        }

        return enumValue.name();
    }

    if (lob) {
        try {
            if (javaType == String.class) {
                return new SerialClob(((String) value).toCharArray());
            } else if (javaType == char[].class) {
                return new SerialClob((char[]) value);
            } else if (javaType == byte[].class) {
                return new SerialBlob((byte[]) value);
            } else {
                final ByteArrayOutputStream os = new ByteArrayOutputStream();
                final ObjectOutputStream oos = new ObjectOutputStream(os);
                try {
                    oos.writeObject(value);
                } finally {
                    oos.close();
                }

                return new SerialBlob(os.toByteArray());
            }
        } catch (final Exception e) {
            throw new PersistenceException("Cannot set parameter", e);
        }
    } else {
        return value;
    }

}

From source file:org.castor.jpa.CastorEntityTransaction.java

/**
 * Roll back the current transaction/*from www  .j  a va  2s .  c om*/
 * 
 * @throws IllegalStateException
 *             if {@link #isActive()} is false.
 * @throws PersistenceException
 *             if an unexpected error condition is encountered.
 */
public void rollback() {
    // Verify transaction is active.
    verifyActive();

    try {
        // Roll back Castor transaction.
        this.database.rollback();
        // Set transaction inactive.
        this.active = false;
        // Set roll back only false.
        this.rollbackOnly = false;
        // Invalidate persistence context.
        this.entityManager.invalidatePersistenceContext();
    } catch (TransactionNotInProgressException e) {
        log.error("Could not rollback Castor transaction.", e);
        throw new PersistenceException("Could not rollback Castor transaction.", e);
    }
}

From source file:org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.java

private PersistenceException persistenceException(String message, Exception cause) {
    return new PersistenceException(getExceptionHeader() + message, cause);
}

From source file:org.jboss.ejb3.entity.PersistenceXmlLoader.java

private static Document loadURL(URL configURL, EntityResolver resolver) throws Exception {
    InputStream is = configURL != null ? configURL.openStream() : null;
    if (is == null) {
        throw new IOException("Failed to obtain InputStream from url: " + configURL);
    }/*from w  ww  .j  ava  2s  .  co  m*/
    List errors = new ArrayList();
    DocumentBuilderFactory docBuilderFactory = null;
    docBuilderFactory = DocumentBuilderFactory.newInstance();
    docBuilderFactory.setValidating(true);
    docBuilderFactory.setNamespaceAware(true);
    try {
        //otherwise Xerces fails in validation
        docBuilderFactory.setAttribute("http://apache.org/xml/features/validation/schema", true);
    } catch (IllegalArgumentException e) {
        docBuilderFactory.setValidating(false);
        docBuilderFactory.setNamespaceAware(false);
    }
    InputSource source = new InputSource(is);
    DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
    docBuilder.setEntityResolver(resolver);
    docBuilder.setErrorHandler(new PersistenceXmlLoader.ErrorLogger("XML InputStream", errors, resolver));
    Document doc = docBuilder.parse(source);
    if (errors.size() != 0) {
        throw new PersistenceException("invalid persistence.xml", (Throwable) errors.get(0));
    }
    return doc;
}

From source file:org.sonar.jpa.session.JpaDatabaseSession.java

private void internalSave(Object model, boolean flushIfNeeded) {
    try {// w w  w  .j av  a  2 s  .c om
        getEntityManager().persist(model);
    } catch (PersistenceException e) {
        /*
         * See http://jira.codehaus.org/browse/SONAR-2234
         * In some cases Hibernate can throw exceptions without meaningful information about context, so we improve them here.
         */
        throw new PersistenceException("Unable to persist : " + model, e);
    }
    if (flushIfNeeded && (++index % BATCH_SIZE == 0)) {
        commit();
    }
}

From source file:org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager.java

private void scanPackage(SpringPersistenceUnitInfo scannedUnit, String pkg) {
    if (this.componentsIndex != null) {
        Set<String> candidates = new HashSet<>();
        for (AnnotationTypeFilter filter : entityTypeFilters) {
            candidates//from  ww  w  .jav  a2 s . c o m
                    .addAll(this.componentsIndex.getCandidateTypes(pkg, filter.getAnnotationType().getName()));
        }
        candidates.forEach(scannedUnit::addManagedClassName);
        Set<String> managedPackages = this.componentsIndex.getCandidateTypes(pkg, "package-info");
        managedPackages.forEach(scannedUnit::addManagedPackage);
        return;
    }

    try {
        String pattern = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX
                + ClassUtils.convertClassNameToResourcePath(pkg) + CLASS_RESOURCE_PATTERN;
        Resource[] resources = this.resourcePatternResolver.getResources(pattern);
        MetadataReaderFactory readerFactory = new CachingMetadataReaderFactory(this.resourcePatternResolver);
        for (Resource resource : resources) {
            if (resource.isReadable()) {
                MetadataReader reader = readerFactory.getMetadataReader(resource);
                String className = reader.getClassMetadata().getClassName();
                if (matchesFilter(reader, readerFactory)) {
                    scannedUnit.addManagedClassName(className);
                    if (scannedUnit.getPersistenceUnitRootUrl() == null) {
                        URL url = resource.getURL();
                        if (ResourceUtils.isJarURL(url)) {
                            scannedUnit.setPersistenceUnitRootUrl(ResourceUtils.extractJarFileURL(url));
                        }
                    }
                } else if (className.endsWith(PACKAGE_INFO_SUFFIX)) {
                    scannedUnit.addManagedPackage(
                            className.substring(0, className.length() - PACKAGE_INFO_SUFFIX.length()));
                }
            }
        }
    } catch (IOException ex) {
        throw new PersistenceException("Failed to scan classpath for unlisted entity classes", ex);
    }
}

From source file:org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager.java

/**
 * Try to determine the persistence unit root URL based on the given
 * "defaultPersistenceUnitRootLocation".
 * @return the persistence unit root URL to pass to the JPA PersistenceProvider
 * @see #setDefaultPersistenceUnitRootLocation
 *///from w w w . j a v a  2  s.co m
@Nullable
private URL determineDefaultPersistenceUnitRootUrl() {
    if (this.defaultPersistenceUnitRootLocation == null) {
        return null;
    }
    try {
        URL url = this.resourcePatternResolver.getResource(this.defaultPersistenceUnitRootLocation).getURL();
        return (ResourceUtils.isJarURL(url) ? ResourceUtils.extractJarFileURL(url) : url);
    } catch (IOException ex) {
        throw new PersistenceException("Unable to resolve persistence unit root URL", ex);
    }
}