List of usage examples for javax.persistence EntityTransaction isActive
public boolean isActive();
From source file:org.apache.juddi.validation.ValidatePublish.java
/** * throws if it doesn't exist, returns it if it does * * @param tmodelKey/*from w ww. j a va 2 s. co 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:org.opencastproject.search.impl.persistence.SearchServiceDatabaseImpl.java
/** * {@inheritDoc}//from ww w.j a v a 2 s .c om * * @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.api.impl.UDDIPublicationImpl.java
public ServiceDetail saveService(SaveService body) throws DispositionReportFaultMessage { long startTime = System.currentTimeMillis(); EntityManager em = PersistenceManager.getEntityManager(); EntityTransaction tx = em.getTransaction(); try {//ww w . j ava2 s.c om 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: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 ww . j av a 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.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 w w w.j av a 2 s .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:info.dolezel.jarss.rest.v1.FeedsService.java
@POST @Consumes(MediaType.APPLICATION_JSON)// w ww. jav 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.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.jav 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. * //www. j av a2s . c o 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/*from w ww . jav a 2s . 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; }
From source file:org.opencastproject.serviceregistry.impl.ServiceRegistryJpaImpl.java
/** * {@inheritDoc}/*from w ww . j a va 2 s .com*/ * * @see org.opencastproject.serviceregistry.api.ServiceRegistry#setMaintenanceStatus(java.lang.String, boolean) */ @Override public void setMaintenanceStatus(String baseUrl, boolean maintenance) throws NotFoundException { EntityManager em = null; EntityTransaction tx = null; try { em = emf.createEntityManager(); tx = em.getTransaction(); tx.begin(); HostRegistrationJpaImpl reg = fetchHostRegistration(em, baseUrl); if (reg == null) { throw new NotFoundException("Can not set maintenance mode on a host that has not been registered"); } reg.setMaintenanceMode(maintenance); em.merge(reg); tx.commit(); hostsStatistics.updateHost(reg); } catch (RollbackException e) { if (tx != null && tx.isActive()) { tx.rollback(); } throw e; } finally { if (em != null) em.close(); } }