List of usage examples for javax.persistence EntityTransaction commit
public void commit();
From source file:org.apache.juddi.api.impl.JUDDIApiImpl.java
/** * Instructs the registry to perform a synchronous subscription * response.//from ww w .ja v a 2 s.co m * @param body * @return SyncSubscriptionDetail * @throws DispositionReportFaultMessage * @throws RemoteException */ @SuppressWarnings("unchecked") public SyncSubscriptionDetail invokeSyncSubscription(SyncSubscription body) throws DispositionReportFaultMessage, RemoteException { //validate SyncSubscriptionDetail syncSubscriptionDetail = new SyncSubscriptionDetail(); Map<String, org.apache.juddi.api_v3.ClientSubscriptionInfo> clientSubscriptionInfoMap = new HashMap<String, org.apache.juddi.api_v3.ClientSubscriptionInfo>(); //find the clerks to go with these subscriptions EntityManager em = PersistenceManager.getEntityManager(); EntityTransaction tx = em.getTransaction(); try { tx.begin(); this.getEntityPublisher(em, body.getAuthInfo()); for (GetSubscriptionResults getSubscriptionResult : body.getGetSubscriptionResultsList()) { String subscriptionKey = getSubscriptionResult.getSubscriptionKey(); org.apache.juddi.model.ClientSubscriptionInfo modelClientSubscriptionInfo = null; try { modelClientSubscriptionInfo = em.find(org.apache.juddi.model.ClientSubscriptionInfo.class, subscriptionKey); } catch (ClassCastException e) { } if (modelClientSubscriptionInfo == null) { throw new InvalidKeyPassedException( new ErrorMessage("errors.invalidkey.SubscripKeyNotFound", subscriptionKey)); } org.apache.juddi.api_v3.ClientSubscriptionInfo apiClientSubscriptionInfo = new org.apache.juddi.api_v3.ClientSubscriptionInfo(); MappingModelToApi.mapClientSubscriptionInfo(modelClientSubscriptionInfo, apiClientSubscriptionInfo); clientSubscriptionInfoMap.put(apiClientSubscriptionInfo.getSubscriptionKey(), apiClientSubscriptionInfo); } tx.commit(); } finally { if (tx.isActive()) { tx.rollback(); } em.close(); } for (GetSubscriptionResults getSubscriptionResult : body.getGetSubscriptionResultsList()) { try { String subscriptionKey = getSubscriptionResult.getSubscriptionKey(); Clerk fromClerk = clientSubscriptionInfoMap.get(subscriptionKey).getFromClerk(); Clerk toClerk = clientSubscriptionInfoMap.get(subscriptionKey).getToClerk(); String clazz = fromClerk.getNode().getProxyTransport(); Class<?> transportClass = ClassUtil.forName(clazz, this.getClass()); Transport transport = (Transport) transportClass.getConstructor(String.class) .newInstance(fromClerk.getNode().getName()); UDDISubscriptionPortType subscriptionService = transport .getUDDISubscriptionService(fromClerk.getNode().getSubscriptionUrl()); SubscriptionResultsList list = subscriptionService.getSubscriptionResults(getSubscriptionResult); JAXBContext context = JAXBContext.newInstance(list.getClass()); Marshaller marshaller = context.createMarshaller(); StringWriter sw = new StringWriter(); marshaller.marshal(list, sw); log.info("Notification received by UDDISubscriptionListenerService : " + sw.toString()); NotificationList<String> nl = NotificationList.getInstance(); nl.getNotifications().add(sw.toString()); //update the registry with the notification list. XRegisterHelper.handle(fromClerk, toClerk, list); syncSubscriptionDetail.getSubscriptionResultsList().add(list); } catch (Exception ce) { log.error(ce.getMessage(), ce); if (ce instanceof DispositionReportFaultMessage) { throw (DispositionReportFaultMessage) ce; } if (ce instanceof RemoteException) { throw (RemoteException) ce; } } } //for now sending a clean object back return syncSubscriptionDetail; }
From source file:com.eucalyptus.images.ImageManager.java
public ModifyImageAttributeResponseType modifyImageAttribute(final ModifyImageAttributeType request) throws EucalyptusCloudException { final ModifyImageAttributeResponseType reply = (ModifyImageAttributeResponseType) request.getReply(); final EntityTransaction tx = Entities.get(ImageInfo.class); try {/* w ww . ja va 2s . co m*/ final ImageInfo imgInfo = Entities .uniqueResult(Images.exampleWithImageId(imageIdentifier(request.getImageId()))); if (!canModifyImage(imgInfo)) { throw new EucalyptusCloudException("Not authorized to modify image attribute"); } switch (request.imageAttribute()) { case LaunchPermission: if (request.add()) { imgInfo.addPermissions(verifyUserIds(request.userIds())); if (request.groupAll()) { imgInfo.setImagePublic(true); } } else { imgInfo.removePermissions(request.userIds()); if (request.groupAll()) { imgInfo.setImagePublic(false); } } break; case ProductCode: for (String productCode : request.getProductCodes()) { imgInfo.addProductCode(productCode); } break; case Description: imgInfo.setDescription(request.getDescription()); break; } tx.commit(); reply.set_return(true); } catch (EucalyptusCloudException e) { tx.rollback(); reply.set_return(false); throw e; } catch (TransactionException | NoSuchElementException ex) { tx.rollback(); throw new EucalyptusCloudException(ex); } return reply; }
From source file:org.apache.juddi.api.impl.UDDICustodyTransferImpl.java
public void getTransferToken(String authInfo, KeyBag keyBag, Holder<String> nodeID, Holder<XMLGregorianCalendar> expirationTime, Holder<byte[]> opaqueToken) throws DispositionReportFaultMessage { long startTime = System.currentTimeMillis(); EntityManager em = PersistenceManager.getEntityManager(); EntityTransaction tx = em.getTransaction(); try {//from w w w . j a v a 2 s .com tx.begin(); UddiEntityPublisher publisher = this.getEntityPublisher(em, authInfo); new ValidateCustodyTransfer(publisher).validateGetTransferToken(em, keyBag); int transferExpirationDays = DEFAULT_TRANSFEREXPIRATION_DAYS; try { transferExpirationDays = AppConfig.getConfiguration() .getInt(Property.JUDDI_TRANSFER_EXPIRATION_DAYS); // For output nodeID.value = AppConfig.getConfiguration().getString(Property.JUDDI_NODE_ID); } catch (ConfigurationException ce) { throw new FatalErrorException(new ErrorMessage("errors.configuration.Retrieval")); } String transferKey = TRANSFER_TOKEN_PREFIX + UUID.randomUUID(); org.apache.juddi.model.TransferToken transferToken = new org.apache.juddi.model.TransferToken(); transferToken.setTransferToken(transferKey); // For output opaqueToken.value = transferKey.getBytes(); GregorianCalendar gc = new GregorianCalendar(); gc.add(GregorianCalendar.DAY_OF_MONTH, transferExpirationDays); transferToken.setExpirationDate(gc.getTime()); try { DatatypeFactory df = DatatypeFactory.newInstance(); // For output expirationTime.value = df.newXMLGregorianCalendar(gc); } catch (DatatypeConfigurationException ce) { throw new FatalErrorException(new ErrorMessage("errors.Unspecified")); } List<String> keyList = keyBag.getKey(); for (String key : keyList) { TransferTokenKey tokenKey = new TransferTokenKey(transferToken, key); transferToken.getTransferKeys().add(tokenKey); } em.persist(transferToken); tx.commit(); long procTime = System.currentTimeMillis() - startTime; serviceCounter.update(CustodyTransferQuery.GET_TRANSFERTOKEN, QueryStatus.SUCCESS, procTime); } finally { if (tx.isActive()) { tx.rollback(); } em.close(); } }
From source file:com.eucalyptus.blockstorage.BlockStorageController.java
/** * Perform a volume export validated by the token presented in the request. * Upon completion of the Export operation, the identified host (by ip and iqn) will * have access to connect to the requested volume. No connection is made, just the authorization. * * If a valid export record exists for the given token and host information, then the connectionString * for that record is returned rather than creating a new record. * @param request//from w ww . j a v a 2 s .c om * @return * @throws EucalyptusCloudException */ public ExportVolumeResponseType ExportVolume(ExportVolumeType request) throws EucalyptusCloudException { final ExportVolumeResponseType reply = (ExportVolumeResponseType) request.getReply(); final String volumeId = request.getVolumeId(); final String token = request.getToken(); final String ip = request.getIp(); final String iqn = request.getIqn(); reply.setVolumeId(volumeId); LOG.info("Processing ExportVolume request for volume " + volumeId); final Function<VolumeInfo, String> exportAndAttach = new Function<VolumeInfo, String>() { @Override public String apply(VolumeInfo volume) { int tokenRetry = 3; VolumeToken tokenInfo = null; VolumeInfo volEntity = Entities.merge(volume); for (int i = 0; i < tokenRetry; i++) { try { tokenInfo = volEntity.getAttachmentTokenIfValid(token); if (tokenInfo != null) { break; } } catch (Exception e) { LOG.warn("Could not check for valid token. Will retry. ", e); tokenInfo = null; } try { Thread.sleep(100); //sleep 100ms to make retry useful. } catch (InterruptedException e) { throw new RuntimeException("Token check backoff sleep interrupted", e); } } if (tokenInfo == null) { throw new RuntimeException("Cannot export, due to invalid token"); } VolumeExportRecord export = null; try { export = tokenInfo.getValidExport(ip, iqn); } catch (EucalyptusCloudException e2) { LOG.error("Failed when checking/getting valid export for " + ip + " - " + iqn); return null; } if (export == null) { String connectionString = null; try { //attachVolume must be idempotent. connectionString = blockManager.exportVolume(volumeId, iqn); } catch (Exception e) { LOG.error("Could not attach volume: " + e.getMessage()); LOG.trace("Failed volume attach", e); return null; } try { //addExport must be idempotent, if one exists a new is not added with same data tokenInfo.addExport(ip, iqn, connectionString); return connectionString; } catch (Exception e) { LOG.error("Could not export volume " + volumeId + " failed to add export record"); try { LOG.info("Unexporting volume " + volumeId + " to " + iqn + " for export failure cleanup"); blockManager.unexportVolume(volumeId, iqn); } catch (EucalyptusCloudException e1) { LOG.error("Failed to detach volume during invalidation failure", e); } return null; } } else { LOG.debug("Found extant valid export for " + ip + " and " + iqn + " returning connection information for that export"); return export.getConnectionString(); } } }; VolumeInfo searchVol = new VolumeInfo(volumeId); EntityTransaction db = Entities.get(VolumeInfo.class); VolumeInfo vol = null; try { vol = Entities.uniqueResult(searchVol); db.commit(); } catch (NoSuchElementException e) { LOG.error("No volume db record found for " + volumeId, e); throw new EucalyptusCloudException("Volume not found " + volumeId); } catch (TransactionException e) { LOG.error("Failed to Export due to db error", e); throw new EucalyptusCloudException("Could not export volume", e); } finally { if (db.isActive()) { db.rollback(); } } //Do the export try { String connectionString = Entities.asTransaction(VolumeInfo.class, exportAndAttach).apply(vol); if (connectionString != null) { reply.setConnectionString(connectionString); } else { throw new Exception("Got null record result. Cannot set connection string"); } } catch (Exception e) { LOG.error("Failed ExportVolume transaction due to: " + e.getMessage(), e); throw new EucalyptusCloudException("Failed to add export", e); } return reply; }
From source file:org.apache.juddi.api.impl.UDDIPublicationImpl.java
public ServiceDetail saveService(SaveService body) throws DispositionReportFaultMessage { long startTime = System.currentTimeMillis(); EntityManager em = PersistenceManager.getEntityManager(); EntityTransaction tx = em.getTransaction(); try {//w w w. j av a2 s. co m tx.begin(); UddiEntityPublisher publisher = this.getEntityPublisher(em, body.getAuthInfo()); ValidatePublish validator = new ValidatePublish(publisher); validator.validateSaveService(em, body, null); ServiceDetail result = new ServiceDetail(); List<org.uddi.api_v3.BusinessService> apiBusinessServiceList = body.getBusinessService(); for (org.uddi.api_v3.BusinessService apiBusinessService : apiBusinessServiceList) { org.apache.juddi.model.BusinessService modelBusinessService = new org.apache.juddi.model.BusinessService(); org.apache.juddi.model.BusinessEntity modelBusinessEntity = new org.apache.juddi.model.BusinessEntity(); modelBusinessEntity.setEntityKey(apiBusinessService.getBusinessKey()); MappingApiToModel.mapBusinessService(apiBusinessService, modelBusinessService, modelBusinessEntity); setOperationalInfo(em, modelBusinessService, publisher, false); em.persist(modelBusinessService); result.getBusinessService().add(apiBusinessService); validator.validateSaveServiceMax(em, modelBusinessService.getBusinessEntity().getEntityKey()); } tx.commit(); long procTime = System.currentTimeMillis() - startTime; serviceCounter.update(PublicationQuery.SAVE_SERVICE, QueryStatus.SUCCESS, procTime); return result; } catch (DispositionReportFaultMessage drfm) { long procTime = System.currentTimeMillis() - startTime; serviceCounter.update(PublicationQuery.SAVE_SERVICE, QueryStatus.FAILED, procTime); throw drfm; } finally { if (tx.isActive()) { tx.rollback(); } em.close(); } }
From source file:de.randi2.testUtility.utility.Bootstrap.java
private void initRandBS(Trial trial, GregorianCalendar date, Random rand) { // long time1 = System.nanoTime(); EntityTransaction transaction = entityManager.getTransaction(); transaction.begin();/*from w w w .j av a 2 s . com*/ trial = entityManager.find(Trial.class, trial.getId()); TrialSubject subject = new TrialSubject(); SubjectProperty<Serializable> subprob = new SubjectProperty<Serializable>(trial.getCriteria().get(0)); SubjectProperty<Serializable> subprob1 = new SubjectProperty<Serializable>(trial.getCriteria().get(1)); SubjectProperty<Serializable> subprob2 = new SubjectProperty<Serializable>(trial.getCriteria().get(2)); try { if (rand.nextInt(2) == 0) { subprob.setValue(DichotomousCriterion.class.cast(trial.getCriteria().get(0)).getOption1()); } else { subprob.setValue(DichotomousCriterion.class.cast(trial.getCriteria().get(0)).getOption2()); } if (rand.nextInt(2) == 0) { subprob1.setValue(DichotomousCriterion.class.cast(trial.getCriteria().get(1)).getOption1()); } else { subprob1.setValue(DichotomousCriterion.class.cast(trial.getCriteria().get(1)).getOption2()); } if (rand.nextInt(2) == 0) { subprob2.setValue(DichotomousCriterion.class.cast(trial.getCriteria().get(2)).getOption1()); } else { subprob2.setValue(DichotomousCriterion.class.cast(trial.getCriteria().get(2)).getOption2()); } } catch (ConstraintViolatedException e) { e.printStackTrace(); } Set<SubjectProperty<?>> proberties = new HashSet<SubjectProperty<?>>(); proberties.add(subprob); proberties.add(subprob1); proberties.add(subprob2); subject.setProperties(proberties); trialService.randomize(trial, subject); transaction.commit(); transaction.begin(); subject = entityManager.find(TrialSubject.class, subject.getId()); subject.setCreatedAt(date); subject = entityManager.merge(subject); transaction.commit(); // System.out.println("time random before: " + // (System.nanoTime()-time1)/1000000 + " ms"); }
From source file:de.iai.ilcd.model.dao.DataSetDao.java
/** * Set the {@link DataSet#setMostRecentVersion(boolean) most recent version flags} for all data sets with the * specified uuid. Please note that this method * <strong>does not open a separate transaction</strong>. * /*from w w w .j a v a2 s.c om*/ * @param uuid * uuid of the data sets */ @SuppressWarnings("unchecked") protected boolean setMostRecentVersionFlags(String uuid) { EntityManager em = PersistenceUtil.getEntityManager(); EntityTransaction t = em.getTransaction(); try { Query q = em.createQuery("SELECT a FROM " + this.getJpaName() + " a WHERE a.uuid.uuid=:uuid ORDER BY a.version.majorVersion desc, a.version.minorVersion desc, a.version.subMinorVersion desc"); q.setParameter("uuid", uuid); List<T> res = q.getResultList(); if (!res.isEmpty()) { t.begin(); // get first element and mark it as most recent version (correct order is taken care of in query!) T tmp = res.get(0); tmp.setMostRecentVersion(true); tmp = em.merge(tmp); // set "false" for all other elements if required final int size = res.size(); if (size > 1) { for (int i = 1; i < size; i++) { tmp = res.get(i); if (tmp.isMostRecentVersion()) { tmp.setMostRecentVersion(false); tmp = em.merge(tmp); } } } t.commit(); return true; } else { DataSetDao.LOGGER.warn("Most recent version flag was called for non-existent UUID: " + uuid); return false; } } catch (Exception e) { DataSetDao.LOGGER.error("Could not set most recent version flag for UUID: " + uuid); if (t.isActive()) { t.rollback(); } return false; } }
From source file:com.espirit.moddev.examples.uxbridge.newsdrilldown.jpa.NewsHandler.java
/** * saves or updates a newscategory.// w w w .ja v a 2 s . com * * @param category the category * @return the category with the new id * @throws Exception the exception */ private NewsCategory saveNewsCategory(NewsCategory category) throws Exception { EntityManager em = null; EntityTransaction tx = null; try { em = emf.createEntityManager(); tx = em.getTransaction(); tx.begin(); // try loading the category for the firstspirit id NewsCategory cat = getNewsCategory(category.getFs_id(), category.getLanguage(), em); if (cat != null) { List<NewsMetaCategory> metaCats = category.getMetaCategories(); // the already persistent categories List<NewsMetaCategory> original_metaCats = cat.getMetaCategories(); // update existing category cat.setMetaCategories(new ArrayList<NewsMetaCategory>()); for (NewsMetaCategory metaCat : metaCats) { metaCat = saveNewsMetaCategory(metaCat, em); cat.getMetaCategories().add(metaCat); original_metaCats.remove(metaCat); } for (NewsMetaCategory mc : original_metaCats) { mc.setLastmodified(category.getLastmodified()); } cat.getMetaCategories().addAll(original_metaCats); cat.setFs_id(category.getFs_id()); cat.setLanguage(category.getLanguage()); cat.setName(category.getName()); cat.setVersion(category.getVersion()); cat.setLastmodified(category.getLastmodified()); // update category = em.merge(cat); } else { updateMetaCategories(category, em); // save to db em.persist(category); } tx.commit(); return category; } catch (Exception e) { if (tx != null && tx.isActive()) { tx.setRollbackOnly(); } logger.error("", e); 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.UDDICustodyTransferImpl.java
@SuppressWarnings("unchecked") public void discardTransferToken(DiscardTransferToken body) throws DispositionReportFaultMessage { long startTime = System.currentTimeMillis(); EntityManager em = PersistenceManager.getEntityManager(); EntityTransaction tx = em.getTransaction(); try {/*from w ww .jav a2s . c o m*/ tx.begin(); UddiEntityPublisher publisher = this.getEntityPublisher(em, body.getAuthInfo()); new ValidateCustodyTransfer(publisher).validateDiscardTransferToken(em, body); org.uddi.custody_v3.TransferToken apiTransferToken = body.getTransferToken(); if (apiTransferToken != null) { String transferTokenId = new String(apiTransferToken.getOpaqueToken()); org.apache.juddi.model.TransferToken modelTransferToken = em .find(org.apache.juddi.model.TransferToken.class, transferTokenId); if (modelTransferToken != null) em.remove(modelTransferToken); } KeyBag keyBag = body.getKeyBag(); if (keyBag != null) { List<String> keyList = keyBag.getKey(); Vector<DynamicQuery.Parameter> params = new Vector<DynamicQuery.Parameter>(0); for (String key : keyList) { // Creating parameters for key-checking query DynamicQuery.Parameter param = new DynamicQuery.Parameter("UPPER(ttk.entityKey)", key.toUpperCase(), DynamicQuery.PREDICATE_EQUALS); params.add(param); } // Find the associated transfer tokens and remove them. DynamicQuery getTokensQry = new DynamicQuery(); getTokensQry.append("select distinct ttk.transferToken from TransferTokenKey ttk").pad(); getTokensQry.WHERE().pad().appendGroupedOr(params.toArray(new DynamicQuery.Parameter[0])); Query qry = getTokensQry.buildJPAQuery(em); List<org.apache.juddi.model.TransferToken> tokensToDelete = qry.getResultList(); if (tokensToDelete != null && tokensToDelete.size() > 0) { for (org.apache.juddi.model.TransferToken tt : tokensToDelete) em.remove(tt); } } tx.commit(); long procTime = System.currentTimeMillis() - startTime; serviceCounter.update(CustodyTransferQuery.DISCARD_TRANSFERTOKEN, QueryStatus.SUCCESS, procTime); } finally { if (tx.isActive()) { tx.rollback(); } em.close(); } }
From source file:com.espirit.moddev.examples.uxbridge.newsdrilldown.jpa.NewsHandler.java
/** * Deletes every item older than the creationTime of the UXBEntity. * * @param entity Entity containing the expireDate (= createTime of the entity) *///www .j av a 2s . com public void cleanup(UXBEntity entity) throws Exception { EntityManager em = null; EntityTransaction tx = null; try { em = emf.createEntityManager(); tx = em.getTransaction(); tx.begin(); // Remove old newsdrilldown Query query = em.createQuery(new StringBuilder() .append("SELECT x FROM news x WHERE x.lastmodified<:expiredate ").toString()); query.setParameter("expiredate", entity.getCreateTime()); if (!query.getResultList().isEmpty()) { for (Object obj : query.getResultList()) { News art = (News) obj; em.remove(art); } } // Remove old newsCategories query = em.createQuery(new StringBuilder() .append("SELECT x FROM category x WHERE x.lastmodified<:expiredate ").toString()); query.setParameter("expiredate", entity.getCreateTime()); if (!query.getResultList().isEmpty()) { for (Object obj : query.getResultList()) { NewsCategory art = (NewsCategory) obj; em.remove(art); } } // Remove old newsMetaCategories query = em.createQuery(new StringBuilder() .append("SELECT x FROM metaCategory x WHERE x.lastmodified<:expiredate ").toString()); query.setParameter("expiredate", entity.getCreateTime()); if (!query.getResultList().isEmpty()) { for (Object obj : query.getResultList()) { NewsMetaCategory art = (NewsMetaCategory) obj; em.remove(art); } } tx.commit(); } catch (Exception e) { if (tx != null && tx.isActive()) { tx.setRollbackOnly(); } logger.error("Failure while deleting from the database", e); throw e; } finally { if (tx != null && tx.isActive()) { if (tx.getRollbackOnly()) { tx.rollback(); } } if (em != null) { em.close(); } } }