List of usage examples for javax.persistence EntityTransaction isActive
public boolean isActive();
From source file:org.opencastproject.messages.MailService.java
public void deleteMessageSignature(Long id) throws MailServiceException, NotFoundException { EntityManager em = null;/*from w w w .j a v a2 s . c o m*/ EntityTransaction tx = null; try { em = emf.createEntityManager(); tx = em.getTransaction(); tx.begin(); String orgId = securityService.getOrganization().getId(); Option<MessageSignatureDto> signatureOption = findMessageSignatureById(id, orgId, em); if (signatureOption.isNone()) throw new NotFoundException(); em.remove(signatureOption.get()); tx.commit(); } catch (NotFoundException e) { throw e; } catch (Exception e) { logger.error("Could not delete message signature '{}': {}", id, e.getMessage()); if (tx.isActive()) tx.rollback(); throw new MailServiceException(e); } finally { if (em != null) em.close(); } }
From source file:org.apache.juddi.api.impl.JUDDIApiImpl.java
/** * Retrieves all publisher from the persistence layer. This method is * specific to jUDDI. Administrative privilege required. Use caution when calling, result * set is not bound. If there are many publishers, it is possible to have a * result set that is too large/* w w w . ja va 2 s .c o m*/ * @param body * @return PublisherDetail * @throws DispositionReportFaultMessage * @throws RemoteException */ @SuppressWarnings("unchecked") public PublisherDetail getAllPublisherDetail(GetAllPublisherDetail body) throws DispositionReportFaultMessage, RemoteException { new ValidatePublisher(null).validateGetAllPublisherDetail(body); EntityManager em = PersistenceManager.getEntityManager(); EntityTransaction tx = em.getTransaction(); try { tx.begin(); this.getEntityPublisher(em, body.getAuthInfo()); PublisherDetail result = new PublisherDetail(); Query query = em.createQuery("SELECT p from Publisher as p"); List<Publisher> modelPublisherList = query.getResultList(); for (Publisher modelPublisher : modelPublisherList) { org.apache.juddi.api_v3.Publisher apiPublisher = new org.apache.juddi.api_v3.Publisher(); MappingModelToApi.mapPublisher(modelPublisher, apiPublisher); result.getPublisher().add(apiPublisher); } tx.commit(); return result; } finally { if (tx.isActive()) { tx.rollback(); } em.close(); } }
From source file:org.apache.juddi.api.impl.UDDIInquiryImpl.java
public RelatedBusinessesList findRelatedBusinesses(FindRelatedBusinesses body) throws DispositionReportFaultMessage { long startTime = System.currentTimeMillis(); try {//from w w w. ja v a 2 s .c om new ValidateInquiry(null).validateFindRelatedBusinesses(body, false); } catch (DispositionReportFaultMessage drfm) { long procTime = System.currentTimeMillis() - startTime; serviceCounter.update(InquiryQuery.FIND_RELATEDBUSINESSES, QueryStatus.FAILED, procTime); throw drfm; } EntityManager em = PersistenceManager.getEntityManager(); EntityTransaction tx = em.getTransaction(); try { tx.begin(); if (isAuthenticated()) this.getEntityPublisher(em, body.getAuthInfo()); // TODO: findQualifiers aren't really used for this call, except maybe for sorting. Sorting must be done in Java due to the retrieval method used. Right now // no sorting is performed. org.apache.juddi.query.util.FindQualifiers findQualifiers = new org.apache.juddi.query.util.FindQualifiers(); findQualifiers.mapApiFindQualifiers(body.getFindQualifiers()); RelatedBusinessesList result = InquiryHelper.getRelatedBusinessesList(body, em); tx.rollback(); long procTime = System.currentTimeMillis() - startTime; serviceCounter.update(InquiryQuery.FIND_RELATEDBUSINESSES, QueryStatus.SUCCESS, procTime); return result; } finally { if (tx.isActive()) { tx.rollback(); } em.close(); } }
From source file:org.opencastproject.messages.MailService.java
public EmailConfiguration updateEmailConfiguration(EmailConfiguration emailConfiguration) throws MailServiceException { EntityManager em = null;/* w w w.j av a 2s. c o m*/ EntityTransaction tx = null; try { em = emf.createEntityManager(); tx = em.getTransaction(); tx.begin(); String orgId = securityService.getOrganization().getId(); EmailConfigurationDto emailConfig = mergeEmailConfiguration(emailConfiguration, orgId, em); tx.commit(); EmailConfiguration updatedEmailConfiguration = emailConfig.toEmailConfiguration(); updateSmtpConfiguration(updatedEmailConfiguration); return updatedEmailConfiguration; } catch (Exception e) { logger.error("Could not update email configuration '{}': {}", emailConfiguration, e.getMessage()); if (tx.isActive()) tx.rollback(); throw new MailServiceException(e); } finally { if (em != null) em.close(); } }
From source file:org.apache.juddi.api.impl.UDDIPublicationImplExt.java
public BusinessDetail saveBusinessFudge(SaveBusiness body, String nodeID) throws DispositionReportFaultMessage { if (!body.getBusinessEntity().isEmpty()) { log.debug("Inbound save business Fudger request for key " + body.getBusinessEntity().get(0).getBusinessKey()); }//from w w w. j av a2 s . c o m EntityManager em = PersistenceManager.getEntityManager(); EntityTransaction tx = em.getTransaction(); try { tx.begin(); UddiEntityPublisher publisher = this.getEntityPublisher(em, body.getAuthInfo()); ValidatePublish validator = new ValidatePublish(publisher); validator.validateSaveBusiness(em, body, null); BusinessDetail result = new BusinessDetail(); List<org.uddi.api_v3.BusinessEntity> apiBusinessEntityList = body.getBusinessEntity(); for (org.uddi.api_v3.BusinessEntity apiBusinessEntity : apiBusinessEntityList) { org.apache.juddi.model.BusinessEntity modelBusinessEntity = new org.apache.juddi.model.BusinessEntity(); MappingApiToModel.mapBusinessEntity(apiBusinessEntity, modelBusinessEntity); nodeId = nodeID; setOperationalInfo(em, modelBusinessEntity, publisher); em.persist(modelBusinessEntity); result.getBusinessEntity().add(apiBusinessEntity); } //check how many business this publisher owns. validator.validateSaveBusinessMax(em); tx.commit(); return result; } catch (DispositionReportFaultMessage drfm) { throw drfm; } finally { if (tx.isActive()) { tx.rollback(); } em.close(); } }
From source file:org.opencastproject.search.impl.persistence.SearchServiceDatabaseImpl.java
private void populateSeriesData() throws SearchServiceDatabaseException { EntityManager em = null;/*from w ww . ja va2s . c o m*/ EntityTransaction tx = null; try { em = emf.createEntityManager(); tx = em.getTransaction(); tx.begin(); TypedQuery<SearchEntity> q = (TypedQuery<SearchEntity>) em.createNamedQuery("Search.getNoSeries"); List<SearchEntity> seriesList = q.getResultList(); for (SearchEntity series : seriesList) { String mpSeriesId = MediaPackageParser.getFromXml(series.getMediaPackageXML()).getSeries(); if (StringUtils.isNotBlank(mpSeriesId) && !mpSeriesId.equals(series.getSeriesId())) { logger.info("Fixing missing series ID for episode {}, series is {}", series.getMediaPackageId(), mpSeriesId); series.setSeriesId(mpSeriesId); em.merge(series); } } 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.eclipse.smila.connectivity.deltaindexing.jpa.impl.DeltaIndexingManagerImpl.java
/** * {@inheritDoc}/*from w ww .j a v a 2 s . com*/ * * @see org.eclipse.smila.connectivity.deltaindexing.DeltaIndexingManager#unlockDatasource(String) */ @Override public void unlockDatasource(final String dataSourceID) throws DeltaIndexingException { _lock.readLock().lock(); try { final EntityManager em = createEntityManager(); final EntityTransaction transaction = em.getTransaction(); try { transaction.begin(); final Query query = em.createNamedQuery(DataSourceDao.NAMED_QUERY_KILL_SESSION); query.setParameter(DeltaIndexingDao.NAMED_QUERY_PARAM_SOURCE, dataSourceID); query.executeUpdate(); transaction.commit(); if (_log.isInfoEnabled()) { _log.info("removed delta indexing sessions and unlocked data source " + dataSourceID); } } catch (final Exception e) { if (transaction.isActive()) { transaction.rollback(); } throw new DeltaIndexingException("error unlocking delta indexing data source " + dataSourceID, e); } finally { closeEntityManager(em); } } finally { _lock.readLock().unlock(); } }
From source file:org.opencastproject.themes.persistence.ThemesServiceDatabaseImpl.java
@Override public Theme updateTheme(Theme theme) throws ThemesServiceDatabaseException { EntityManager em = null;// w w w. j a v a2s . c o m EntityTransaction tx = null; try { em = emf.createEntityManager(); tx = em.getTransaction(); tx.begin(); ThemeDto themeDto = null; if (theme.getId().isSome()) themeDto = getThemeDto(theme.getId().get(), em); if (themeDto == null) { // no theme stored, create new entity themeDto = new ThemeDto(); themeDto.setOrganization(securityService.getOrganization().getId()); updateTheme(theme, themeDto); em.persist(themeDto); } else { updateTheme(theme, themeDto); em.merge(themeDto); } tx.commit(); theme = themeDto.toTheme(userDirectoryService); messageSender.sendObjectMessage(ThemeItem.THEME_QUEUE, MessageSender.DestinationType.Queue, ThemeItem.update(toSerializableTheme(theme))); return theme; } catch (Exception e) { logger.error("Could not update theme {}: {}", theme, ExceptionUtils.getStackTrace(e)); if (tx.isActive()) { tx.rollback(); } throw new ThemesServiceDatabaseException(e); } finally { if (em != null) { em.close(); } } }
From source file:com.eucalyptus.images.Images.java
public static ImageInfo createFromDeviceMapping(final UserFullName userFullName, final String imageName, final String imageDescription, final ImageMetadata.Platform platform, String eki, String eri, final String rootDeviceName, final List<BlockDeviceMappingItemType> blockDeviceMappings) throws EucalyptusCloudException { final ImageMetadata.Architecture imageArch = ImageMetadata.Architecture.x86_64;//TODO:GRZE:OMGFIXME: track parent vol info; needed here final ImageMetadata.Platform imagePlatform = platform; if (ImageMetadata.Platform.windows.equals(imagePlatform)) { eki = null;/*w w w.j a va2s .c o m*/ eri = null; } // Block device mappings have been verified before control gets here. // If anything has changed with regard to the snapshot state, it will be caught while data structures for the image. final BlockDeviceMappingItemType rootBlockDevice = Iterables.find(blockDeviceMappings, findEbsRoot(rootDeviceName), null); if (rootBlockDevice == null) { throw new EucalyptusCloudException( "Failed to create image, root device mapping not found: " + rootDeviceName); } final String snapshotId = ResourceIdentifiers.tryNormalize() .apply(rootBlockDevice.getEbs().getSnapshotId()); Snapshot snap; try { snap = Transactions.one(Snapshot.named(userFullName.asAccountFullName(), snapshotId), RestrictedTypes.filterPrivileged(), Functions.<Snapshot>identity()); } catch (NoSuchElementException ex) { throw new EucalyptusCloudException("Failed to create image from specified block device mapping: " + rootBlockDevice + " because of: Snapshot not found " + snapshotId); } catch (TransactionExecutionException ex) { throw new EucalyptusCloudException("Failed to create image from specified block device mapping: " + rootBlockDevice + " because of: " + ex.getMessage()); } catch (ExecutionException ex) { LOG.error(ex, ex); throw new EucalyptusCloudException("Failed to create image from specified block device mapping: " + rootBlockDevice + " because of: " + ex.getMessage()); } final Integer suppliedVolumeSize = rootBlockDevice.getEbs().getVolumeSize() != null ? rootBlockDevice.getEbs().getVolumeSize() : snap.getVolumeSize(); final Long imageSizeBytes = suppliedVolumeSize * 1024l * 1024l * 1024l; final Boolean targetDeleteOnTermination = Boolean.TRUE .equals(rootBlockDevice.getEbs().getDeleteOnTermination()); final String imageId = ResourceIdentifiers.generateString(ImageMetadata.Type.machine.getTypePrefix()); final boolean mapRoot = DEFAULT_PARTITIONED_ROOT_DEVICE.equals(rootDeviceName); BlockStorageImageInfo ret = new BlockStorageImageInfo(userFullName, imageId, imageName, imageDescription, imageSizeBytes, imageArch, imagePlatform, eki, eri, snap.getDisplayName(), targetDeleteOnTermination, mapRoot ? DEFAULT_ROOT_DEVICE : rootDeviceName); final EntityTransaction tx = Entities.get(BlockStorageImageInfo.class); try { ret = Entities.merge(ret); Iterables.addAll(ret.getDeviceMappings(), Iterables.transform(blockDeviceMappings, Images.deviceMappingGenerator(ret, suppliedVolumeSize, mapRoot ? Collections.singletonMap(DEFAULT_PARTITIONED_ROOT_DEVICE, DEFAULT_ROOT_DEVICE) : Collections.<String, String>emptyMap()))); ret.setImageFormat(ImageMetadata.ImageFormat.fulldisk.toString()); ret.setState(ImageMetadata.State.available); tx.commit(); LOG.info("Registering image pk=" + ret.getDisplayName() + " ownerId=" + userFullName); } catch (Exception e) { throw new EucalyptusCloudException( "Failed to register image using snapshot: " + snapshotId + " because of: " + e.getMessage(), e); } finally { if (tx.isActive()) tx.rollback(); } return ret; }
From source file:org.apache.juddi.v3.auth.HTTPHeaderAuthenticator.java
@Override public UddiEntityPublisher identify(String notusedauthtoken, String notusedusername, WebServiceContext ctx) throws AuthenticationException, FatalErrorException { int MaxBindingsPerService = -1; int MaxServicesPerBusiness = -1; int MaxTmodels = -1; int MaxBusinesses = -1; String http_header_name = null; try {//ww w.ja va 2s.co m http_header_name = AppConfig.getConfiguration() .getString(Property.JUDDI_AUTHENTICATOR_HTTP_HEADER_NAME); MaxBindingsPerService = AppConfig.getConfiguration().getInt(Property.JUDDI_MAX_BINDINGS_PER_SERVICE, -1); MaxServicesPerBusiness = AppConfig.getConfiguration().getInt(Property.JUDDI_MAX_SERVICES_PER_BUSINESS, -1); MaxTmodels = AppConfig.getConfiguration().getInt(Property.JUDDI_MAX_TMODELS_PER_PUBLISHER, -1); MaxBusinesses = AppConfig.getConfiguration().getInt(Property.JUDDI_MAX_BUSINESSES_PER_PUBLISHER, -1); } catch (Exception ex) { MaxBindingsPerService = -1; MaxServicesPerBusiness = -1; MaxTmodels = -1; MaxBusinesses = -1; log.error("config exception! ", ex); } if (http_header_name == null) { throw new UnknownUserException(new ErrorMessage("errors.auth.NoPublisher", "misconfiguration!")); } EntityManager em = PersistenceManager.getEntityManager(); EntityTransaction tx = em.getTransaction(); try { String user = null; MessageContext mc = ctx.getMessageContext(); HttpServletRequest req = null; if (mc != null) { req = (HttpServletRequest) mc.get(MessageContext.SERVLET_REQUEST); user = req.getHeader(http_header_name); } if (user == null || user.length() == 0) { throw new UnknownUserException(new ErrorMessage("errors.auth.NoPublisher")); } tx.begin(); Publisher publisher = em.find(Publisher.class, user); if (publisher == null) { log.warn("Publisher \"" + user + "\" was not found in the database, adding the publisher in on the fly."); publisher = new Publisher(); publisher.setAuthorizedName(user); publisher.setIsAdmin("false"); publisher.setIsEnabled("true"); publisher.setMaxBindingsPerService(MaxBindingsPerService); publisher.setMaxBusinesses(MaxBusinesses); publisher.setMaxServicesPerBusiness(MaxServicesPerBusiness); publisher.setMaxTmodels(MaxTmodels); publisher.setPublisherName("Unknown"); em.persist(publisher); tx.commit(); } return publisher; } finally { if (tx.isActive()) { tx.rollback(); } em.close(); } }