List of usage examples for javax.persistence EntityManager remove
public void remove(Object entity);
From source file:org.oxymores.chronix.core.ChronixContext.java
public void cleanTransanc() { EntityManager em = this.getTransacEM(); em.getTransaction().begin();// w w w . j a v a2 s . c o m // Remove elements from deleted applications for (String appId : em.createQuery("SELECT DISTINCT tb.appID FROM TranscientBase tb", String.class) .getResultList()) { if (appId != null && this.getApplication(appId) != null) { continue; } em.createQuery("DELETE FROM TranscientBase tb WHERE tb.appID = :a").setParameter("a", appId) .executeUpdate(); em.createQuery("DELETE FROM ClockTick ct WHERE ct.appId = :a").setParameter("a", appId).executeUpdate(); em.createQuery("DELETE FROM TokenReservation tr WHERE tr.applicationId = :a").setParameter("a", appId) .executeUpdate(); } // For each application, purge... for (Application a : this.applicationsByName.values()) { // TB must have a State, a Place, a Source. Purging TB implies purging EV. for (TranscientBase tb : em .createQuery("SELECT tb FROM TranscientBase tb WHERE tb.appID=:a", TranscientBase.class) .setParameter("a", a.getId().toString()).getResultList()) { if (tb instanceof CalendarPointer) { // CalendarPointer are special: there is one without Place & State per Calendar (the calendar main pointer) try { tb.getCalendar(this); if (tb.getStateID() != null || tb.getPlaceID() != null || tb.getActiveID() != null) { if (tb.getState(this) == null || tb.getPlace(this) == null) { em.remove(tb); } } } catch (Exception e) { em.remove(tb); } continue; } else { // General case try { if (tb.getState(this) == null || tb.getPlace(this) == null || tb.getActive(this) == null) { em.remove(tb); } } catch (Exception e) { em.remove(tb); } } } // CT must have a clock for (ClockTick ct : em.createQuery("SELECT ct FROM ClockTick ct WHERE ct.appId=:a", ClockTick.class) .setParameter("a", a.getId().toString()).getResultList()) { try { ct.getClock(this); } catch (Exception e) { em.remove(ct); } } // TR must have Place, State, Token for (TokenReservation tr : em .createQuery("SELECT tr FROM TokenReservation tr WHERE tr.applicationId=:a", TokenReservation.class) .setParameter("a", a.getId().toString()).getResultList()) { try { tr.getState(this); tr.getPlace(this); tr.getToken(this); } catch (Exception e) { em.remove(tr); } } } em.getTransaction().commit(); em.close(); }
From source file:org.apache.juddi.api.impl.UDDISubscriptionImpl.java
public void saveSubscription(String authInfo, Holder<List<Subscription>> subscription) throws DispositionReportFaultMessage { long startTime = System.currentTimeMillis(); EntityManager em = PersistenceManager.getEntityManager(); EntityTransaction tx = em.getTransaction(); try {//from w ww . ja va 2 s.co m tx.begin(); UddiEntityPublisher publisher = this.getEntityPublisher(em, authInfo); new ValidateSubscription(publisher).validateSubscriptions(em, subscription.value); List<org.uddi.sub_v3.Subscription> apiSubscriptionList = subscription.value; for (org.uddi.sub_v3.Subscription apiSubscription : apiSubscriptionList) { org.apache.juddi.model.Subscription modelSubscription = new org.apache.juddi.model.Subscription(); Object existing = em.find(org.apache.juddi.model.Subscription.class, apiSubscription.getSubscriptionKey()); if (existing != null) { org.apache.juddi.model.Subscription existingEntity = (org.apache.juddi.model.Subscription) existing; doRenewal(existingEntity, apiSubscription); //carrying over the created and last notified dates if this is a renewal. modelSubscription.setCreateDate(existingEntity.getCreateDate()); modelSubscription.setLastNotified(existingEntity.getLastNotified()); em.remove(existing); } else { modelSubscription.setCreateDate(new Date()); } doSubscriptionExpirationDate(apiSubscription); MappingApiToModel.mapSubscription(apiSubscription, modelSubscription); modelSubscription.setAuthorizedName(publisher.getAuthorizedName()); // Add the matching keys to the match collection List<?> keys = getSubscriptionMatches(apiSubscription.getSubscriptionFilter(), em); if (keys != null && keys.size() > 0) { for (Object key : keys) { SubscriptionMatch subMatch = new SubscriptionMatch(modelSubscription, (String) key); modelSubscription.getSubscriptionMatches().add(subMatch); } } em.persist(modelSubscription); } tx.commit(); long procTime = System.currentTimeMillis() - startTime; serviceCounter.update(SubscriptionQuery.SAVE_SUBSCRIPTION, QueryStatus.SUCCESS, procTime); } catch (DispositionReportFaultMessage drfm) { long procTime = System.currentTimeMillis() - startTime; serviceCounter.update(SubscriptionQuery.SAVE_SUBSCRIPTION, QueryStatus.FAILED, procTime); throw drfm; } finally { if (tx.isActive()) { tx.rollback(); } em.close(); } }
From source file:io.apiman.manager.api.jpa.JpaStorage.java
private <T> void remove(T entity) throws StorageException { EntityManager em = getActiveEntityManager(); em.remove(em.contains(entity) ? entity : em.merge(entity)); }
From source file:com.espirit.moddev.examples.uxbridge.newsdrilldown.jpa.NewsHandler.java
/** * Deletes a newsdrilldown from the db./*from w ww . j av a2 s. c om*/ * * @param entity The newsdrilldown to delete */ public void delete(UXBEntity entity) throws Exception { EntityManager em = null; EntityTransaction tx = null; try { em = emf.createEntityManager(); tx = em.getTransaction(); tx.begin(); Query query = em.createQuery(new StringBuilder() .append("FROM news x WHERE x.fs_id = :fs_id AND x.language = :language").toString()); query.setParameter("fs_id", Long.parseLong(entity.getUuid())); query.setParameter("language", entity.getLanguage()); if (!query.getResultList().isEmpty()) { News art = (News) query.getSingleResult(); // delete file from filesystem URL url = new URL(art.getUrl()); File file = new File(webpath + url.getPath()); if (file.exists()) { // Try acquiring the lock without blocking. This method returns // null or throws an exception if the file is already locked. try { FileChannel channel = new RandomAccessFile(file, "rw").getChannel(); // Try to lock the file FileLock lock = channel.tryLock(); // Delete the file file.delete(); // Release the lock lock.release(); lock.channel().close(); } catch (OverlappingFileLockException e) { logger.info("File is already locked in this thread or virtual machine"); } catch (MalformedURLException e) { logger.info("wrong url", e); } } // remove article from content repository em.remove(art); } tx.commit(); } catch (Exception e) { if (tx != null) { tx.setRollbackOnly(); } throw e; } finally { if (tx != null && tx.isActive()) { if (tx.getRollbackOnly()) { tx.rollback(); } } if (em != null) { em.close(); } } }
From source file:org.apache.juddi.api.impl.JUDDIApiImpl.java
/** * Deletes publisher(s) from the persistence layer. This method is * specific to jUDDI. Administrative privilege required. * * @param body/*from w ww. j a v a2s .c om*/ * @throws DispositionReportFaultMessage */ public void deletePublisher(DeletePublisher body) throws DispositionReportFaultMessage { EntityManager em = PersistenceManager.getEntityManager(); EntityTransaction tx = em.getTransaction(); try { tx.begin(); UddiEntityPublisher publisher = this.getEntityPublisher(em, body.getAuthInfo()); new ValidatePublish(publisher).validateDeletePublisher(em, body); List<String> entityKeyList = body.getPublisherId(); for (String entityKey : entityKeyList) { Publisher obj = em.find(org.apache.juddi.model.Publisher.class, entityKey); //get an authtoken for this publisher so that we can get its registeredInfo UDDISecurityImpl security = new UDDISecurityImpl(); AuthToken authToken = security.getAuthToken(entityKey); GetRegisteredInfo r = new GetRegisteredInfo(); r.setAuthInfo(authToken.getAuthInfo()); r.setInfoSelection(InfoSelection.ALL); log.info("removing all businesses owned by publisher " + entityKey + "."); UDDIPublicationImpl publish = new UDDIPublicationImpl(); RegisteredInfo registeredInfo = publish.getRegisteredInfo(r); BusinessInfos businessInfos = registeredInfo.getBusinessInfos(); if (businessInfos != null && businessInfos.getBusinessInfo() != null) { Iterator<BusinessInfo> iter = businessInfos.getBusinessInfo().iterator(); while (iter.hasNext()) { BusinessInfo businessInfo = iter.next(); Object business = em.find(org.apache.juddi.model.BusinessEntity.class, businessInfo.getBusinessKey()); em.remove(business); } } log.info("mark all tmodels for publisher " + entityKey + " as deleted."); TModelInfos tmodelInfos = registeredInfo.getTModelInfos(); if (tmodelInfos != null && tmodelInfos.getTModelInfo() != null) { Iterator<TModelInfo> iter = tmodelInfos.getTModelInfo().iterator(); while (iter.hasNext()) { TModelInfo tModelInfo = iter.next(); Tmodel tmodel = (Tmodel) em.find(org.apache.juddi.model.Tmodel.class, tModelInfo.getTModelKey()); tmodel.setDeleted(true); em.persist(tmodel); } } log.info("remove all persisted AuthTokens for publisher " + entityKey + "."); Query q1 = em .createQuery("DELETE FROM AuthToken auth WHERE auth.authorizedName = '" + entityKey + "'"); q1.executeUpdate(); log.info("removing publisher " + entityKey + "."); //delete the publisher em.remove(obj); } tx.commit(); } finally { if (tx.isActive()) { tx.rollback(); } em.close(); } }
From source file:org.apache.juddi.api.impl.UDDIPublicationImpl.java
private void setOperationalInfo(EntityManager em, org.apache.juddi.model.BusinessService uddiEntity, UddiEntityPublisher publisher, boolean isChild) throws DispositionReportFaultMessage { uddiEntity.setAuthorizedName(publisher.getAuthorizedName()); Date now = new Date(); uddiEntity.setModified(now);/*from w w w . j a va2 s .co m*/ uddiEntity.setModifiedIncludingChildren(now); if (!isChild) { org.apache.juddi.model.BusinessEntity parent = em.find(org.apache.juddi.model.BusinessEntity.class, uddiEntity.getBusinessEntity().getEntityKey()); parent.setModifiedIncludingChildren(now); em.persist(parent); } String nodeId = ""; try { nodeId = AppConfig.getConfiguration().getString(Property.JUDDI_NODE_ID); } catch (ConfigurationException ce) { throw new FatalErrorException( new ErrorMessage("errors.configuration.Retrieval", Property.JUDDI_NODE_ID)); } uddiEntity.setNodeId(nodeId); org.apache.juddi.model.BusinessService existingUddiEntity = em.find(uddiEntity.getClass(), uddiEntity.getEntityKey()); if (existingUddiEntity != null) { uddiEntity.setCreated(existingUddiEntity.getCreated()); } else uddiEntity.setCreated(now); List<org.apache.juddi.model.BindingTemplate> bindingList = uddiEntity.getBindingTemplates(); for (org.apache.juddi.model.BindingTemplate binding : bindingList) setOperationalInfo(em, binding, publisher, true); if (existingUddiEntity != null) em.remove(existingUddiEntity); }
From source file:op.controlling.PnlControlling.java
private JPanel createContentPanel4Drugs() { JPanel pnlContent = new JPanel(new VerticalLayout()); /***//from ww w. j a v a 2s .c o m * ____ ____ _ _ _ _ _ * | _ \ _ __ _ _ __ _ / ___|___ _ __ | |_ _ __ ___ | | | | (_)___| |_ * | | | | '__| | | |/ _` | | | / _ \| '_ \| __| '__/ _ \| | | | | / __| __| * | |_| | | | |_| | (_| | | |__| (_) | | | | |_| | | (_) | | | |___| \__ \ |_ * |____/|_| \__,_|\__, | \____\___/|_| |_|\__|_| \___/|_| |_____|_|___/\__| * |___/ */ JPanel pnlDrugControl = new JPanel(new BorderLayout()); final JButton btnDrugControl = GUITools.createHyperlinkButton("opde.controlling.drugs.controllist", null, null); final JComboBox cmbStation = new JComboBox(StationTools.getAll4Combobox(false)); btnDrugControl.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { OPDE.getMainframe().setBlocked(true); SwingWorker worker = new SwingWorker() { @Override protected Object doInBackground() throws Exception { return MedStockTools.getListForMedControl((Station) cmbStation.getSelectedItem(), progressClosure); } @Override protected void done() { try { SYSFilesTools.print(get().toString(), true); } catch (ExecutionException ee) { OPDE.fatal(ee); } catch (InterruptedException ie) { // nop } OPDE.getDisplayManager().setProgressBarMessage(null); OPDE.getMainframe().setBlocked(false); } }; worker.execute(); } }); pnlDrugControl.add(btnDrugControl, BorderLayout.WEST); pnlDrugControl.add(cmbStation, BorderLayout.EAST); pnlContent.add(pnlDrugControl); /*** * __ __ _ _ _ ____ _ _ _ _ _ _ * \ \ / /__(_) __ _| |__ | |_ / ___|___ _ __ | |_ _ __ ___ | | | \ | | __ _ _ __ ___ ___ | |_(_) ___ ___ * \ \ /\ / / _ \ |/ _` | '_ \| __| | / _ \| '_ \| __| '__/ _ \| | | \| |/ _` | '__/ __/ _ \| __| |/ __/ __| * \ V V / __/ | (_| | | | | |_| |__| (_) | | | | |_| | | (_) | | | |\ | (_| | | | (_| (_) | |_| | (__\__ \ * \_/\_/ \___|_|\__, |_| |_|\__|\____\___/|_| |_|\__|_| \___/|_| |_| \_|\__,_|_| \___\___/ \__|_|\___|___/ * |___/ */ JPanel pnlWeightControllNarcotics = new JPanel(new BorderLayout()); final JButton btnWeightControl = GUITools .createHyperlinkButton("opde.controlling.prescription.narcotics.weightcontrol", null, null); // final JComboBox cmbStation = new JComboBox(StationTools.getAll4Combobox(false)); btnWeightControl.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { OPDE.getMainframe().setBlocked(true); SwingWorker worker = new SwingWorker() { @Override protected Object doInBackground() throws Exception { return MedStockTools.getNarcoticsWeightList(new LocalDate().minusMonths(1), new LocalDate()); } @Override protected void done() { try { SYSFilesTools.print(get().toString(), true); } catch (ExecutionException ee) { OPDE.fatal(ee); } catch (InterruptedException ie) { // nop } OPDE.getDisplayManager().setProgressBarMessage(null); OPDE.getMainframe().setBlocked(false); } }; worker.execute(); } }); final JToggleButton btnNotify = new JToggleButton(SYSConst.icon22mailOFF); btnNotify.setSelectedIcon(SYSConst.icon22mailON); btnNotify.setSelected(NotificationTools.find(OPDE.getLogin().getUser(), NotificationTools.NKEY_DRUG_WEIGHT_CONTROL) != null); btnNotify.setToolTipText(SYSTools.xx("opde.notification.enable.for.this.topic")); btnNotify.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent e) { EntityManager em = OPDE.createEM(); try { em.getTransaction().begin(); Users user = em.merge(OPDE.getLogin().getUser()); em.lock(user, LockModeType.OPTIMISTIC_FORCE_INCREMENT); if (e.getStateChange() == ItemEvent.SELECTED) { Notification myNotification = em .merge(new Notification(NotificationTools.NKEY_DRUG_WEIGHT_CONTROL, user)); user.getNotifications().add(myNotification); } else { Notification myNotification = em.merge(NotificationTools.find(OPDE.getLogin().getUser(), NotificationTools.NKEY_DRUG_WEIGHT_CONTROL)); user.getNotifications().remove(myNotification); em.remove(myNotification); } em.getTransaction().commit(); OPDE.getLogin().setUser(user); } 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 ex) { if (em.getTransaction().isActive()) { em.getTransaction().rollback(); } OPDE.fatal(ex); } finally { em.close(); } } }); pnlWeightControllNarcotics.add(btnWeightControl, BorderLayout.WEST); pnlWeightControllNarcotics.add(btnNotify, BorderLayout.EAST); pnlContent.add(pnlWeightControllNarcotics); return pnlContent; }
From source file:com.enioka.jqm.api.HibernateClient.java
public int restartCrashedJob(int idJob) { EntityManager em = null; // History and Job ID have the same ID. History h = null;//w w w.ja v a 2 s.co m try { em = getEm(); h = em.find(History.class, idJob); } catch (NoResultException e) { closeQuietly(em); throw new JqmClientException( "You cannot restart a job that is not done or which was purged from history"); } catch (Exception e) { closeQuietly(em); throw new JqmClientException("could not restart a job (internal error)", e); } if (!h.getState().equals(State.CRASHED)) { closeQuietly(em); throw new JqmClientException("You cannot restart a job that has not crashed"); } if (!h.getJd().isCanBeRestarted()) { closeQuietly(em); throw new JqmClientException("This type of job was configured to prevent being restarded"); } try { em.getTransaction().begin(); em.remove(h); em.getTransaction().commit(); return enqueue(getJobRequest(h, em)); } catch (Exception e) { throw new JqmClientException("could not purge & restart a job (internal error)", e); } finally { closeQuietly(em); } }
From source file:org.apache.juddi.api.impl.UDDIPublicationImpl.java
private void setOperationalInfo(EntityManager em, org.apache.juddi.model.BindingTemplate uddiEntity, UddiEntityPublisher publisher, boolean isChild) throws DispositionReportFaultMessage { uddiEntity.setAuthorizedName(publisher.getAuthorizedName()); Date now = new Date(); uddiEntity.setModified(now);//w w w.j a v a2 s . c om uddiEntity.setModifiedIncludingChildren(now); if (!isChild) { org.apache.juddi.model.BusinessService parent = em.find(org.apache.juddi.model.BusinessService.class, uddiEntity.getBusinessService().getEntityKey()); parent.setModifiedIncludingChildren(now); em.persist(parent); // JUDDI-421: now the businessEntity parent will have it's modifiedIncludingChildren set org.apache.juddi.model.BusinessEntity businessParent = em .find(org.apache.juddi.model.BusinessEntity.class, parent.getBusinessEntity().getEntityKey()); businessParent.setModifiedIncludingChildren(now); em.persist(businessParent); } String nodeId = ""; try { nodeId = AppConfig.getConfiguration().getString(Property.JUDDI_NODE_ID); } catch (ConfigurationException ce) { throw new FatalErrorException( new ErrorMessage("errors.configuration.Retrieval", Property.JUDDI_NODE_ID)); } uddiEntity.setNodeId(nodeId); org.apache.juddi.model.BindingTemplate existingUddiEntity = em.find(uddiEntity.getClass(), uddiEntity.getEntityKey()); if (existingUddiEntity != null) uddiEntity.setCreated(existingUddiEntity.getCreated()); else uddiEntity.setCreated(now); if (existingUddiEntity != null) em.remove(existingUddiEntity); }
From source file:de.iai.ilcd.model.dao.DataSetDao.java
/** * Generic persist method for data set objects. * //from www . j a v a 2 s .co m * @param dataSet * data set to persist * @param pType * which type of persistence operation, new, update (i.e. overwrite existing data set), ... * @param out * PrintWriter to log error messages which can be presented to the end user * @return true if persist is successful, false otherwise * @see #preCheckAndPersist(DataSet) */ public boolean checkAndPersist(T dataSet, PersistType pType, PrintWriter out) { // TODO: check if version shall be excluded for some types if (dataSet.getRootDataStock() == null) { out.println("Error: root data stock must not be null!"); return false; } // perform pre-persist actions this.preCheckAndPersist(dataSet); EntityManager em = PersistenceUtil.getEntityManager(); // locate existing method by UUID T existingDataSet = this.getByUuidAndVersion(dataSet.getUuidAsString(), dataSet.getVersion()); // if existing found ... if (existingDataSet != null) { // ... and mode is set to only new ... if (PersistType.ONLYNEW.equals(pType)) { if (out != null) { out.println("Warning: " + this.getAccessedClass().getSimpleName() + " data set with uuid " + dataSet.getUuidAsString() + " and version " + dataSet.getVersion().getVersionString() + " already exists in database; will ignore this data set."); } // ... just ignore it return false; } } EntityTransaction t = em.getTransaction(); // now the DB interaction try { t.begin(); // delete existing for merge operation if (existingDataSet != null && PersistType.MERGE.equals(pType)) { if (out != null) { out.println("Notice: " + this.getAccessedClass().getSimpleName() + " method data set with uuid " + existingDataSet.getUuidAsString() + " and version " + existingDataSet.getVersion().getVersionString() + " already exists in database; will replace it with this data set"); } em.remove(existingDataSet); } // persist the new method em.persist(dataSet); // actual write to DB t.commit(); // set the most recent version flags correctly if (!this.setMostRecentVersionFlags(dataSet.getUuidAsString())) { return false; } // and return with success :) return true; } catch (Exception e) { DataSetDao.LOGGER.error( "Cannot persist " + this.getAccessedClass().getSimpleName() + " data set with uuid {}", dataSet.getUuidAsString()); DataSetDao.LOGGER.error("Exception is: ", e); if (out != null) { out.println("Error: " + this.getAccessedClass().getSimpleName() + " data set with uuid " + dataSet.getUuidAsString() + " and version " + dataSet.getVersion().getVersionString() + " could not be saved into database; unknown database error; Exception message: " + e.getMessage()); } t.rollback(); } return false; }