use of javax.persistence.PersistenceException in project ORCID-Source by ORCID.
the class ResearcherUrlDaoTest method testCannotAddDuplicatedResearcherUrl.
@Test
@Rollback(true)
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void testCannotAddDuplicatedResearcherUrl() {
try {
ResearcherUrlEntity newRUrl = new ResearcherUrlEntity();
newRUrl.setDateCreated(new Date());
newRUrl.setLastModified(new Date());
newRUrl.setClientSourceId("4444-4444-4444-4443");
newRUrl.setUrl("http://www.researcherurl2.com?id=1");
newRUrl.setUrlName("test");
newRUrl.setUser(new ProfileEntity("4444-4444-4444-4443"));
newRUrl.setVisibility(Visibility.PUBLIC);
newRUrl = dao.merge(newRUrl);
assertNotNull(newRUrl);
fail();
} catch (PersistenceException e) {
}
}
use of javax.persistence.PersistenceException in project learn-hanzi by reinardhz.
the class HanziServiceImpl method insertHanzi.
/**
* A method to insert inputted hanzi to database.
*
* If the data successfully inserted to database , return the successfull inserted hanzi and its created date in json format.
* Response json string example: {"hanzi_data":[{"hanzi":"會", "created_date":"1491448282654"}]}. <br/>
*
* <br/>
*
* @param hanzi - String hanzi to insert.
* @return String result - The inserted hanzi data in json format, or String: "Error: Cannot insert. Data already exist.", if trying to insert the already inserted data.
* @throws Exception - If errors occurs when inserting data to database.
*/
public String insertHanzi(String input) throws Exception {
try {
logger.info("Inserting hanzi to database...");
logger.debug("preparing the data...");
HanziData inputHanziData = new HanziData();
inputHanziData.setHanzi(input);
inputHanziData.setCreated_date(System.currentTimeMillis());
logger.debug("preparing the child...");
Set<UserAndHanzi> childs = new HashSet<UserAndHanzi>();
UserAndHanzi child = new UserAndHanzi();
UserData userData = new UserData();
// manual input
userData.setUser_id(1L);
child.setUserData(userData);
child.setHanziData(inputHanziData);
childs.add(child);
// add the child
logger.debug("adding the child to the data...");
inputHanziData.setUserAndHanzi(childs);
logger.debug("call dao, to insert data to database");
HanziData insertedHanziData = hanziDaoImpl.insert(inputHanziData);
logger.info("Insert hanzi to database succeed");
logger.info("Converting the inserted data to json object...");
logger.debug("Preparing the json object...");
HanziDataJsonResponseObject resultJsonObject = new HanziDataJsonResponseObject();
logger.debug("Preparing the child json object...");
Hanzi_data resultChildJsonObject = new Hanzi_data();
resultChildJsonObject.setHanzi(insertedHanziData.getHanzi());
resultChildJsonObject.setCreated_date(String.valueOf(insertedHanziData.getCreated_date()));
logger.debug("Converting the child json object into array...");
List<Hanzi_data> var = new ArrayList<>();
var.add(resultChildJsonObject);
Hanzi_data[] resultChildJsonArray = var.<Hanzi_data>toArray(new Hanzi_data[0]);
logger.debug("Adding the array into json object...");
resultJsonObject.setHanzi_data(resultChildJsonArray);
logger.debug("Converting json object into json string...");
ObjectMapper mapper = new ObjectMapper();
String result = mapper.writeValueAsString(resultJsonObject);
return result;
} catch (PersistenceException pe) {
logger.error("Cannot insert. Data already exist.");
return "Error: Cannot insert. Data already exist.";
} catch (Exception e) {
logger.error("Unexpected error occurred when inserting hanzi to database.");
throw e;
}
}
use of javax.persistence.PersistenceException in project hibernate-orm by hibernate.
the class CallbackBuilderLegacyImpl method resolveCallbacks.
@SuppressWarnings({ "unchecked", "WeakerAccess" })
public Callback[] resolveCallbacks(XClass beanClass, CallbackType callbackType, ReflectionManager reflectionManager) {
List<Callback> callbacks = new ArrayList<>();
List<String> callbacksMethodNames = new ArrayList<>();
List<Class> orderedListeners = new ArrayList<>();
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);
}
ReflectHelper.ensureAccessibility(method);
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<>();
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(managedBeanRegistry.getBean(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);
}
ReflectHelper.ensureAccessibility(method);
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()]);
}
use of javax.persistence.PersistenceException in project hibernate-orm by hibernate.
the class EntityManagerTest method testPersistExisting.
@Test
public void testPersistExisting() throws Exception {
EntityManager em = getOrCreateEntityManager();
em.getTransaction().begin();
Wallet w = new Wallet();
w.setBrand("Lacoste");
w.setModel("Minimic");
w.setSerial("0100202002");
em.persist(w);
w = new Wallet();
w.setBrand("Lacoste");
w.setModel("Minimic");
w.setSerial("0100202002");
try {
em.persist(w);
} catch (EntityExistsException eee) {
// success
if (em.getTransaction() != null) {
em.getTransaction().rollback();
}
em.close();
return;
}
try {
em.getTransaction().commit();
fail("Should have raised an exception");
} catch (PersistenceException pe) {
} finally {
em.close();
}
}
use of javax.persistence.PersistenceException in project hibernate-orm by hibernate.
the class AttributeConverterSqlTypeDescriptorAdapter method getBinder.
// Binding ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@Override
@SuppressWarnings("unchecked")
public <X> ValueBinder<X> getBinder(JavaTypeDescriptor<X> javaTypeDescriptor) {
// Get the binder for the intermediate type representation
final ValueBinder realBinder = delegate.getBinder(intermediateJavaTypeDescriptor);
return new ValueBinder<X>() {
@Override
public void bind(PreparedStatement st, X value, int index, WrapperOptions options) throws SQLException {
final Object convertedValue;
try {
convertedValue = converter.toRelationalValue(value);
} catch (PersistenceException pe) {
throw pe;
} catch (RuntimeException re) {
throw new PersistenceException("Error attempting to apply AttributeConverter", re);
}
log.debugf("Converted value on binding : %s -> %s", value, convertedValue);
realBinder.bind(st, convertedValue, index, options);
}
@Override
public void bind(CallableStatement st, X value, String name, WrapperOptions options) throws SQLException {
final Object convertedValue;
try {
convertedValue = converter.toRelationalValue(value);
} catch (PersistenceException pe) {
throw pe;
} catch (RuntimeException re) {
throw new PersistenceException("Error attempting to apply AttributeConverter", re);
}
log.debugf("Converted value on binding : %s -> %s", value, convertedValue);
realBinder.bind(st, convertedValue, name, options);
}
};
}
Aggregations