List of usage examples for javax.persistence EntityTransaction begin
public void begin();
From source file:org.opencastproject.adminui.usersettings.UserSettingsService.java
/** * Update a user setting that currently exists using its unique id to find it. * @param id The id for the user setting. * @param key The key for the user setting. * @param value The value for the user setting. * @return The updated {@link UserSetting}. * @throws UserSettingsServiceException/* ww w . ja v a 2 s. c o m*/ */ public UserSetting updateUserSetting(long id, String key, String value) throws UserSettingsServiceException { EntityManager em = null; EntityTransaction tx = null; String orgId = ""; String username = ""; logger.debug("Updating user setting id: %d key: %s value: %s", id, key, value); try { em = emf.createEntityManager(); tx = em.getTransaction(); tx.begin(); orgId = securityService.getOrganization().getId(); username = securityService.getUser().getUsername(); UserSettingDto userSettingDto = em.find(UserSettingDto.class, id); em.persist(userSettingDto); userSettingDto.setKey(key); userSettingDto.setValue(value); tx.commit(); return userSettingDto.toUserSetting(); } catch (Exception e) { logger.error("Could not update user setting username '%s' org:'%s' id:'%d' key:'%s' value:'%s':\n%s", username, orgId, id, key, value, ExceptionUtils.getStackTrace(e)); if (tx.isActive()) { tx.rollback(); } throw new UserSettingsServiceException(e); } finally { if (em != null) { em.close(); } } }
From source file:org.opencastproject.search.impl.persistence.SearchServiceDatabaseImpl.java
/** * {@inheritDoc}/* ww w . j a va 2 s . c o m*/ * * @see org.opencastproject.search.impl.persistence.SearchServiceDatabase#getModificationDate(String) */ @Override public Date getModificationDate(String mediaPackageId) throws NotFoundException, SearchServiceDatabaseException { EntityManager em = null; EntityTransaction tx = null; try { em = emf.createEntityManager(); tx = em.getTransaction(); tx.begin(); SearchEntity searchEntity = getSearchEntity(mediaPackageId, em); if (searchEntity == null) throw new NotFoundException("No media package with id=" + mediaPackageId + " exists"); // Ensure this user is allowed to read this media package String accessControlXml = searchEntity.getAccessControl(); if (accessControlXml != null) { AccessControlList acl = AccessControlParser.parseAcl(accessControlXml); User currentUser = securityService.getUser(); Organization currentOrg = securityService.getOrganization(); if (!AccessControlUtil.isAuthorized(acl, currentUser, currentOrg, READ.toString())) throw new UnauthorizedException( currentUser + " is not authorized to read media package " + mediaPackageId); } return searchEntity.getModificationDate(); } catch (NotFoundException e) { throw e; } catch (Exception e) { logger.error("Could not get modification date {}: {}", mediaPackageId, e.getMessage()); if (tx.isActive()) { tx.rollback(); } throw new SearchServiceDatabaseException(e); } finally { if (em != null) em.close(); } }
From source file:org.opencastproject.search.impl.persistence.SearchServiceDatabaseImpl.java
/** * {@inheritDoc}//ww w . j av a 2 s . c om * * @see org.opencastproject.search.impl.persistence.SearchServiceDatabase#getDeletionDate(String) */ @Override public Date getDeletionDate(String mediaPackageId) throws NotFoundException, SearchServiceDatabaseException { EntityManager em = null; EntityTransaction tx = null; try { em = emf.createEntityManager(); tx = em.getTransaction(); tx.begin(); SearchEntity searchEntity = getSearchEntity(mediaPackageId, em); if (searchEntity == null) { throw new NotFoundException("No media package with id=" + mediaPackageId + " exists"); } // Ensure this user is allowed to read this media package String accessControlXml = searchEntity.getAccessControl(); if (accessControlXml != null) { AccessControlList acl = AccessControlParser.parseAcl(accessControlXml); User currentUser = securityService.getUser(); Organization currentOrg = securityService.getOrganization(); if (!AccessControlUtil.isAuthorized(acl, currentUser, currentOrg, READ.toString())) throw new UnauthorizedException( currentUser + " is not authorized to read media package " + mediaPackageId); } return searchEntity.getDeletionDate(); } catch (NotFoundException e) { throw e; } catch (Exception e) { logger.error("Could not get deletion date {}: {}", mediaPackageId, e.getMessage()); if (tx.isActive()) { tx.rollback(); } throw new SearchServiceDatabaseException(e); } finally { if (em != null) em.close(); } }
From source file:org.opencastproject.search.impl.persistence.SearchServiceDatabaseImpl.java
/** * {@inheritDoc}// w w w .j a v a 2s.com * * @see org.opencastproject.search.impl.persistence.SearchServiceDatabase#getOrganizationId(String) */ @Override public String getOrganizationId(String mediaPackageId) throws NotFoundException, SearchServiceDatabaseException { EntityManager em = null; EntityTransaction tx = null; try { em = emf.createEntityManager(); tx = em.getTransaction(); tx.begin(); SearchEntity searchEntity = getSearchEntity(mediaPackageId, em); if (searchEntity == null) throw new NotFoundException("No media package with id=" + mediaPackageId + " exists"); // Ensure this user is allowed to read this media package String accessControlXml = searchEntity.getAccessControl(); if (accessControlXml != null) { AccessControlList acl = AccessControlParser.parseAcl(accessControlXml); User currentUser = securityService.getUser(); Organization currentOrg = securityService.getOrganization(); if (!AccessControlUtil.isAuthorized(acl, currentUser, currentOrg, READ.toString())) throw new UnauthorizedException( currentUser + " is not authorized to read media package " + mediaPackageId); } return searchEntity.getOrganization(); } catch (NotFoundException e) { throw e; } catch (Exception e) { logger.error("Could not get deletion date {}: {}", mediaPackageId, e.getMessage()); if (tx.isActive()) { tx.rollback(); } throw new SearchServiceDatabaseException(e); } finally { if (em != null) em.close(); } }
From source file:org.opencastproject.search.impl.persistence.SearchServiceDatabaseImpl.java
/** * {@inheritDoc}/*from w w w. j a v a 2 s .com*/ * * @see org.opencastproject.search.impl.persistence.SearchServiceDatabase#getMediaPackage(String) */ @Override public MediaPackage getMediaPackage(String mediaPackageId) throws NotFoundException, SearchServiceDatabaseException { EntityManager em = null; EntityTransaction tx = null; try { em = emf.createEntityManager(); tx = em.getTransaction(); tx.begin(); SearchEntity episodeEntity = getSearchEntity(mediaPackageId, em); if (episodeEntity == null) throw new NotFoundException("No episode with id=" + mediaPackageId + " exists"); // Ensure this user is allowed to read this episode String accessControlXml = episodeEntity.getAccessControl(); if (accessControlXml != null) { AccessControlList acl = AccessControlParser.parseAcl(accessControlXml); User currentUser = securityService.getUser(); Organization currentOrg = securityService.getOrganization(); // There are several reasons a user may need to load a episode: to read content, to edit it, or add content if (!AccessControlUtil.isAuthorized(acl, currentUser, currentOrg, READ.toString()) && !AccessControlUtil.isAuthorized(acl, currentUser, currentOrg, CONTRIBUTE.toString()) && !AccessControlUtil.isAuthorized(acl, currentUser, currentOrg, WRITE.toString())) { throw new UnauthorizedException( currentUser + " is not authorized to see episode " + mediaPackageId); } } return MediaPackageParser.getFromXml(episodeEntity.getMediaPackageXML()); } catch (NotFoundException e) { throw e; } catch (Exception e) { logger.error("Could not get episode {} from database: {} ", mediaPackageId, e.getMessage()); if (tx.isActive()) { tx.rollback(); } throw new SearchServiceDatabaseException(e); } finally { if (em != null) em.close(); } }
From source file:org.opencastproject.search.impl.persistence.SearchServiceDatabaseImpl.java
/** * {@inheritDoc}//from ww w.java2s .c o m * * @see org.opencastproject.search.impl.persistence.SearchServiceDatabase#deleteMediaPackage(String, Date) */ @Override public void deleteMediaPackage(String mediaPackageId, Date deletionDate) throws SearchServiceDatabaseException, NotFoundException { EntityManager em = null; EntityTransaction tx = null; try { em = emf.createEntityManager(); tx = em.getTransaction(); tx.begin(); SearchEntity searchEntity = getSearchEntity(mediaPackageId, em); if (searchEntity == null) throw new NotFoundException("No media package with id=" + mediaPackageId + " exists"); // Ensure this user is allowed to delete this episode String accessControlXml = searchEntity.getAccessControl(); if (accessControlXml != null) { AccessControlList acl = AccessControlParser.parseAcl(accessControlXml); User currentUser = securityService.getUser(); Organization currentOrg = securityService.getOrganization(); if (!AccessControlUtil.isAuthorized(acl, currentUser, currentOrg, WRITE.toString())) throw new UnauthorizedException( currentUser + " is not authorized to delete media package " + mediaPackageId); searchEntity.setDeletionDate(deletionDate); em.merge(searchEntity); } tx.commit(); } catch (NotFoundException e) { throw e; } catch (Exception e) { logger.error("Could not delete episode {}: {}", mediaPackageId, e.getMessage()); if (tx.isActive()) { tx.rollback(); } throw new SearchServiceDatabaseException(e); } finally { if (em != null) em.close(); } }
From source file:org.opencastproject.search.impl.persistence.SearchServiceDatabaseImpl.java
/** * {@inheritDoc}//from w w 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.opencastproject.userdirectory.JpaGroupRoleProvider.java
/** * Adds or updates a group to the persistence. * * @param group/*from w w w . j av a2 s. co m*/ * the group to add */ public void addGroup(final JpaGroup group) { Set<JpaRole> roles = UserDirectoryPersistenceUtil.saveRoles(group.getRoles(), emf); JpaOrganization organization = UserDirectoryPersistenceUtil.saveOrganization(group.getOrganization(), emf); JpaGroup jpaGroup = new JpaGroup(group.getGroupId(), organization, group.getName(), group.getDescription(), roles, group.getMembers()); // Then save the jpaGroup EntityManager em = null; EntityTransaction tx = null; try { em = emf.createEntityManager(); tx = em.getTransaction(); tx.begin(); JpaGroup foundGroup = UserDirectoryPersistenceUtil.findGroup(jpaGroup.getGroupId(), jpaGroup.getOrganization().getId(), emf); if (foundGroup == null) { em.persist(jpaGroup); } else { foundGroup.setName(jpaGroup.getName()); foundGroup.setDescription(jpaGroup.getDescription()); foundGroup.setMembers(jpaGroup.getMembers()); foundGroup.setRoles(roles); em.merge(foundGroup); } tx.commit(); messageSender.sendObjectMessage(GroupItem.GROUP_QUEUE, MessageSender.DestinationType.Queue, GroupItem.update(JaxbGroup.fromGroup(jpaGroup))); } finally { if (tx.isActive()) { tx.rollback(); } if (em != null) em.close(); } }
From source file:nl.b3p.kaartenbalie.service.servlet.CallWMSServlet.java
/** Processes the incoming request and calls the various methods to create the right output stream. * * @param request servlet request//from w ww .j a v a 2 s .c om * @param response servlet response * * @throws ServletException * @throws IOException */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { long startTime = System.currentTimeMillis(); StringBuffer baseUrl = createBaseUrl(request, true); if (CAPABILITIES_DTD == null) { CAPABILITIES_DTD = baseUrl.toString() + "/dtd/capabilities_1_1_1.dtd"; } if (EXCEPTION_DTD == null) { EXCEPTION_DTD = baseUrl.toString() + "/dtd/exception_1_1_1.dtd"; } if (DESCRIBELAYER_DTD == null) { DESCRIBELAYER_DTD = baseUrl.toString() + "/dtd/WMS_DescribeLayerResponse.dtd"; } DataWrapper data = new DataWrapper(request, response); Object identity = null; EntityManager em; EntityTransaction tx = null; try { identity = MyEMFDatabase.createEntityManager(MyEMFDatabase.MAIN_EM); em = MyEMFDatabase.getEntityManager(MyEMFDatabase.MAIN_EM); tx = em.getTransaction(); tx.begin(); DataMonitoring rr = new DataMonitoring(); data.setRequestReporting(rr); String serviceName = OGCConstants.WMS_SERVICE_WMS; try { OGCRequest ogcrequest = calcOGCRequest(request); String personalCode = null; if (ogcrequest != null) personalCode = ogcrequest.getPersonalCode(); data.setOgcrequest(ogcrequest); String serviceParam = ogcrequest.getParameter(OGCConstants.SERVICE); if (serviceParam != null || !"".equals(serviceParam)) { serviceName = serviceParam; } String iUrl = ogcrequest.getUrl(); rr.startClientRequest(iUrl, iUrl.getBytes().length, startTime, request.getRemoteAddr(), request.getMethod()); User user = checkLogin(request, personalCode, em); ogcrequest.checkRequestURL(); Organization mainOrg = null; String userName = null; if (user != null) { mainOrg = user.getMainOrganization(); userName = user.getUsername(); } rr.setUserAndOrganization(user, mainOrg); data.setHeader("X-Kaartenbalie-User", userName); parseRequestAndData(data, user); } catch (AccessDeniedException adex) { rr.setClientRequestException(adex); response.addHeader("WWW-Authenticate", "Basic realm=\"Kaartenbalie login\""); response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Access denied to Kaartenbalie"); } catch (ProviderException pex) { log.error("Error while communicating with provider: " + pex.getLocalizedMessage()); rr.setClientRequestException(pex); handleRequestException(pex, data); } catch (Exception e) { log.error(String.format("Error while handling request for URI %s, query string %s: %s: %s", request.getRequestURI(), request.getQueryString(), e.getClass().getName(), e.getMessage()), e); rr.setClientRequestException(e); handleRequestException(e, data); } finally { rr.endClientRequest(serviceName, data.getOperation(), data.getContentLength(), System.currentTimeMillis() - startTime); } if (!tx.getRollbackOnly()) { tx.commit(); } } catch (Exception ex) { log.error("Error creating EntityManager", ex); handleRequestException(ex, data); } finally { if (tx != null && tx.isActive()) { tx.rollback(); } MyEMFDatabase.closeEntityManager(identity, MyEMFDatabase.MAIN_EM); } }
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 {/*from w w w .j ava 2 s . 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(); } }