List of usage examples for javax.persistence EntityTransaction commit
public void commit();
From source file:com.eucalyptus.blockstorage.BlockStorageController.java
public CreateStorageSnapshotResponseType CreateStorageSnapshot(CreateStorageSnapshotType request) throws EucalyptusCloudException { CreateStorageSnapshotResponseType reply = (CreateStorageSnapshotResponseType) request.getReply(); StorageProperties.updateWalrusUrl(); if (!StorageProperties.enableSnapshots) { LOG.error("Snapshots have been disabled. Please check connection to ObjectStorage."); return reply; }//from w w w .j a va 2 s .co m String volumeId = request.getVolumeId(); LOG.info("Processing CreateStorageSnapshot request for volume " + volumeId); String snapshotId = request.getSnapshotId(); EntityTransaction dbTrans = Entities.get(VolumeInfo.class); VolumeInfo sourceVolumeInfo = null; try { VolumeInfo volumeInfo = new VolumeInfo(volumeId); sourceVolumeInfo = Entities.uniqueResult(volumeInfo); dbTrans.commit(); } catch (NoSuchElementException e) { LOG.debug("Volume " + volumeId + " not found in db"); throw new NoSuchVolumeException(volumeId); } catch (final Throwable e) { LOG.warn("Volume " + volumeId + " error getting info from db. May not exist. " + e.getMessage()); throw new EucalyptusCloudException("Could not get volume information for volume " + volumeId, e); } finally { if (dbTrans.isActive()) { dbTrans.rollback(); } dbTrans = null; } if (sourceVolumeInfo == null) { //Another check to be sure that we have the source volume throw new NoSuchVolumeException(volumeId); } else { //check status if (!sourceVolumeInfo.getStatus().equals(StorageProperties.Status.available.toString())) { throw new VolumeNotReadyException(volumeId); } else { //create snapshot if (StorageProperties.shouldEnforceUsageLimits) { int maxSize = -1; try { maxSize = BlockStorageGlobalConfiguration.getInstance() .getGlobal_total_snapshot_size_limit_gb(); } catch (Exception e) { LOG.error("Could not determine max global snapshot limit. Aborting snapshot creation", e); throw new EucalyptusCloudException("Total size limit not found.", e); } if (maxSize <= 0) { LOG.warn("Total snapshot size limit is less than or equal to 0"); throw new EucalyptusCloudException("Total snapshot size limit is less than or equal to 0"); } if (totalSnapshotSizeLimitExceeded(snapshotId, sourceVolumeInfo.getSize(), maxSize)) { LOG.info("Snapshot " + snapshotId + " exceeds total snapshot size limit of " + maxSize + "GB"); throw new SnapshotTooLargeException(snapshotId, maxSize); } } Snapshotter snapshotter = null; SnapshotInfo snapshotInfo = new SnapshotInfo(snapshotId); EntityTransaction snapTrans = Entities.get(SnapshotInfo.class); Date startTime = new Date(); try { snapshotInfo.setUserName(sourceVolumeInfo.getUserName()); snapshotInfo.setVolumeId(volumeId); snapshotInfo.setStartTime(startTime); snapshotInfo.setProgress("0"); snapshotInfo.setSizeGb(sourceVolumeInfo.getSize()); snapshotInfo.setStatus(StorageProperties.Status.creating.toString()); /* Change to support sync snap consistency point set on CLC round-trip */ /* * Always do this operation. On backends that don't support it they will * return null. In that case it is effectively a no-op and we continue normal * async snapshot. * * If the snap point is set, then we update the DB properly. */ String snapPointId = null; try { //This will be a no-op if the backend doesn't support it. Will return null. snapPointId = blockManager.createSnapshotPoint(volumeId, snapshotId); if (snapPointId == null) { LOG.debug("Synchronous snap point not supported for this backend. Cleanly skipped."); } else { snapshotInfo.setSnapPointId(snapPointId); } //Do a commit here because the snapshotter expects to find db entry. snapshotInfo.setStatus(StorageProperties.Status.creating.toString()); Context ctx = null; try { ctx = Contexts.lookup(request.getCorrelationId()); if (!ctx.getChannel().isOpen()) { throw new NoSuchContextException("Channel is closed"); } } catch (NoSuchContextException e) { if (snapPointId != null) { //Other end hung up, mark this as failed since this is a sync operation throw new EucalyptusCloudException("Channel closed, aborting snapshot."); } } } catch (EucalyptusCloudException e) { //If the snapshot was done but took too long then delete the snap and fail the op. try { blockManager.deleteSnapshotPoint(volumeId, snapshotId, snapPointId); } catch (Exception ex) { LOG.error("Snapshot " + snapshotId + " exception on snap point cleanup after failure: " + e.getMessage()); } LOG.error("Snapshot " + snapshotId + " failed to create snap point successfully: " + e.getMessage()); throw e; } finally { Entities.persist(snapshotInfo); } /* Resume old code path and finish the snapshot process if already started */ //snapshot asynchronously snapshotter = new Snapshotter(volumeId, snapshotId, snapPointId); reply.setSnapshotId(snapshotId); reply.setVolumeId(volumeId); reply.setStartTime( DateUtils.format(startTime.getTime(), DateUtils.ISO8601_DATETIME_PATTERN) + ".000Z"); reply.setProgress(snapshotInfo.getProgress()); } catch (EucalyptusCloudException cloudEx) { snapshotInfo.setStatus(StorageProperties.Status.failed.toString()); LOG.error("Snapshot " + snapshotId + " creation failed with exception ", cloudEx); throw cloudEx; } catch (final Throwable e) { snapshotInfo.setStatus(StorageProperties.Status.failed.toString()); LOG.error("Snapshot " + snapshotId + " Error committing state update to failed", e); throw new EucalyptusCloudException( "Snapshot " + snapshotId + " unexpected throwable exception caught", e); } finally { if (snapTrans.isActive()) { snapTrans.commit(); } snapTrans = null; } reply.setStatus(snapshotInfo.getStatus()); if (snapshotter != null) { // Kick off the snapshotter task after persisting snapshot to database snapshotService.add(snapshotter); } } } return reply; }
From source file:com.sixsq.slipstream.run.RunNodeResource.java
private void deleteNodeInstancesInTransaction(Representation entity) throws Exception { EntityManager em = PersistenceUtil.createEntityManager(); EntityTransaction transaction = em.getTransaction(); Run run = Run.loadFromUuid(getUuid(), em); try {//from w w w .j ava 2 s. c o m Form form = new Form(entity); boolean deleteOnly = "true".equals(form.getFirstValue(DELETE_INSTANCE_IDS_ONLY_FORM_PARAM, "").trim()) ? true : false; if (!deleteOnly) { validateRun(run); } transaction.begin(); String ids = form.getFirstValue(INSTANCE_IDS_REMOVE_FORM_PARAM, ""); if (ids.isEmpty()) { throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, "Provide list of node instance IDs to be removed from the Run."); } else { String cloudServiceName = ""; try { cloudServiceName = run.getCloudServiceNameForNode(nodename); } catch (NullPointerException ex) { throwClientBadRequest("Invalid nodename: " + nodename); } List<String> instanceIds = Arrays.asList(ids.split("\\s*,\\s*")); for (String _id : instanceIds) { String instanceName = ""; try { instanceName = getNodeInstanceName(Integer.parseInt(_id)); } catch (NumberFormatException ex) { throwClientBadRequest("Invalid instance name: " + _id); } setRemovingNodeInstance(run, instanceName); run.removeNodeInstanceName(instanceName, cloudServiceName); } run.postEventScaleDown(nodename, instanceIds); // update instance ids removeNodeInstanceIndices(run, instanceIds); decrementNodeMultiplicityOnRun(instanceIds.size(), run); } if (!deleteOnly) { StateMachine.createStateMachine(run).tryAdvanceToProvisionning(); } transaction.commit(); } catch (Exception ex) { if (transaction.isActive()) { transaction.rollback(); } throw ex; } finally { em.close(); } getResponse().setStatus(Status.SUCCESS_NO_CONTENT); }
From source file:com.espirit.moddev.examples.uxbridge.newsdrilldown.jpa.NewsHandler.java
/** * Deletes a newsdrilldown from the db./*from w w w . j a va 2 s .c o m*/ * * @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: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"); }/* www . ja v a 2 s . c om*/ 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.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 w w w . j a v a2 s.c om*/ 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.search.impl.persistence.SearchServiceDatabaseImpl.java
/** * {@inheritDoc}//from w w w . jav a2 s . co m * * @see org.opencastproject.search.impl.persistence.SearchServiceDatabase#storeMediaPackage(MediaPackage, * AccessControlList, Date) */ @Override public void storeMediaPackage(MediaPackage mediaPackage, AccessControlList acl, Date now) throws SearchServiceDatabaseException, UnauthorizedException { String mediaPackageXML = MediaPackageParser.getAsXml(mediaPackage); String mediaPackageId = mediaPackage.getIdentifier().toString(); EntityManager em = null; EntityTransaction tx = null; try { em = emf.createEntityManager(); tx = em.getTransaction(); tx.begin(); SearchEntity entity = getSearchEntity(mediaPackageId, em); if (entity == null) { // Create new search entity SearchEntity searchEntity = new SearchEntity(); searchEntity.setOrganization(securityService.getOrganization().getId()); searchEntity.setMediaPackageId(mediaPackageId); searchEntity.setMediaPackageXML(mediaPackageXML); searchEntity.setAccessControl(AccessControlParser.toXml(acl)); searchEntity.setModificationDate(now); searchEntity.setSeriesId(mediaPackage.getSeries()); em.persist(searchEntity); } else { // Ensure this user is allowed to update this media package String accessControlXml = entity.getAccessControl(); if (accessControlXml != null) { AccessControlList accessList = AccessControlParser.parseAcl(accessControlXml); User currentUser = securityService.getUser(); Organization currentOrg = securityService.getOrganization(); if (!AccessControlUtil.isAuthorized(accessList, currentUser, currentOrg, WRITE.toString())) { throw new UnauthorizedException( currentUser + " is not authorized to update media package " + mediaPackageId); } } entity.setOrganization(securityService.getOrganization().getId()); entity.setMediaPackageId(mediaPackageId); entity.setMediaPackageXML(mediaPackageXML); entity.setAccessControl(AccessControlParser.toXml(acl)); entity.setModificationDate(now); entity.setSeriesId(mediaPackage.getSeries()); em.merge(entity); } tx.commit(); } catch (Exception e) { logger.error("Could not update media package: {}", e.getMessage()); if (tx.isActive()) { tx.rollback(); } throw new SearchServiceDatabaseException(e); } finally { if (em != null) em.close(); } }
From source file:org.apache.juddi.validation.ValidatePublish.java
/** * throws if it doesn't exist, returns it if it does * * @param tmodelKey/*from w w w .j av a2 s . c o m*/ * @return null, or a TModel object * @throws ValueNotAllowedException * @since 3.3 */ private TModel verifyTModelKeyExists(String tmodelKey) throws ValueNotAllowedException, DispositionReportFaultMessage { TModel api = null; EntityManager em = PersistenceManager.getEntityManager(); boolean found = false; if (em == null) { log.warn(new ErrorMessage("errors.tmodel.ReferentialIntegrityNullEM")); } else { Tmodel modelTModel = null; { EntityTransaction tx = em.getTransaction(); try { tx.begin(); modelTModel = em.find(org.apache.juddi.model.Tmodel.class, tmodelKey); if (modelTModel != null) { found = true; api = new TModel(); MappingModelToApi.mapTModel(modelTModel, api); } tx.commit(); } finally { if (tx.isActive()) { tx.rollback(); } em.close(); } } } if (!found) { throw new ValueNotAllowedException( new ErrorMessage("errors.tmodel.ReferencedKeyDoesNotExist", tmodelKey)); } return api; }
From source file:info.dolezel.jarss.rest.v1.FeedsService.java
@POST @Consumes(MediaType.APPLICATION_JSON)//from w w w . j av a 2 s . co 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.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 ww w . j a v a 2 s . c om*/ 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:org.opencastproject.serviceregistry.impl.ServiceRegistryJpaImpl.java
/** * Internal method to update a job, throwing unwrapped JPA exceptions. * /* w w w . j a va 2s . c om*/ * @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; } }