List of usage examples for javax.persistence EntityTransaction rollback
public void rollback();
From source file:fr.natoine.dao.annotation.DAOAnnotation.java
/** * Retrieves a specified quantity of Annotations associated to a Resource specified by its URL * @param _url/*from w ww.j a v a 2 s . c o m*/ * @param asc * @param first_indice * @param max_results * @return */ public List<Annotation> retrieveAnnotations(String _url, boolean asc, int first_indice, int max_results) { //EntityManagerFactory emf = this.setEMF(); EntityManager em = emf.createEntityManager(); EntityTransaction tx = em.getTransaction(); try { tx.begin(); URI _uri = (URI) em.createQuery("from URI where effectiveURI = ?").setParameter(1, _url) .getSingleResult(); if (_uri == null) { tx.commit(); // //em.close(); System.out.println("[RetrieveAnnotation.retrieveAnnotations] unable to retrieve Annotations" + " cause : there is no uri " + _url); return new ArrayList<Annotation>(); } //List annotations = em.createQuery("select distinct annotation from Annotation as annotation inner join annotation.annotated as annotated inner join annotated.representsResource as uri where uri=?").setParameter(1, _uri).getResultList(); String order_by_clause = " order by annotation.id desc"; if (asc) order_by_clause = " order by annotation.id asc"; Query _query = em.createQuery( "select distinct annotation from Annotation as annotation inner join annotation.annotatedURIs as uri where uri=?" + order_by_clause) .setParameter(1, _uri); _query.setFirstResult(first_indice); _query.setMaxResults(max_results); List<Annotation> annotations = _query.getResultList(); tx.commit(); //em.close(); return annotations; } catch (Exception e) { //tx.commit(); tx.rollback(); //em.close(); System.out.println("[RetrieveAnnotation.retrieveAnnotations] unable to retrieve Annotations" + " cause : " + e.getMessage()); return new ArrayList<Annotation>(); } }
From source file:com.eucalyptus.blockstorage.BlockStorageController.java
public GetVolumeTokenResponseType GetVolumeToken(GetVolumeTokenType request) throws EucalyptusCloudException { GetVolumeTokenResponseType reply = (GetVolumeTokenResponseType) request.getReply(); String volumeId = request.getVolumeId(); LOG.info("Processing GetVolumeToken request for volume " + volumeId); if (null == volumeId) { LOG.error("Cannot get token for a null-valued volumeId"); throw new EucalyptusCloudException("No volumeId specified in token request"); }//from www . jav a 2s. co m EntityTransaction db = Entities.get(VolumeInfo.class); try { VolumeInfo vol = Entities.uniqueResult(new VolumeInfo(volumeId)); VolumeToken token = vol.getOrCreateAttachmentToken(); //Encrypt the token with the NC's private key String encryptedToken = BlockStorageUtil.encryptForNode(token.getToken(), BlockStorageUtil.getPartitionForLocalService(Storage.class)); reply.setToken(encryptedToken); reply.setVolumeId(volumeId); db.commit(); return reply; } catch (NoSuchElementException e) { throw new EucalyptusCloudException("Volume " + request.getVolumeId() + " not found", e); } catch (Exception e) { LOG.error("Failed to get volume token: " + e.getMessage()); throw new EucalyptusCloudException("Could not get volume token for volume " + request.getVolumeId(), e); } finally { if (db.isActive()) { db.rollback(); } } }
From source file:org.apache.juddi.config.Install.java
protected static void install(Configuration config) throws JAXBException, DispositionReportFaultMessage, IOException, ConfigurationException { EntityManager em = PersistenceManager.getEntityManager(); EntityTransaction tx = em.getTransaction(); UddiEntityPublisher rootPublisher = null; try {/*from www.ja v a 2 s . c o m*/ tx.begin(); boolean seedAlways = config.getBoolean("juddi.seed.always", false); boolean alreadyInstalled = alreadyInstalled(config); if (!seedAlways && alreadyInstalled) new FatalErrorException(new ErrorMessage("errors.install.AlreadyInstalled")); String rootPublisherStr = config.getString(Property.JUDDI_ROOT_PUBLISHER); String fileRootTModelKeygen = rootPublisherStr + FILE_TMODELKEYGEN; TModel rootTModelKeyGen = (TModel) buildInstallEntity(fileRootTModelKeygen, "org.uddi.api_v3", config); String fileRootBusinessEntity = rootPublisherStr + FILE_BUSINESSENTITY; org.uddi.api_v3.BusinessEntity rootBusinessEntity = (org.uddi.api_v3.BusinessEntity) buildInstallEntity( fileRootBusinessEntity, "org.uddi.api_v3", config); String rootPartition = getRootPartition(rootTModelKeyGen); String nodeId = getNodeId(rootBusinessEntity.getBusinessKey(), rootPartition); String fileRootPublisher = rootPublisherStr + FILE_PUBLISHER; if (!alreadyInstalled) { log.info("Loading the root Publisher from file " + fileRootPublisher); rootPublisher = installPublisher(em, fileRootPublisher, config); installRootPublisherKeyGen(em, rootTModelKeyGen, rootPartition, rootPublisher, nodeId); rootBusinessEntity.setBusinessKey(nodeId); installBusinessEntity(true, em, rootBusinessEntity, rootPublisher, rootPartition, config); } else { log.debug("juddi.seed.always reapplies all seed files except for the root data."); } List<String> juddiPublishers = getPublishers(config); for (String publisherStr : juddiPublishers) { String filePublisher = publisherStr + FILE_PUBLISHER; String fileTModelKeygen = publisherStr + FILE_TMODELKEYGEN; TModel tModelKeyGen = (TModel) buildInstallEntity(fileTModelKeygen, "org.uddi.api_v3", config); String fileBusinessEntity = publisherStr + FILE_BUSINESSENTITY; org.uddi.api_v3.BusinessEntity businessEntity = (org.uddi.api_v3.BusinessEntity) buildInstallEntity( fileBusinessEntity, "org.uddi.api_v3", config); UddiEntityPublisher publisher = installPublisher(em, filePublisher, config); if (publisher == null) { throw new ConfigurationException("File " + filePublisher + " not found."); } else { if (tModelKeyGen != null) installPublisherKeyGen(em, tModelKeyGen, publisher, nodeId); if (businessEntity != null) installBusinessEntity(false, em, businessEntity, publisher, null, config); String fileTModels = publisherStr + FILE_TMODELS; installSaveTModel(em, fileTModels, publisher, nodeId, config); } } tx.commit(); } catch (DispositionReportFaultMessage dr) { log.error(dr.getMessage(), dr); tx.rollback(); throw dr; } catch (JAXBException je) { log.error(je.getMessage(), je); tx.rollback(); throw je; } catch (IOException ie) { log.error(ie.getMessage(), ie); tx.rollback(); throw ie; } finally { if (tx.isActive()) { tx.rollback(); } em.close(); } }
From source file:de.iai.ilcd.model.dao.DataSetDao.java
/** * Generic persist method for data set objects. * /*ww w .j a va2 s .c o 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; }
From source file:fr.natoine.dao.annotation.DAOAnnotation.java
/** * Retrieves all the annotations associated to a Resource specified by its URL, grouped by annotationStatus * @param _url/*from w w w . j a v a2 s. co m*/ * @param asc * @return */ public List<Annotation> retrieveAnnotationsGroupByStatus(String _url, boolean asc) { //EntityManagerFactory emf = this.setEMF(); EntityManager em = emf.createEntityManager(); EntityTransaction tx = em.getTransaction(); try { tx.begin(); URI _uri = (URI) em.createQuery("from URI where effectiveURI = ?").setParameter(1, _url) .getSingleResult(); if (_uri == null) { tx.commit(); // //em.close(); System.out.println("[RetrieveAnnotation.retrieveAnnotations] unable to retrieve Annotations" + " cause : there is no uri " + _url); return new ArrayList<Annotation>(); } //List annotations = em.createQuery("select distinct annotation from Annotation as annotation inner join annotation.annotated as annotated inner join annotated.representsResource as uri where uri=?").setParameter(1, _uri).getResultList(); String order_by_clause = " annotation.id desc"; if (asc) order_by_clause = " annotation.id asc"; List<Annotation> annotations = em.createQuery( "select distinct annotation from Annotation as annotation inner join annotation.annotatedURIs as uri where uri=? order by annotation.status," + order_by_clause) .setParameter(1, _uri).getResultList(); //List annotations = em.createQuery("select distinct annotation from Annotation as annotation inner join annotation.annotatedURIs as uri where uri=? group by annotation.status" ).setParameter(1, _uri).getResultList(); tx.commit(); //em.close(); return annotations; } catch (Exception e) { //tx.commit(); tx.rollback(); //em.close(); System.out.println("[RetrieveAnnotation.retrieveAnnotations] unable to retrieve Annotations" + " cause : " + e.getMessage()); return new ArrayList<Annotation>(); } }
From source file:fr.natoine.dao.annotation.DAOAnnotation.java
/** * Retrieves all the annotations associated to a specified Resource through its URL, ordered by FirstAuthor * @param _url/*from w w w . j av a2 s . com*/ * @param asc * @return */ public List<Annotation> retrieveAnnotationsGroupByFirstAuthor(String _url, boolean asc) { //EntityManagerFactory emf = this.setEMF(); EntityManager em = emf.createEntityManager(); EntityTransaction tx = em.getTransaction(); try { tx.begin(); URI _uri = (URI) em.createQuery("from URI where effectiveURI = ?").setParameter(1, _url) .getSingleResult(); if (_uri == null) { tx.commit(); // //em.close(); System.out.println("[RetrieveAnnotation.retrieveAnnotations] unable to retrieve Annotations" + " cause : there is no uri " + _url); return new ArrayList<Annotation>(); } //List annotations = em.createQuery("select distinct annotation from Annotation as annotation inner join annotation.annotated as annotated inner join annotated.representsResource as uri where uri=?").setParameter(1, _uri).getResultList(); String order_by_clause = " annotation.id desc"; if (asc) order_by_clause = " annotation.id asc"; List<Annotation> annotations = em.createQuery( "select distinct annotation from Annotation as annotation inner join annotation.annotatedURIs as uri where uri=? order by annotation.creator," + order_by_clause) .setParameter(1, _uri).getResultList(); //List annotations = em.createQuery("select distinct annotation from Annotation as annotation inner join annotation.annotatedURIs as uri where uri=? group by annotation.status" ).setParameter(1, _uri).getResultList(); tx.commit(); //em.close(); return annotations; } catch (Exception e) { //tx.commit(); tx.rollback(); //em.close(); System.out.println("[RetrieveAnnotation.retrieveAnnotations] unable to retrieve Annotations" + " cause : " + e.getMessage()); return new ArrayList<Annotation>(); } }
From source file:info.dolezel.jarss.rest.v1.FeedsService.java
@POST @Consumes(MediaType.APPLICATION_JSON)/* w w w . ja v a 2 s . c o m*/ public Response subscribeFeed(@Context SecurityContext context, FeedSubscriptionData data) { FeedCategory fc = null; EntityManager em; EntityTransaction tx; User user; FeedData feedData; Feed f; boolean createdNewFD = false; if (data.getUrl() == null) { return Response.status(Response.Status.BAD_REQUEST).entity(new ErrorDescription("Feed URL missing")) .build(); } user = (User) context.getUserPrincipal(); em = HibernateUtil.getEntityManager(); tx = em.getTransaction(); tx.begin(); try { if (data.getCategoryId() != 0) { try { fc = (FeedCategory) em .createQuery("select fc from FeedCategory fc where fc.id = :id", FeedCategory.class) .setParameter("id", data.getCategoryId()).getSingleResult(); } catch (NoResultException e) { return Response.status(Response.Status.NOT_FOUND) .entity(new ErrorDescription("Feed category not found")).build(); } if (!fc.getUser().equals(user)) { return Response.status(Response.Status.FORBIDDEN) .entity(new ErrorDescription("Feed category not owned by user")).build(); } } // Try to look up existing FeedData try { feedData = (FeedData) em.createNamedQuery("FeedData.getByUrl").setParameter("url", data.getUrl()) .getSingleResult(); } catch (NoResultException e) { feedData = new FeedData(); feedData.setUrl(data.getUrl()); try { loadFeedDetails(feedData); } catch (Exception ex) { e.printStackTrace(); return Response.status(Response.Status.BAD_GATEWAY) .entity(new ErrorDescription("Cannot fetch the feed")).build(); } em.persist(feedData); createdNewFD = true; } f = new Feed(); f.setUser(user); f.setFeedCategory(fc); f.setData(feedData); f.setName(feedData.getTitle()); em.persist(f); tx.commit(); if (createdNewFD) FeedsEngine.getInstance().submitFeedRefresh(feedData); return Response.noContent().build(); } finally { if (tx.isActive()) tx.rollback(); em.close(); } }
From source file:org.apache.juddi.api.impl.UDDIPublicationImpl.java
public BindingDetail saveBinding(SaveBinding body) throws DispositionReportFaultMessage { long startTime = System.currentTimeMillis(); EntityManager em = PersistenceManager.getEntityManager(); EntityTransaction tx = em.getTransaction(); try {/*from ww w. j av a 2 s . c o m*/ tx.begin(); UddiEntityPublisher publisher = this.getEntityPublisher(em, body.getAuthInfo()); ValidatePublish validator = new ValidatePublish(publisher); validator.validateSaveBinding(em, body, null); BindingDetail result = new BindingDetail(); result.setListDescription(new ListDescription()); List<org.uddi.api_v3.BindingTemplate> apiBindingTemplateList = body.getBindingTemplate(); for (org.uddi.api_v3.BindingTemplate apiBindingTemplate : apiBindingTemplateList) { org.apache.juddi.model.BindingTemplate modelBindingTemplate = new org.apache.juddi.model.BindingTemplate(); org.apache.juddi.model.BusinessService modelBusinessService = new org.apache.juddi.model.BusinessService(); modelBusinessService.setEntityKey(apiBindingTemplate.getServiceKey()); MappingApiToModel.mapBindingTemplate(apiBindingTemplate, modelBindingTemplate, modelBusinessService); setOperationalInfo(em, modelBindingTemplate, publisher, false); em.persist(modelBindingTemplate); result.getBindingTemplate().add(apiBindingTemplate); result.getListDescription().setActualCount(result.getListDescription().getActualCount() + 1); result.getListDescription().setIncludeCount(result.getListDescription().getIncludeCount() + 1); validator.validateSaveBindingMax(em, modelBindingTemplate.getBusinessService().getEntityKey()); } tx.commit(); long procTime = System.currentTimeMillis() - startTime; serviceCounter.update(PublicationQuery.SAVE_BINDING, QueryStatus.SUCCESS, procTime); return result; } catch (DispositionReportFaultMessage drfm) { long procTime = System.currentTimeMillis() - startTime; serviceCounter.update(PublicationQuery.SAVE_BINDING, QueryStatus.FAILED, procTime); throw drfm; } finally { if (tx.isActive()) { tx.rollback(); } em.close(); } }
From source file:org.opencastproject.serviceregistry.impl.ServiceRegistryJpaImpl.java
/** * Internal method to update a job, throwing unwrapped JPA exceptions. * //from ww w. j ava 2 s.co m * @param em * the current entity manager * @param job * the job to update * @return the updated job * @throws PersistenceException * if there is an exception thrown while persisting the job via JPA * @throws IllegalArgumentException */ protected Job updateInternal(EntityManager em, Job job) throws PersistenceException { EntityTransaction tx = em.getTransaction(); try { tx.begin(); JobJpaImpl fromDb; fromDb = em.find(JobJpaImpl.class, job.getId()); if (fromDb == null) { throw new NoResultException(); } update(fromDb, (JaxbJob) job); em.merge(fromDb); tx.commit(); ((JaxbJob) job).setVersion(fromDb.getVersion()); setJobUri(job); return job; } catch (PersistenceException e) { if (tx.isActive()) { tx.rollback(); } throw e; } }
From source file:org.apache.juddi.validation.ValidatePublish.java
/** * Validates that a tmodel key is registered Alex O'Ree * * @param tmodelKey// www.j a va2s . c o m * @param em * @throws ValueNotAllowedException * @see org.apache.juddi.config.Install * @since 3.1.5 */ private boolean verifyTModelKeyExistsAndChecked(String tmodelKey, Configuration config) throws ValueNotAllowedException { boolean checked = true; if (tmodelKey == null || tmodelKey.length() == 0) { return false; } if (tmodelKey.equalsIgnoreCase("uddi:uddi.org:categorization:types")) { return false; } if (tmodelKey.equalsIgnoreCase("uddi:uddi.org:categorization:nodes")) { return false; } if (tmodelKey.equalsIgnoreCase("uddi:uddi.org:v3_inquiry")) { return false; } if (tmodelKey.equalsIgnoreCase("uddi:uddi.org:v3_publication")) { return false; } if (tmodelKey.equalsIgnoreCase("uddi:uddi.org:v3_security")) { return false; } if (tmodelKey.equalsIgnoreCase("uddi:uddi.org:v3_ownership_transfer")) { return false; } if (tmodelKey.equalsIgnoreCase("uddi:uddi.org:v3_subscription")) { return false; } if (tmodelKey.equalsIgnoreCase("uddi:uddi.org:v3_subscriptionlistener")) { return false; } if (config == null) { log.warn(new ErrorMessage("errors.tmodel.ReferentialIntegrityNullConfig")); return false; } boolean checkRef = false; try { checkRef = config.getBoolean(Property.JUDDI_ENFORCE_REFERENTIAL_INTEGRITY, false); } catch (Exception ex) { log.warn("Error caught reading " + Property.JUDDI_ENFORCE_REFERENTIAL_INTEGRITY + " from config file", ex); } if (checkRef) { if (log.isDebugEnabled()) { log.debug("verifyTModelKeyExists " + tmodelKey); } EntityManager em = PersistenceManager.getEntityManager(); if (em == null) { //this is normally the Install class firing up log.warn(new ErrorMessage("errors.tmodel.ReferentialIntegrityNullEM")); } else { //Collections.sort(buildInTmodels); //if ((buildInTmodels, tmodelKey) == -1) Tmodel modelTModel = null; { EntityTransaction tx = em.getTransaction(); try { tx.begin(); modelTModel = em.find(org.apache.juddi.model.Tmodel.class, tmodelKey); if (modelTModel == null) { checked = false; } else { for (org.apache.juddi.model.KeyedReference ref : modelTModel.getCategoryBag() .getKeyedReferences()) { if ("uddi-org:types:unchecked".equalsIgnoreCase(ref.getKeyName())) { checked = false; break; } } } tx.commit(); } finally { if (tx.isActive()) { tx.rollback(); } em.close(); } if (modelTModel == null) { throw new ValueNotAllowedException( new ErrorMessage("errors.tmodel.ReferencedKeyDoesNotExist", tmodelKey)); } } } } return checked; }