List of usage examples for javax.persistence EntityManager merge
public <T> T merge(T entity);
From source file:edu.vt.middleware.gator.JpaConfigManager.java
/** {@inheritDoc}. */ @Transactional(propagation = Propagation.REQUIRED) public void save(final ProjectConfig project) { final EntityManager em = getEntityManager(); final Set<ClientConfig> removedClients = new HashSet<ClientConfig>(); if (logger.isDebugEnabled()) { logger.debug("Saving " + project); }//from w w w . j a va 2s . c o m ProjectConfig liveProject; project.setModifiedDate(Calendar.getInstance()); if (project.isNew()) { em.persist(project); liveProject = find(ProjectConfig.class, project.getId()); } else { // Determine removed clients final ProjectConfig pDb = find(ProjectConfig.class, project.getId()); for (ClientConfig client : pDb.getClients()) { if (project.getClient(client.getId()) == null) { removedClients.add(client); } } liveProject = em.merge(project); } // Touch all collections to lazy load dependent data so complete project // configuration is available to event handlers liveProject.getAppenders(); liveProject.getCategories(); liveProject.getClients(); liveProject.getPermissions(); // Fire events on a separate thread so we do not disrupt client thread // (e.g. avoid subscriber blocking) for (ConfigChangeListener listener : getConfigChangeListeners()) { eventExecutor.execute(new ProjectChangedEvent(listener, liveProject, removedClients)); } }
From source file:org.traccar.web.server.model.DataServiceImpl.java
@Override public Device changeAlarmSettings(Device device) { EntityManager entityManager = getSessionEntityManager(); synchronized (entityManager) { entityManager.getTransaction().begin(); try {// ww w . j a v a 2 s. c om device.setAlarmEnabled(!device.isAlarmEnabled()); device = entityManager.merge(device); entityManager.getTransaction().commit(); return device; } catch (RuntimeException e) { entityManager.getTransaction().rollback(); throw e; } } }
From source file:org.eclipse.smila.connectivity.deltaindexing.jpa.impl.DeltaIndexingManagerImpl.java
/** * Sets the visited flags of a unchanged dao object. The modified flag is NOT set !!! Sub compounds of compounds are * also set to visited.//ww w . j a va2 s . c om * * @param em * the EntityManager * @param dao * the DeltaIndexingDao * @throws DeltaIndexingException * if any error occurs */ private void visitUnchangedDaos(final EntityManager em, final DeltaIndexingDao dao) throws DeltaIndexingException { // visit dao if it's a compound or if it has no parent dao.visit(); em.merge(dao); if (_log.isTraceEnabled()) { _log.trace("visited Id with hash:" + dao.getIdHash()); } // check if dao is a compound and visit all sub compounds if (dao.isCompound()) { final Query query = em.createNamedQuery(DeltaIndexingDao.NAMED_QUERY_FIND_SUB_COMPOUNDS); final List<DeltaIndexingDao> daos = query .setParameter(DeltaIndexingDao.NAMED_QUERY_PARAM_PARENT_ID_HASH, dao.getIdHash()) .getResultList(); if (daos != null) { for (final DeltaIndexingDao subDao : daos) { visitUnchangedDaos(em, subDao); } // for } // if } }
From source file:org.opencastproject.themes.persistence.ThemesServiceDatabaseImpl.java
@Override public Theme updateTheme(Theme theme) throws ThemesServiceDatabaseException { EntityManager em = null; EntityTransaction tx = null;//from w ww . j a v a2 s. c o m try { em = emf.createEntityManager(); tx = em.getTransaction(); tx.begin(); ThemeDto themeDto = null; if (theme.getId().isSome()) themeDto = getThemeDto(theme.getId().get(), em); if (themeDto == null) { // no theme stored, create new entity themeDto = new ThemeDto(); themeDto.setOrganization(securityService.getOrganization().getId()); updateTheme(theme, themeDto); em.persist(themeDto); } else { updateTheme(theme, themeDto); em.merge(themeDto); } tx.commit(); theme = themeDto.toTheme(userDirectoryService); messageSender.sendObjectMessage(ThemeItem.THEME_QUEUE, MessageSender.DestinationType.Queue, ThemeItem.update(toSerializableTheme(theme))); return theme; } catch (Exception e) { logger.error("Could not update theme {}: {}", theme, ExceptionUtils.getStackTrace(e)); if (tx.isActive()) { tx.rollback(); } throw new ThemesServiceDatabaseException(e); } finally { if (em != null) { em.close(); } } }
From source file:uk.ac.edukapp.service.WidgetProfileService.java
private Message addTagToWidget(Widgetprofile widget, String newTag) { Message msg = new Message(); try {//from w ww .ja va 2 s .com Tag tag = tagService.insertTag(newTag); if (widget.getTags().contains(tag)) { msg.setMessage("Widget already has tag: " + newTag); } else { EntityManager entityManager = getEntityManagerFactory().createEntityManager(); entityManager.getTransaction().begin(); widget.getTags().add(tag); entityManager.merge(widget); entityManager.getTransaction().commit(); entityManager.close(); msg.setMessage("OK"); } } catch (Exception e) { msg.setMessage("Problem creating tag: " + e.getMessage()); } return msg; /*EntityManager entityManager = getEntityManagerFactory() .createEntityManager(); entityManager.getTransaction().begin(); Query q = entityManager .createQuery("SELECT t FROM Tag t WHERE t.tagtext=?1"); q.setParameter(1, newTag); List<Tag> tags = (List<Tag>) q.getResultList(); Tag tag = null; if (tags != null && tags.size() != 0) { tag = (Tag) tags.get(0); } if (tag == null) { tag = new Tag(); tag.setTagtext(newTag); entityManager.persist(tag); } List<Tag> widget_tags = (List<Tag>) widget.getTags(); if (widget_tags == null) { widget_tags = new ArrayList<Tag>(); } // widget_tags contains fails - even after implementing equals() and // hash_code() in Tag, WidgetProfile // so use this primitive way boolean contains = false; for (Tag t : widget_tags) { if (t.getTagtext().equals(tag.getTagtext()) && t.getId() == tag.getId()) { contains = true; } } // if (widget_tags.contains(tag)) { if (contains) { Message msg = new Message(); msg.setMessage("Widget:" + widget.getId() + " already has tag:" + tag.getTagtext()); return msg; } else { widget_tags.add(tag); } entityManager.persist(entityManager.merge(widget)); // entityManager.merge(widget); entityManager.getTransaction().commit(); entityManager.close(); Message msg = new Message(); msg.setMessage("OK"); msg.setId("" + tag.getId()); return msg;*/ }
From source file:org.traccar.web.server.model.DataServiceImpl.java
@Override public ApplicationSettings updateApplicationSettings(ApplicationSettings applicationSettings) { if (applicationSettings == null) { return getApplicationSettings(); } else {/*from w ww . j a v a 2 s . co m*/ EntityManager entityManager = getServletEntityManager(); synchronized (entityManager) { User user = getSessionUser(); if (user.getAdmin()) { entityManager.getTransaction().begin(); try { entityManager.merge(applicationSettings); entityManager.getTransaction().commit(); this.applicationSettings = applicationSettings; return applicationSettings; } catch (RuntimeException e) { entityManager.getTransaction().rollback(); throw e; } } else { throw new SecurityException(); } } } }
From source file:op.users.PnlUser.java
private CollapsiblePane createCP4(final Users user) { final String key = user.getUID() + ".xusers"; if (!cpMap.containsKey(key)) { cpMap.put(key, new CollapsiblePane()); try {/* ww w . j av a 2 s . c o m*/ cpMap.get(key).setCollapsed(true); } catch (PropertyVetoException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } } final CollapsiblePane cp = cpMap.get(key); DefaultCPTitle cptitle = new DefaultCPTitle("<html><font size=+1>" + user.toString() + (UsersTools.isQualified(user) ? ", " + SYSTools.xx("opde.users.qualifiedNurse") : "") + "</font></html>", new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { cp.setCollapsed(!cp.isCollapsed()); } catch (PropertyVetoException pve) { // BAH! } } }); /*** * ____ _ ______ __ * / ___| |__ __ _ _ __ __ _ ___| _ \ \ / / * | | | '_ \ / _` | '_ \ / _` |/ _ \ |_) \ \ /\ / / * | |___| | | | (_| | | | | (_| | __/ __/ \ V V / * \____|_| |_|\__,_|_| |_|\__, |\___|_| \_/\_/ * |___/ */ final JButton btnChangePW = new JButton(SYSConst.icon22password); btnChangePW.setPressedIcon(SYSConst.icon22passwordPressed); btnChangePW.setAlignmentX(Component.RIGHT_ALIGNMENT); btnChangePW.setContentAreaFilled(false); btnChangePW.setBorder(null); btnChangePW.setToolTipText(SYSTools.xx("opde.users.btnChangePW.tooltip")); btnChangePW.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent actionEvent) { EntityManager em = OPDE.createEM(); try { em.getTransaction().begin(); Users myUser = em.merge(usermap.get(user.getUID())); String newpw = SYSTools.generatePassword(myUser.getVorname(), myUser.getName()); em.lock(myUser, LockModeType.OPTIMISTIC); myUser.setMd5pw(SYSTools.hashword(newpw)); em.getTransaction().commit(); lstUsers.remove(user); lstUsers.add(myUser); usermap.put(key, myUser); Collections.sort(lstUsers); SYSTools.printpw(newpw, myUser); OPDE.getDisplayManager().addSubMessage(new DisplayMessage(SYSTools.xx("opde.users.pwchanged"))); } catch (OptimisticLockException ole) { OPDE.warn(ole); if (em.getTransaction().isActive()) { em.getTransaction().rollback(); } OPDE.getDisplayManager().addSubMessage(DisplayManager.getLockMessage()); } catch (Exception e) { if (em.getTransaction().isActive()) { em.getTransaction().rollback(); } OPDE.fatal(e); } finally { em.close(); } } }); btnChangePW.setEnabled(user.isActive()); cptitle.getRight().add(btnChangePW); /*** * _ _ _ _ _ ___ _ _ * | |__ | |_ _ __ / \ ___| |_(_)_ _____|_ _|_ __ __ _ ___| |_(_)_ _____ * | '_ \| __| '_ \ / _ \ / __| __| \ \ / / _ \| || '_ \ / _` |/ __| __| \ \ / / _ \ * | |_) | |_| | | |/ ___ \ (__| |_| |\ V / __/| || | | | (_| | (__| |_| |\ V / __/ * |_.__/ \__|_| |_/_/ \_\___|\__|_| \_/ \___|___|_| |_|\__,_|\___|\__|_| \_/ \___| * */ final JButton btnActiveInactive = new JButton( user.isActive() ? SYSConst.icon22stop : SYSConst.icon22playerPlay); btnActiveInactive .setPressedIcon(user.isActive() ? SYSConst.icon22stopPressed : SYSConst.icon22playerPlayPressed); btnActiveInactive.setAlignmentX(Component.RIGHT_ALIGNMENT); btnActiveInactive.setContentAreaFilled(false); btnActiveInactive.setBorder(null); btnActiveInactive.setToolTipText(SYSTools .xx(internalClassID + (user.isActive() ? ".btnActiveInactive.stop" : ".btnActiveInactive.play"))); btnActiveInactive.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent actionEvent) { EntityManager em = OPDE.createEM(); try { em.getTransaction().begin(); Users myUser = em.merge(usermap.get(user.getUID())); em.lock(myUser, LockModeType.OPTIMISTIC); myUser.setStatus(myUser.isActive() ? UsersTools.STATUS_INACTIVE : UsersTools.STATUS_ACTIVE); em.getTransaction().commit(); lstUsers.remove(user); lstUsers.add(myUser); usermap.put(myUser.getUID(), myUser); Collections.sort(lstUsers); CollapsiblePane cp = createCP4(myUser); boolean wasCollapsed = cpMap.get(key).isCollapsed(); cpMap.put(key, cp); cp.setCollapsed(myUser.isActive() ? wasCollapsed : true); buildPanel(); } catch (OptimisticLockException ole) { OPDE.warn(ole); if (em.getTransaction().isActive()) { em.getTransaction().rollback(); } if (ole.getMessage().indexOf("Class> entity.info.Resident") > -1) { OPDE.getMainframe().emptyFrame(); OPDE.getMainframe().afterLogin(); } OPDE.getDisplayManager().addSubMessage(DisplayManager.getLockMessage()); } catch (Exception e) { if (em.getTransaction().isActive()) { em.getTransaction().rollback(); } OPDE.fatal(e); } finally { em.close(); } } }); cptitle.getRight().add(btnActiveInactive); /*** * _ _ _ * ___ __| (_) |_ * / _ \/ _` | | __| * | __/ (_| | | |_ * \___|\__,_|_|\__| * */ final JButton btnEdit = new JButton(SYSConst.icon22edit3); btnEdit.setPressedIcon(SYSConst.icon22edit3Pressed); btnEdit.setAlignmentX(Component.RIGHT_ALIGNMENT); btnEdit.setContentAreaFilled(false); btnEdit.setBorder(null); btnEdit.setToolTipText(SYSTools.xx("opde.users.btnEdit")); btnEdit.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent actionEvent) { new DlgUser(user, new Closure() { @Override public void execute(Object o) { if (o != null) { EntityManager em = OPDE.createEM(); try { em.getTransaction().begin(); Users myUser = em.merge((Users) o); em.lock(myUser, LockModeType.OPTIMISTIC); em.getTransaction().commit(); lstUsers.remove(user); lstUsers.add(myUser); usermap.put(myUser.getUID(), myUser); Collections.sort(lstUsers); CollapsiblePane cp = createCP4(myUser); boolean wasCollapsed = cpMap.get(key).isCollapsed(); cpMap.put(key, cp); cp.setCollapsed(myUser.isActive() ? wasCollapsed : true); buildPanel(); } catch (OptimisticLockException ole) { OPDE.warn(ole); if (em.getTransaction().isActive()) { em.getTransaction().rollback(); } if (ole.getMessage().indexOf("Class> entity.info.Resident") > -1) { OPDE.getMainframe().emptyFrame(); OPDE.getMainframe().afterLogin(); } OPDE.getDisplayManager().addSubMessage(DisplayManager.getLockMessage()); } catch (Exception e) { if (em.getTransaction().isActive()) { em.getTransaction().rollback(); } OPDE.fatal(e); } finally { em.close(); } } } }); } }); cptitle.getRight().add(btnEdit); cp.setTitleLabelComponent(cptitle.getMain()); cp.setSlidingDirection(SwingConstants.SOUTH); /*** * ___ ___ _ _ _____ ___ _ _ _____ * / __/ _ \| \| |_ _| __| \| |_ _| * | (_| (_) | .` | | | | _|| .` | | | * \___\___/|_|\_| |_| |___|_|\_| |_| * */ cp.addCollapsiblePaneListener(new CollapsiblePaneAdapter() { @Override public void paneExpanded(CollapsiblePaneEvent collapsiblePaneEvent) { if (!contentMap.containsKey(key)) { contentMap.put(key, new PnlEditMemberships(user, lstGroups)); } cp.setContentPane(contentMap.get(key)); cp.setOpaque(false); } } ); cp.setBackground(UsersTools.getBG1(user)); cp.setCollapsible(user.isActive()); cp.setHorizontalAlignment(SwingConstants.LEADING); cp.setOpaque(false); return cp; }
From source file:org.opencastproject.kernel.security.persistence.OrganizationDatabaseImpl.java
/** * @see org.opencastproject.kernel.security.persistence.OrganizationDatabase#storeOrganization(org.opencastproject.security.api.Organization) *//* ww w . j a va 2 s . co m*/ @Override public void storeOrganization(Organization org) throws OrganizationDatabaseException { EntityManager em = null; EntityTransaction tx = null; try { em = emf.createEntityManager(); tx = em.getTransaction(); tx.begin(); JpaOrganization organizationEntity = getOrganizationEntity(org.getId()); if (organizationEntity == null) { JpaOrganization organization = new JpaOrganization(org.getId(), org.getName(), org.getServers(), org.getAdminRole(), org.getAnonymousRole(), org.getProperties()); em.persist(organization); } else { organizationEntity.setName(org.getName()); organizationEntity.setAdminRole(org.getAdminRole()); organizationEntity.setAnonymousRole(org.getAnonymousRole()); organizationEntity.setServers(org.getServers()); organizationEntity.setProperties(org.getProperties()); em.merge(organizationEntity); } tx.commit(); } catch (Exception e) { logger.error("Could not update organization: {}", e.getMessage()); if (tx.isActive()) { tx.rollback(); } throw new OrganizationDatabaseException(e); } finally { if (em != null) em.close(); } }
From source file:org.opencastproject.userdirectory.JpaGroupRoleProvider.java
/** * Adds or updates a group to the persistence. * * @param group// www . j ava 2s .co m * the group to add */ public void addGroup(final JpaGroup group) { Set<JpaRole> roles = UserDirectoryPersistenceUtil.saveRoles(group.getRoles(), emf); JpaOrganization organization = UserDirectoryPersistenceUtil.saveOrganization(group.getOrganization(), emf); JpaGroup jpaGroup = new JpaGroup(group.getGroupId(), organization, group.getName(), group.getDescription(), roles, group.getMembers()); // Then save the jpaGroup EntityManager em = null; EntityTransaction tx = null; try { em = emf.createEntityManager(); tx = em.getTransaction(); tx.begin(); JpaGroup foundGroup = UserDirectoryPersistenceUtil.findGroup(jpaGroup.getGroupId(), jpaGroup.getOrganization().getId(), emf); if (foundGroup == null) { em.persist(jpaGroup); } else { foundGroup.setName(jpaGroup.getName()); foundGroup.setDescription(jpaGroup.getDescription()); foundGroup.setMembers(jpaGroup.getMembers()); foundGroup.setRoles(roles); em.merge(foundGroup); } tx.commit(); messageSender.sendObjectMessage(GroupItem.GROUP_QUEUE, MessageSender.DestinationType.Queue, GroupItem.update(JaxbGroup.fromGroup(jpaGroup))); } finally { if (tx.isActive()) { tx.rollback(); } if (em != null) em.close(); } }
From source file:org.eclipse.smila.connectivity.deltaindexing.jpa.impl.DeltaIndexingManagerImpl.java
/** * {@inheritDoc}/*w w w . j av a2 s . c o m*/ * * @see org.eclipse.smila.connectivity.deltaindexing.DeltaIndexingManager#finish(String) */ @Override public void finish(final String sessionId) throws DeltaIndexingSessionException, DeltaIndexingException { _lock.readLock().lock(); try { final DataSourceDao dao = assertSession(sessionId); final EntityManager em = createEntityManager(); final EntityTransaction transaction = em.getTransaction(); try { transaction.begin(); final DataSourceDao unlockedDao = new DataSourceDao(dao.getDataSourceId(), null); em.merge(unlockedDao); transaction.commit(); if (_log.isTraceEnabled()) { _log.trace("finished session " + sessionId + " with data source: " + dao.getDataSourceId()); } } catch (final Exception e) { if (transaction.isActive()) { transaction.rollback(); } throw new DeltaIndexingException( "error finishing delta indexing for data source: " + dao.getDataSourceId(), e); } finally { closeEntityManager(em); } } finally { _lock.readLock().unlock(); } }