List of usage examples for javax.persistence EntityManager flush
public void flush();
From source file:org.rhq.enterprise.server.alert.AlertDefinitionWithComplexNotificationsTest.java
private void prepareDB() { executeInTransaction(false, new TransactionCallback() { @Override/* w w w. ja v a2 s .co m*/ public void execute() throws Exception { EntityManager em = getEntityManager(); agent = new Agent(universalName, "localhost", 0, "foo", "bar"); server = new Server(); server.setAddress("localhost"); server.setName(universalName); server.setOperationMode(OperationMode.NORMAL); server.setAgents(Collections.singletonList(agent)); role = new Role(universalName); role.addPermission(Permission.MANAGE_INVENTORY); role.addPermission(Permission.MANAGE_SETTINGS); subject = new Subject(universalName, true, false); subject.addRole(role); resourceType = new ResourceTypeBuilder().createPlatformResourceType().withId(0) .withName(universalName).withPlugin(universalName).build(); MeasurementDefinition md = new MeasurementDefinition(universalName, MeasurementCategory.PERFORMANCE, MeasurementUnits.PERCENTAGE, DataType.MEASUREMENT, false, 100000, DisplayType.DETAIL); resourceType.addMetricDefinition(md); resourceGroup = new ResourceGroup(universalName, resourceType); resources = new LinkedHashSet<Resource>(); for (int i = 0; i < 10; ++i) { Resource res = createResourceForTest(universalName + i); resources.add(res); resourceGroup.addExplicitResource(res); } templateAlertDefinition = createDefinitionForTest("template", true); templateAlertDefinition.setResourceType(resourceType); groupAlertDefinition = createDefinitionForTest("group", true); groupAlertDefinition.setGroup(resourceGroup); resourceAlertDefinition = createDefinitionForTest("resource", true); resourceAlertDefinition.setResource(resources.iterator().next()); em.persist(agent); em.persist(server); em.persist(role); em.persist(subject); em.persist(resourceType); em.persist(resourceGroup); for (Resource r : resources) { em.persist(r); } em.persist(templateAlertDefinition); em.persist(groupAlertDefinition); em.persist(resourceAlertDefinition); //only need this for a short time now, so that we can precreate the plugin structure alertSenderService = new TestAlertSenderPluginService(getTempDir()); prepareCustomServerPluginService(alertSenderService); alertSenderService.masterConfig.getPluginDirectory().mkdirs(); unprepareServerPluginService(); JavaArchive archive = ShrinkWrap.create(JavaArchive.class); archive.addClass(TestAlertSender.class); URL res = this.getClass().getClassLoader().getResource("test-alert-sender-serverplugin.xml"); archive.addAsResource(res, "META-INF/rhq-serverplugin.xml"); File pluginFile = new File(alertSenderService.masterConfig.getPluginDirectory(), "test-aler-plugin.jar"); archive.as(ZipExporter.class).exportTo(pluginFile, true); //the alert sender plugin manager needs the plugins in the database... serverPlugin = TestServerPluginService.getPlugin(pluginFile.toURI().toURL()); em.persist(serverPlugin); em.flush(); } }); }
From source file:com.hiperf.common.ui.server.storage.impl.PersistenceHelper.java
private boolean doPersist(ObjectsToPersist toPersist, String userName, Map<com.hiperf.common.ui.shared.util.Id, INakedObject> res, Map<Object, IdHolder> newIdByOldId, EntityManager em, boolean validateBefore, Locale locale, boolean processExceptions) throws ClassNotFoundException, IntrospectionException, PersistenceException, IllegalAccessException, InvocationTargetException, InstantiationException { try {//w w w . jav a 2s. c o m Validator validator = validatorFactory.getValidator(); List<INakedObject> toInsert = toPersist.getInsertedObjects(); if (toInsert != null) { int max = 100 * toInsert.size(); int idx = -1; int k = -1; int s = toInsert.size(); int prevSize = s; while (!toInsert.isEmpty()) { if (s == toInsert.size()) { k++; } else k = 0; if (k == 1) { logger.log(Level.FINE, "Impossible to persist data : one linked object not found in toInsert list"); return false; } if (prevSize == toInsert.size()) { idx++; } else { idx = 0; prevSize = toInsert.size(); } if (idx > max) { logger.log(Level.FINE, "Impossible to persist data : one linked object not found in toInsert list..."); return false; } Iterator<INakedObject> it = toInsert.iterator(); while (it.hasNext()) { INakedObject o = (INakedObject) it.next(); String className = o.getClass().getName(); if (o instanceof IAuditable) { IAuditable aud = (IAuditable) o; aud.setCreateUser(userName); aud.setCreateDate(new Date()); } Set<PropertyDescriptor> ids = idsByClassName.get(className); processLinkedCollectionsBeforePersist(o, collectionsByClassName.get(className)); if (!processLinkedObjectsBeforePersist(newIdByOldId, o, lazysByClassName.get(className), toPersist)) continue; if (!processLinkedObjectsBeforePersist(newIdByOldId, o, eagerObjectsByClassName.get(className), toPersist)) continue; if (generatedIdClasses.contains(className)) { PropertyDescriptor idPd = ids.iterator().next(); Object oldId = idPd.getReadMethod().invoke(o, StorageService.emptyArg); Object[] args = new Object[1]; if (!idPd.getPropertyType().isPrimitive()) args[0] = null; else args[0] = 0L; idPd.getWriteMethod().invoke(o, args); if (validateBefore) { Set<ConstraintViolation<INakedObject>> errors = validator.validate(o); if (errors != null && !errors.isEmpty()) { it.remove(); continue; } try { em.persist(o); } catch (Exception e) { it.remove(); continue; } } else em.persist(o); Object newId = idPd.getReadMethod().invoke(o, StorageService.emptyArg); newIdByOldId.put(oldId, new IdHolder(newId, className)); List<Object> idVals = new ArrayList<Object>(1); idVals.add(oldId); List<String> idFields = new ArrayList<String>(1); idFields.add(idPd.getName()); res.put(new com.hiperf.common.ui.shared.util.Id(idFields, idVals), o); it.remove(); } else { com.hiperf.common.ui.shared.util.Id id = getId(o, ids); int i = 0; boolean toProcess = true; for (Object idVal : id.getFieldValues()) { if ((idVal instanceof Long && ((Long) idVal).longValue() < 0) || (idVal instanceof String && ((String) idVal).startsWith(PersistenceManager.SEQ_PREFIX))) { IdHolder newIds = newIdByOldId.get(idVal); if (newIds != null) { String att = id.getFieldNames().get(i); for (PropertyDescriptor idPd : ids) { if (idPd.getName().equals(att)) { Object[] args = new Object[1]; args[0] = newIds.getId(); idPd.getWriteMethod().invoke(o, args); break; } } } else { toProcess = false; break; } } i++; } if (toProcess) { if (validateBefore) { Set<ConstraintViolation<INakedObject>> errors = validator.validate(o); if (errors != null && !errors.isEmpty()) { it.remove(); continue; } try { refreshManyToOneLinkedWithId(o, id, em); em.persist(o); } catch (Exception e) { it.remove(); continue; } } else { refreshManyToOneLinkedWithId(o, id, em); em.persist(o); } id = getId(o, ids); res.put(id, o); it.remove(); } } } } } Map<String, Set<com.hiperf.common.ui.shared.util.Id>> toDelete = toPersist .getRemovedObjectsIdsByClassName(); if (toDelete != null) { for (String className : toDelete.keySet()) { Set<com.hiperf.common.ui.shared.util.Id> ids = toDelete.get(className); Class<?> clazz = Class.forName(className); Map<Field, Field> toRemove = null; if (ids != null && !ids.isEmpty()) { com.hiperf.common.ui.shared.util.Id id = ids.iterator().next(); if (id.getFieldValues().size() > 1) { toRemove = new HashMap<Field, Field>(); Field[] fields = clazz.getDeclaredFields(); for (Field f : fields) { if (f.isAnnotationPresent(ManyToOne.class)) { Field[] ff = f.getType().getDeclaredFields(); for (Field lf : ff) { OneToMany ann = lf.getAnnotation(OneToMany.class); if (ann != null && ann.targetEntity() != null && ann.targetEntity().equals(clazz)) { toRemove.put(f, lf); } } } } // TODO : manage annotations on the getters... } } for (com.hiperf.common.ui.shared.util.Id id : ids) { INakedObject no = getObject(clazz, id, em); if (no != null) { if (toRemove != null && !toRemove.isEmpty()) { for (Entry<Field, Field> e : toRemove.entrySet()) { Field f = e.getKey(); Field ff = e.getValue(); boolean b1 = false; boolean b2 = false; if (!f.isAccessible()) { f.setAccessible(true); b1 = true; } if (!ff.isAccessible()) { ff.setAccessible(true); b2 = true; } ((Collection) ff.get(f.get(no))).remove(no); if (b1) f.setAccessible(false); if (b2) ff.setAccessible(false); } } else { // TODO : manage annotations on the getters... } em.remove(no); } } } } Map<String, Map<com.hiperf.common.ui.shared.util.Id, Map<String, Serializable>>> toUpdate = toPersist .getUpdatedObjects(); if (toUpdate != null) { for (String className : toUpdate.keySet()) { Map<com.hiperf.common.ui.shared.util.Id, Map<String, Serializable>> map = toUpdate .get(className); Class<?> clazz = Class.forName(className); Iterator<Entry<com.hiperf.common.ui.shared.util.Id, Map<String, Serializable>>> iterator = map .entrySet().iterator(); while (iterator.hasNext()) { Entry<com.hiperf.common.ui.shared.util.Id, Map<String, Serializable>> entry = iterator .next(); com.hiperf.common.ui.shared.util.Id id = entry.getKey(); INakedObject original = getObject(clazz, id, em); Map<String, Serializable> updateMap = entry.getValue(); for (String att : updateMap.keySet()) { Object object = updateMap.get(att); if (object != null && object instanceof NakedObjectHandler) { NakedObjectHandler oo = (NakedObjectHandler) object; com.hiperf.common.ui.shared.util.Id objId = oo.getId(); if (generatedIdClasses.contains(oo.getClassName()) && newIdByOldId.containsKey(objId.getFieldValues().get(0))) { IdHolder newIds = newIdByOldId.get(objId.getFieldValues().get(0)); List<Object> idVals = new ArrayList<Object>(1); idVals.add(newIds.getId()); List<String> idFields = new ArrayList<String>(1); idFields.add(idsByClassName.get(oo.getClassName()).iterator().next().getName()); com.hiperf.common.ui.shared.util.Id newObjId = new com.hiperf.common.ui.shared.util.Id( idFields, idVals); object = getObject(Class.forName(oo.getClassName()), newObjId, em); } else { object = getObject(Class.forName(oo.getClassName()), oo.getId(), em); } } updateAttributeValue(className, original, att, object); } if (original instanceof IAuditable) { IAuditable aud = (IAuditable) original; aud.setModifyUser(userName); aud.setModifyDate(new Date()); } INakedObject o = null; if (validateBefore) { Set<ConstraintViolation<INakedObject>> errors = validator.validate(original); if (errors != null && !errors.isEmpty()) { iterator.remove(); continue; } try { o = em.merge(original); em.flush(); } catch (Exception e) { iterator.remove(); continue; } } else o = em.merge(original); res.put(id, o); } } } processAddedManyToMany(toPersist, res, newIdByOldId, em); processRemovedManyToMany(toPersist, res, newIdByOldId, em); em.flush(); return true; } catch (Exception e) { logger.log(Level.WARNING, "Exception", e); if (processExceptions) { processDbExceptions(locale, e); return false; } else throw new PersistenceException(e); } }