List of usage examples for javax.persistence EntityManager merge
public <T> T merge(T entity);
From source file:org.traccar.web.server.model.DataServiceImpl.java
@Override public User removeUser(User user) { User currentUser = getSessionUser(); if (currentUser.getAdmin()) { EntityManager entityManager = getSessionEntityManager(); synchronized (entityManager) { entityManager.getTransaction().begin(); try { user = entityManager.merge(user); user.getDevices().clear(); entityManager.remove(user); entityManager.getTransaction().commit(); return user; } catch (RuntimeException e) { entityManager.getTransaction().rollback(); throw e; }//from w w w. ja v a 2s . co m } } else { throw new SecurityException(); } }
From source file:org.artificer.repository.hibernate.HibernatePersistenceManager.java
@Override public void updateStoredQuery(final String queryName, final StoredQuery srampStoredQuery) throws ArtificerException { new HibernateUtil.HibernateTask<Void>() { @Override/*from w ww . j av a 2s .co m*/ protected Void doExecute(EntityManager entityManager) throws Exception { // The name may have changed, so we need to look it up and modify, rather than just persist // what we're handed. ArtificerStoredQuery artificerStoredQuery = HibernateUtil.getStoredQuery(queryName, entityManager); HibernateUtil.evict(ArtificerStoredQuery.class, artificerStoredQuery.getQueryName(), entityManager); HibernateEntityFactory.processStoredQuery(artificerStoredQuery, srampStoredQuery); entityManager.merge(artificerStoredQuery); return null; } }.execute(); }
From source file:com.github.jinahya.persistence.ShadowTest.java
@Test(enabled = false, invocationCount = 1) public void testNassword() { final EntityManager manager = LocalPU.createEntityManager(); try {/*from ww w. j ava 2 s. c om*/ final EntityTransaction transaction = manager.getTransaction(); transaction.begin(); try { final String username = newUsername(manager); byte[] password = newPassword(); Shadow shadow = persistInstance(manager, username, password); LOGGER.log(Level.INFO, "morton.list: {0}", MORTONS(manager, 0, 1024)); for (int i = 0; i < 3; i++) { System.out.println("-------------------------------------"); Assert.assertTrue(shadow.puthenticate(shadow, password)); final byte[] nassword = newPassword(); shadow.nassword(shadow, password, nassword); shadow = manager.merge(shadow); manager.flush(); LOGGER.log(Level.INFO, "morton.list: {0}", MORTONS(manager, 0, 1024)); Assert.assertFalse(shadow.puthenticate(shadow, password)); Assert.assertTrue(shadow.puthenticate(shadow, nassword)); password = nassword; } transaction.commit(); } catch (Exception e) { LocalPU.printConstraintViolation(e); transaction.rollback(); e.printStackTrace(System.err); Assert.fail(e.getMessage()); } } finally { manager.close(); } }
From source file:op.users.PnlUser.java
private java.util.List<Component> addCommands() { java.util.List<Component> list = new ArrayList<Component>(); /***/* w w w .ja v a 2 s .co m*/ * _ _ _ _ _ * / \ __| | __| | | | |___ ___ _ __ * / _ \ / _` |/ _` | | | / __|/ _ \ '__| * / ___ \ (_| | (_| | |_| \__ \ __/ | * /_/ \_\__,_|\__,_|\___/|___/\___|_| * */ final JideButton btnAddUser = GUITools.createHyperlinkButton(SYSTools.xx("opde.users.btnAddUser"), SYSConst.icon22addUser, null); btnAddUser.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent actionEvent) { if (tabMain.getSelectedIndex() != TAB_USER) { tabMain.setSelectedIndex(TAB_USER); } new DlgUser(new Users(), new Closure() { @Override public void execute(Object o) { if (o != null) { EntityManager em = OPDE.createEM(); try { em.getTransaction().begin(); Users user = em.merge((Users) o); // Put everyone into >>everyone<< Groups everyone = em.find(Groups.class, "everyone"); em.lock(everyone, LockModeType.OPTIMISTIC); user.getGroups().add(everyone); everyone.getMembers().add(user); em.getTransaction().commit(); lstUsers.add(user); reloadDisplay(); } catch (Exception e) { em.getTransaction().rollback(); } finally { em.close(); } } } }); } }); list.add(btnAddUser); /*** * _ _ _ ____ * / \ __| | __| |/ ___|_ __ ___ _ _ _ __ * / _ \ / _` |/ _` | | _| '__/ _ \| | | | '_ \ * / ___ \ (_| | (_| | |_| | | | (_) | |_| | |_) | * /_/ \_\__,_|\__,_|\____|_| \___/ \__,_| .__/ * |_| */ final JideButton btnAddGroup = GUITools.createHyperlinkButton(SYSTools.xx("opde.users.btnAddGroup"), SYSConst.icon22addGroup, null); btnAddGroup.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent actionEvent) { if (tabMain.getSelectedIndex() != TAB_GROUPS) { tabMain.setSelectedIndex(TAB_GROUPS); } new DlgGroup(new Groups(), new Closure() { @Override public void execute(Object o) { if (o != null) { EntityManager em = OPDE.createEM(); try { em.getTransaction().begin(); Groups myGroup = em.merge((Groups) o); em.getTransaction().commit(); createCP4(myGroup); lstGroups.add(myGroup); Collections.sort(lstGroups); buildPanel(); } catch (Exception e) { // em.getTransaction().rollback(); OPDE.fatal(e); } finally { em.close(); } } } }); } }); list.add(btnAddGroup); /*** * _ _ ____ _ _ * | |__ | |_ _ __ | _ \ _ __(_)_ __ | |_ * | '_ \| __| '_ \| |_) | '__| | '_ \| __| * | |_) | |_| | | | __/| | | | | | | |_ * |_.__/ \__|_| |_|_| |_| |_|_| |_|\__| * */ // JideButton btnPrint = GUITools.createHyperlinkButton(SYSTools.xx("misc.commands.print"), SYSConst.icon22print2, new ActionListener() { // @Override // public void actionPerformed(ActionEvent actionEvent) { // // } // }); // list.add(btnPrint); return list; }
From source file:org.opencastproject.userdirectory.jpa.JpaUserAndRoleProvider.java
@PUT @Path("{username}.json") @RestQuery(name = "roleupdate", description = "Updates a user's roles", returnDescription = "No content", restParameters = @RestParameter(name = "roles", type = TEXT, isRequired = true, description = "The user roles as a json array"), pathParameters = @RestParameter(name = "username", type = STRING, isRequired = true, description = "The username"), reponses = { @RestResponse(responseCode = SC_NO_CONTENT, description = "The user roles have been updated.") }) public Response updateUserFromJson(@PathParam("username") String username, @FormParam("roles") String roles) { JSONArray rolesArray = (JSONArray) JSONValue.parse(roles); EntityManager em = null; EntityTransaction tx = null;/*from w w w .j av a2s. co m*/ try { em = emf.createEntityManager(); tx = em.getTransaction(); tx.begin(); // Find the existing user Query q = em.createNamedQuery("user"); q.setParameter("u", username); q.setParameter("o", securityService.getOrganization().getId()); JpaUser jpaUser = null; try { jpaUser = (JpaUser) q.getSingleResult(); jpaUser.roles.clear(); for (Object role : rolesArray) { jpaUser.roles.add((String) role); } em.merge(jpaUser); } catch (NoResultException e) { return null; // this will be translated into a 404 } tx.commit(); return Response.noContent().build(); } finally { if (tx.isActive()) { tx.rollback(); } if (em != null) em.close(); } }
From source file:elaborate.editor.publish.PublishTask.java
private ExportedEntryData exportEntryData(ProjectEntry projectEntry, int entryNum, List<String> projectEntryMetadataFields, Map<String, String> typographicalAnnotationMap) { // String entryFilename = entryFilename(entryNum); String entryFilename = projectEntry.getId() + ".json"; File json = new File(jsonDir, entryFilename); EntityManager entityManager = HibernateUtil.getEntityManager(); entityManager.merge(projectEntry); Map<String, Object> entryData = getProjectEntryData(projectEntry, projectEntryMetadataFields, typographicalAnnotationMap); Multimap<String, AnnotationIndexData> annotationDataMap = (Multimap<String, AnnotationIndexData>) entryData .remove("annotationDataMap"); entityManager.close();/*ww w . j a v a2s .c o m*/ exportJson(json, entryData); List<String> thumbnailUrls = Lists.newArrayList(); for (Map<String, String> map : (List<Map<String, String>>) entryData.get("facsimiles")) { thumbnailUrls.add(map.get("thumbnail")); } ExportedEntryData exportedEntryData = new ExportedEntryData(); exportedEntryData.thumbnailUrls = thumbnailUrls; exportedEntryData.annotationDataMap = annotationDataMap; return exportedEntryData; }
From source file:uk.ac.edukapp.service.WidgetProfileService.java
public Widgetprofile addEditInformation(Widgetprofile widgetProfile, String builderType, String data, String width, String height) { String escapedHTML = StringEscapeUtils.escapeHtml(data); String metaDataJSON = "{\"width\":" + width + ",\"height\":" + height + ",\"html\":\"" + escapedHTML + "\"}"; EntityManager em = getEntityManagerFactory().createEntityManager(); em.getTransaction().begin();//from w w w . j ava 2s .c o m widgetProfile.setMeta_data(metaDataJSON); widgetProfile.setBuilder(builderType); em.merge(widgetProfile); em.getTransaction().commit(); em.close(); return widgetProfile; }
From source file:org.traccar.web.server.model.DataServiceImpl.java
@Override public Device removeDevice(Device device) { EntityManager entityManager = getSessionEntityManager(); synchronized (entityManager) { User user = getSessionUser();//ww w . ja v a2 s . c o m entityManager.getTransaction().begin(); try { device = entityManager.merge(device); user.getDevices().remove(device); device.setLatestPosition(null); entityManager.flush(); Query query = entityManager.createQuery("DELETE FROM Position x WHERE x.device = :device"); query.setParameter("device", device); query.executeUpdate(); entityManager.remove(device); entityManager.getTransaction().commit(); return device; } catch (RuntimeException e) { entityManager.getTransaction().rollback(); throw e; } } }
From source file:op.users.PnlUser.java
private CollapsiblePane createCP4(final Groups group) { final String key = group.getGID() + ".xgroups"; if (!cpMap.containsKey(key)) { cpMap.put(key, new CollapsiblePane()); cpMap.get(key).setSlidingDirection(SwingConstants.SOUTH); cpMap.get(key).setBackground(bg); cpMap.get(key).setForeground(fg); cpMap.get(key).addCollapsiblePaneListener(new CollapsiblePaneAdapter() { @Override// w ww .j ava 2 s . c o m public void paneExpanded(CollapsiblePaneEvent collapsiblePaneEvent) { if (!contentMap.containsKey(key)) { contentMap.put(key, createContentPanel4(group)); } cpMap.get(key).setContentPane(contentMap.get(key)); } }); cpMap.get(key).setHorizontalAlignment(SwingConstants.LEADING); cpMap.get(key).setOpaque(false); try { 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>" + group.getGID().toUpperCase() + (group.isQualified() ? ", " + SYSTools.xx("opde.users.qualifiedGroup") : "") + "</font></html>", new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { cp.setCollapsed(!cp.isCollapsed()); } catch (PropertyVetoException pve) { // BAH! } } }); /*** * _ _ _ * __| | ___| | ___| |_ ___ __ _ _ __ ___ _ _ _ __ * / _` |/ _ \ |/ _ \ __/ _ \ / _` | '__/ _ \| | | | '_ \ * | (_| | __/ | __/ || __/ | (_| | | | (_) | |_| | |_) | * \__,_|\___|_|\___|\__\___| \__, |_| \___/ \__,_| .__/ * |___/ |_| */ final JButton btnDeleteGroup = new JButton(SYSConst.icon22delete); btnDeleteGroup.setPressedIcon(SYSConst.icon22deletePressed); btnDeleteGroup.setAlignmentX(Component.RIGHT_ALIGNMENT); btnDeleteGroup.setContentAreaFilled(false); btnDeleteGroup.setBorder(null); btnDeleteGroup.setToolTipText(SYSTools.xx("opde.users.btnDeleteGroup")); btnDeleteGroup.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent actionEvent) { new DlgYesNo(SYSTools.xx("misc.questions.delete1") + "<br/><i>" + group.getGID() + "</i><br/>" + SYSTools.xx("misc.questions.delete2"), SYSConst.icon48delete, new Closure() { @Override public void execute(Object o) { if (o.equals(JOptionPane.YES_OPTION)) { EntityManager em = OPDE.createEM(); try { em.getTransaction().begin(); Groups myGroup = em.merge(group); em.remove(myGroup); em.getTransaction().commit(); lstGroups.remove(group); cpMap.remove(key); 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(); } } } }); } }); btnDeleteGroup.setEnabled(!group.isSystem()); cpTitle.getRight().add(btnDeleteGroup); cp.setTitleLabelComponent(cpTitle.getMain()); if (!cp.isCollapsed()) { if (!contentMap.containsKey(key)) { contentMap.put(key, createContentPanel4(group)); } cp.setContentPane(contentMap.get(key)); } return cp; }
From source file:org.sigmah.server.endpoint.gwtrpc.RetrievePasswordServlet.java
@Override @Transactional/*from w w w. ja v a 2 s . com*/ public void retrievePassword(String email, String language) throws EmailException { final EntityManager entityManager = injector.getInstance(EntityManager.class); final Query query = entityManager.createQuery("SELECT u FROM User u WHERE u.email = :email"); query.setParameter("email", email); final User thisUser = (User) query.getSingleResult(); // If the user doesn't exists, the following lines won't be executed final String password = generatePassword(); final String hashedPassword = BCrypt.hashpw(password, BCrypt.gensalt()); final SimpleEmail mail = new SimpleEmail(); final Locale locale = getLocale(language); final ResourceBundle bundle = ResourceBundle.getBundle("org.sigmah.server.mail.MailMessages", locale); mail.setSubject(bundle.getString("retrievePassword.subject")); mail.setMsg(MessageFormat.format(bundle.getString("retrievePassword.content"), password)); mail.addTo(email, User.getUserCompleteName(thisUser)); thisUser.setHashedPassword(hashedPassword); entityManager.merge(thisUser); final MailSender mailSender = injector.getInstance(MailSender.class); mailSender.send(mail); }