List of usage examples for javax.persistence EntityManager getTransaction
public EntityTransaction getTransaction();
EntityTransaction
object. From source file:com.enioka.jqm.tools.JqmEngine.java
private void purgeDeadJobInstances(EntityManager em, Node node) { em.getTransaction().begin(); for (JobInstance ji : em .createQuery("SELECT ji FROM JobInstance ji WHERE ji.node = :node", JobInstance.class) .setParameter("node", node).getResultList()) { History h = em.find(History.class, ji.getId()); if (h == null) { h = Helpers.createHistory(ji, em, State.CRASHED, Calendar.getInstance()); Message m = new Message(); m.setJi(ji.getId());/* w w w .j a v a 2s .c o m*/ m.setTextMessage( "Job was supposed to be running at server startup - usually means it was killed along a server by an admin or a crash"); em.persist(m); } em.createQuery("DELETE FROM JobInstance WHERE id = :i").setParameter("i", ji.getId()).executeUpdate(); } em.getTransaction().commit(); }
From source file:ec.edu.chyc.manejopersonal.controller.PersonaJpaController.java
public void destroy(Long id) throws Exception { EntityManager em = null; try {//from w w w . j ava 2s . co m em = getEntityManager(); em.getTransaction().begin(); em.remove(id); em.getTransaction().commit(); } finally { if (em != null) { em.close(); } } }
From source file:com.doculibre.constellio.wicket.panels.admin.thesaurus.AddEditThesaurusPanel.java
public AddEditThesaurusPanel(String id) { super(id, false); this.thesaurusModel = new EntityModel<Thesaurus>(new LoadableDetachableModel() { @Override/*from w w w . j a va 2s .co m*/ protected Object load() { AdminCollectionPanel collectionAdminPanel = (AdminCollectionPanel) findParent( AdminCollectionPanel.class); RecordCollection collection = collectionAdminPanel.getCollection(); Thesaurus thesaurus = collection.getThesaurus(); return thesaurus != null ? thesaurus : newThesaurus; } }); Form form = getForm(); form.setModel(new CompoundPropertyModel(thesaurusModel)); final List<String> errorMessages = new ArrayList<String>(); errorsModalWindow = new ModalWindow("errorsModal"); errorsModalWindow.setCssClassName(ModalWindow.CSS_CLASS_GRAY); skosFileField = new FileUploadField("skosFile"); uploadButton = new Button("uploadButton") { @Override public void onSubmit() { errorMessages.clear(); FileUpload upload = skosFileField.getFileUpload(); if (upload != null) { try { skosFile = upload.writeToTempFile(); } catch (IOException e) { throw new WicketRuntimeException(e); } } AddEditThesaurusPanel.this.add(new AbstractAjaxTimerBehavior(Duration.seconds(1)) { @Override protected void onTimer(AjaxRequestTarget target) { stop(); if (!importing && skosFile != null && skosFile.exists()) { importing = true; importCompleted = false; progressInfo = new ProgressInfo(); progressPanel.start(target); getForm().modelChanging(); new Thread() { @Override public void run() { try { SkosServices skosServices = ConstellioSpringUtils.getSkosServices(); FileInputStream is = new FileInputStream(skosFile); AdminCollectionPanel collectionAdminPanel = (AdminCollectionPanel) findParent( AdminCollectionPanel.class); RecordCollection collection = collectionAdminPanel.getCollection(); Thesaurus importedThesaurus = skosServices.importThesaurus(is, progressInfo, errorMessages); List<ImportThesaurusPlugin> importThesaurusPlugins = PluginFactory .getPlugins(ImportThesaurusPlugin.class); if (!importThesaurusPlugins.isEmpty()) { for (ImportThesaurusPlugin importThesaurusPlugin : importThesaurusPlugins) { is = new FileInputStream(skosFile); importThesaurusPlugin.afterUpload(is, importedThesaurus, collection); } } FileUtils.deleteQuietly(skosFile); thesaurusModel.setObject(importedThesaurus); importing = false; importCompleted = true; } catch (FileNotFoundException e) { throw new WicketRuntimeException(e); } } }.start(); } } }); } }; uploadButton.setDefaultFormProcessing(false); progressInfo = new ProgressInfo(); progressInfoModel = new LoadableDetachableModel() { @Override protected Object load() { return progressInfo; } }; progressPanel = new ProgressPanel("progressPanel", progressInfoModel) { @Override protected void onFinished(AjaxRequestTarget target) { // while (!importCompleted) { // // Wait for the import to be completed // try { // Thread.sleep(500); // } catch (InterruptedException e) { // throw new WicketRuntimeException(e); // } // } target.addComponent(rdfAbout); target.addComponent(dcTitle); target.addComponent(dcDescription); target.addComponent(dcDate); target.addComponent(dcCreator); if (!errorMessages.isEmpty()) { IModel errorMsgModel = new LoadableDetachableModel() { @Override protected Object load() { StringBuffer sb = new StringBuffer(); for (String errorMsg : errorMessages) { sb.append(errorMsg); sb.append("\n"); } return sb.toString(); } }; MultiLineLabel multiLineLabel = new MultiLineLabel(errorsModalWindow.getContentId(), errorMsgModel); multiLineLabel.add(new SimpleAttributeModifier("style", "text-align:left;")); errorsModalWindow.setContent(multiLineLabel); errorsModalWindow.show(target); } } }; progressPanel.setVisible(false); deleteButton = new Button("deleteButton") { @Override public void onSubmit() { Thesaurus thesaurus = thesaurusModel.getObject(); if (thesaurus.getId() != null) { SkosServices skosServices = ConstellioSpringUtils.getSkosServices(); EntityManager entityManager = ConstellioPersistenceContext.getCurrentEntityManager(); if (!entityManager.getTransaction().isActive()) { entityManager.getTransaction().begin(); } skosServices.makeTransient(thesaurus); entityManager.getTransaction().commit(); AdminCollectionPanel collectionAdminPanel = (AdminCollectionPanel) findParent( AdminCollectionPanel.class); RecordCollection collection = collectionAdminPanel.getCollection(); collection.setThesaurus(null); AddEditThesaurusPanel.this.replaceWith(newReturnComponent(AddEditThesaurusPanel.this.getId())); } } @Override public boolean isVisible() { return super.isVisible() && thesaurusModel.getObject().getId() != null; } @Override protected String getOnClickScript() { String confirmMsg = getLocalizer().getString("confirmDelete", AddEditThesaurusPanel.this) .replace("'", "\\'"); return "if (confirm('" + confirmMsg + "')) { return true;} else { return false; }"; } }; deleteButton.setDefaultFormProcessing(false); rdfAbout = new Label("rdfAbout"); rdfAbout.setOutputMarkupId(true); dcTitle = new Label("dcTitle"); dcTitle.setOutputMarkupId(true); dcDescription = new Label("dcDescription"); dcDescription.setOutputMarkupId(true); dcDate = new Label("dcDate"); dcDate.setOutputMarkupId(true); dcCreator = new Label("dcCreator"); dcCreator.setOutputMarkupId(true); form.add(skosFileField); form.add(uploadButton); form.add(progressPanel); form.add(errorsModalWindow); form.add(deleteButton); form.add(rdfAbout); form.add(dcTitle); form.add(dcDescription); form.add(dcDate); form.add(dcCreator); }
From source file:BO.UserHandler.java
public boolean updateDeviceToken(VUser u) { EntityManager em; EntityManagerFactory emf;/*from w w w.jav a2 s . co m*/ emf = Persistence.createEntityManagerFactory(PERSISTENCE_NAME); em = emf.createEntityManager(); System.out.println("Updating token: " + u.getDeviceToken()); try { em.getTransaction().begin(); User user; user = (User) em.createQuery("SELECT u FROM User u WHERE u.email LIKE :email") .setParameter("email", u.getEmail()).setMaxResults(1).getSingleResult(); user.setDeviceToken(u.getDeviceToken()); em.persist(user); em.flush(); em.getTransaction().commit(); return true; } catch (NoResultException e) { return false; } finally { if (em != null) { em.close(); } emf.close(); } }
From source file:com.jada.admin.AdminLookupDispatchAction.java
protected ActionForward process(ActionMapping actionMapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response, String name) { ActionForward forward = null;//from ww w. j ava 2s. c o m AdminBean adminBean = getAdminBean(request); if (adminBean == null) { Cookie cookies[] = request.getCookies(); if (cookies == null) { return actionMapping.findForward("sessionexpire"); } for (int i = 0; i < cookies.length; i++) { if (cookies[i].getName().equals(Constants.SESSION_COOKIE_USER)) { return actionMapping.findForward("sessionexpire"); } } return actionMapping.findForward("login"); } EntityManager em = null; try { em = JpaConnection.getInstance().getCurrentEntityManager(); em.getTransaction().begin(); if (actionMapping instanceof AdminActionMapping) { AdminActionMapping adminMapping = (AdminActionMapping) actionMapping; String userTypes = adminMapping.getUserTypes(); String tokens[] = userTypes.split(","); User user = adminBean.getUser(); String userType = user.getUserType(); boolean found = false; for (int i = 0; i < tokens.length; i++) { if (userType.equals(tokens[i])) { found = true; break; } } if (!found) { throw new com.jada.admin.SecurityException( "user " + user.getUserId() + " is blocked from accessing " + actionMapping.getPath()); } } logger.debug("RequestURL > " + request.getRequestURL()); logger.debug("QueryString > " + request.getQueryString()); if (Utility.getLogLevel(logger).equals(Level.DEBUG)) { logger.debug("Request Information ..."); Enumeration<?> enumeration = request.getParameterNames(); while (enumeration.hasMoreElements()) { String key = (String) enumeration.nextElement(); String line = ""; line += "key=" + key + " value="; String values[] = request.getParameterValues(key); for (int i = 0; i < values.length; i++) { if (i > 0) { line += ","; } line += "[" + values[i] + "]"; } logger.debug(line); } } AdminMaintActionForm form = (AdminMaintActionForm) actionForm; forward = customProcess(actionMapping, form, request, response, name); em = JpaConnection.getInstance().getCurrentEntityManager(); if (em.isOpen()) { if (em.getTransaction().isActive()) { em.getTransaction().commit(); } } if (form != null) { if (form.isStream) { streamWebService(response, form.getStreamData()); } else { encodeForm(form); } } } catch (Throwable e) { logger.error("Exception encountered in " + actionMapping.getName()); logger.error("Exception", e); if (e instanceof com.jada.admin.SecurityException) { forward = actionMapping.findForward("securityException"); } else { forward = actionMapping.findForward("exception"); } } finally { try { em = JpaConnection.getInstance().getCurrentEntityManager(); if (em.isOpen()) { if (em.getTransaction().isActive()) { em.getTransaction().rollback(); } } em.close(); } catch (Throwable e1) { logger.error("Could not rollback transaction after exception!", e1); } } return forward; }
From source file:de.zib.gndms.GORFX.context.service.globus.resource.TaskResource.java
@Override public void remove() { if (taskAction != null) { Log log = taskAction.getLog();/*from w w w . ja va2s. c o m*/ log.debug("Removing task resource: " + getID()); AbstractTask tsk = taskAction.getModel(); boolean cleanUp = false; if (tsk != null) { if (!tsk.isDone()) { // task is still running cancel it and cleanup entity manager taskAction.setCancelled(true); log.debug("cancel task " + tsk.getWid()); cleanUp = true; if (future != null) { future.cancel(true); try { // give cancel some time Thread.sleep(2000L); } catch (InterruptedException e) { logger.debug(e); } } try { EntityManager em = taskAction.getEntityManager(); if (em != null && em.isOpen()) { try { EntityTransaction tx = em.getTransaction(); if (tx.isActive()) tx.rollback(); } finally { em.close(); } } } catch (Exception e) { // don't bother with exceptions log.debug("Exception on task future cancel: " + e.toString(), e); } } EntityManager em = home.getEntityManagerFactory().createEntityManager(); TxFrame tx = new TxFrame(em); // cleanup if necessary try { try { Task t = em.find(Task.class, tsk.getId()); t.setPostMortem(true); tx.commit(); if (cleanUp) { log.debug("Triggering task cleanup"); try { taskAction.setOwnEntityManager(em); taskAction.cleanUpOnFail(t); } catch (Exception e) { log.debug("Exception on cleanup: " + e.toString()); } } // remove task from db log.debug("Removing task: " + t.getId()); tx.begin(); em.remove(t); tx.commit(); } finally { tx.finish(); if (em.isOpen()) em.close(); } } catch (Exception e) { log.debug("Exception on task resource removal: " + e.toString()); e.printStackTrace(); } } } }
From source file:nl.b3p.viewer.admin.stripes.ConfigureSolrActionBean.java
public Resolution delete() { removeFromIndex();//from w ww. ja va 2 s . co m EntityManager em = Stripersist.getEntityManager(); solrConfiguration.getIndexAttributes().clear(); solrConfiguration.getResultAttributes().clear(); em.remove(solrConfiguration); em.getTransaction().commit(); return new ForwardResolution(EDIT_JSP); }
From source file:ar.com.zauber.commons.repository.closures.OpenEntityManagerClosure.java
/** @see Closure#execute(Object) */ public final void execute(final T t) { if (dryrun) { //permite evitar que se hagan commit() en el ambiente de test target.execute(t);//from ww w .j a v a 2 s.c om } else { boolean participate = false; EntityTransaction transaction = null; if (TransactionSynchronizationManager.hasResource(emf)) { // Do not modify the EntityManager: just set the participate flag. participate = true; } else { try { final EntityManager em = emf.createEntityManager(); if (openTx) { if (!warningPrinted) { logger.warn( "The OpenEntityManagerClosure has Transactions enabled and is not recommended" + ". This behaviour will change in the future. Check setOpenTx(), "); } transaction = em.getTransaction(); transaction.begin(); } TransactionSynchronizationManager.bindResource(emf, new EntityManagerHolder(em)); } catch (PersistenceException ex) { throw new DataAccessResourceFailureException("Could not create JPA EntityManager", ex); } } if (transaction != null) { try { target.execute(t); if (transaction.getRollbackOnly()) { transaction.rollback(); } else { transaction.commit(); } } catch (final Throwable e) { if (transaction != null && transaction.isActive()) { transaction.rollback(); } throw new UnhandledException(e); } finally { if (!participate) { final EntityManagerHolder emHolder = (EntityManagerHolder) TransactionSynchronizationManager .unbindResource(emf); EntityManagerFactoryUtils.closeEntityManager(emHolder.getEntityManager()); } } } else { try { target.execute(t); } finally { if (!participate) { final EntityManagerHolder emHolder = (EntityManagerHolder) TransactionSynchronizationManager .unbindResource(emf); EntityManagerFactoryUtils.closeEntityManager(emHolder.getEntityManager()); } } } } }
From source file:de.zib.gndms.infra.system.GNDMSystemDirectory.java
/** * Loads all <tt>ConfigletStates</tt> managed by a specific <tt>EntityManager</tt> into an array. * * <p>Performs the query "listAllConfiglets" on the database and returns an array containing the result. * * @param emParam an EntityManager managing ConfigletStates * @return an array containing all ConfigletStates of the database *///ww w . ja va 2s . c o m @SuppressWarnings({ "unchecked", "JpaQueryApiInspection", "MethodMayBeStatic" }) private synchronized ConfigletState[] loadConfigletStates(final EntityManager emParam) { final ConfigletState[] states; emParam.getTransaction().begin(); try { Query query = emParam.createNamedQuery("listAllConfiglets"); final List<ConfigletState> list = (List<ConfigletState>) query.getResultList(); Object[] states_ = list.toArray(); states = new ConfigletState[states_.length]; for (int i = 0; i < states_.length; i++) states[i] = (ConfigletState) states_[i]; return states; } finally { if (emParam.getTransaction().isActive()) emParam.getTransaction().commit(); } }
From source file:ec.edu.chyc.manejopersonal.controller.PersonaJpaController.java
public void create(Persona persona/*, Contratado contratado, Tesista tesista, Pasante pasante*/) throws Exception { EntityManager em = null; try {/*from ww w . ja v a2 s .c o m*/ em = getEntityManager(); em.getTransaction().begin(); em.persist(persona); /* if (contratado != null) { contratado.setId(persona.getId()); em.persist(contratado); } if (tesista != null) { tesista.setId(persona.getId()); em.persist(tesista); } if (pasante != null) { pasante.setId(persona.getId()); em.persist(pasante); } */ for (PersonaTitulo personaTitulo : persona.getPersonaTitulosCollection()) { personaTitulo.setPersona(persona); Titulo titulo = personaTitulo.getTitulo(); if (titulo.getId() == null || titulo.getId() < 0) { titulo.setId(null); em.persist(titulo); } if (personaTitulo.getUniversidad().getId() == null || personaTitulo.getUniversidad().getId() < 0) { personaTitulo.getUniversidad().setId(null); em.persist(personaTitulo.getUniversidad()); } if (personaTitulo.getId() == null || personaTitulo.getId() < 0) { personaTitulo.setId(null); em.persist(personaTitulo); } } /*for (PersonaFirma personaFirma : persona.getPersonaFirmasCollection()) { personaFirma.setPersona(persona); Firma firma = personaFirma.getFirma(); if (firma.getId() == null || firma.getId() < 0) { firma.setId(null); em.persist(firma); } if (personaFirma.getId() == null || personaFirma.getId() < 0) { personaFirma.setId(null); em.persist(personaFirma); } }*/ guardarPersonaFirma(em, persona); em.getTransaction().commit(); } finally { if (em != null) { em.close(); } } }