List of usage examples for javax.persistence EntityTransaction begin
public void begin();
From source file:org.opencastproject.usertracking.impl.UserTrackingServiceImpl.java
@SuppressWarnings("unchecked") public UserAction addUserFootprint(UserAction a) throws UserTrackingException { a.setType("FOOTPRINT"); EntityManager em = null;/* ww w . j a va 2s. c o m*/ EntityTransaction tx = null; try { em = emf.createEntityManager(); tx = em.getTransaction(); tx.begin(); Query q = em.createNamedQuery("findLastUserFootprintOfSession"); q.setMaxResults(1); q.setParameter("sessionId", a.getSessionId()); Collection<UserAction> userActions = q.getResultList(); if (userActions.size() >= 1) { UserAction last = userActions.iterator().next(); if (last.getMediapackageId().equals(a.getMediapackageId()) && last.getType().equals(a.getType()) && last.getOutpoint() == a.getInpoint()) { last.setOutpoint(a.getOutpoint()); a = last; a.setId(last.getId()); } else { em.persist(a); } } else { em.persist(a); } tx.commit(); return a; } catch (Exception e) { if (tx != null && tx.isActive()) { tx.rollback(); } throw new UserTrackingException(e); } finally { if (em != null && em.isOpen()) { em.close(); } } }
From source file:com.espirit.moddev.examples.uxbridge.newsdrilldown.jpa.NewsHandler.java
/** * Deletes a newsdrilldown from the db.//from ww w . ja va 2s. 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.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 {//w w w . j a va2s . 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 every item older than the creationTime of the UXBEntity. * * @param entity Entity containing the expireDate (= createTime of the entity) *//*from w w w.j a v 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(); } } }
From source file:de.randi2.testUtility.utility.Bootstrap.java
public void init() throws ServiceException { long time1 = System.nanoTime(); EntityTransaction transaction = entityManager.getTransaction(); transaction.begin(); entityManager.persist(Role.ROLE_INVESTIGATOR); entityManager.persist(Role.ROLE_USER); entityManager.persist(Role.ROLE_STATISTICAN); entityManager.persist(Role.ROLE_MONITOR); entityManager.persist(Role.ROLE_P_INVESTIGATOR); entityManager.persist(Role.ROLE_ANONYMOUS); entityManager.persist(Role.ROLE_ADMIN); Role.ROLE_ADMIN.getRolesToAssign().add(Role.ROLE_ADMIN); entityManager.merge(Role.ROLE_ADMIN); transaction.commit();//w w w . j a v a 2 s . c om transaction.begin(); Role roleAdmin = (Role) entityManager.find(Role.class, 1L); roleAdmin.getRolesToAssign().add(roleAdmin); entityManager.merge(roleAdmin); transaction.commit(); transaction.begin(); Person cp1 = new Person(); cp1.setFirstname("Contact"); cp1.setSurname("Person"); cp1.setEmail("randi2@action.ms"); cp1.setPhone("1234567"); cp1.setSex(Gender.MALE); Person cp2 = new Person(); cp2.setFirstname("Contact"); cp2.setSurname("Person"); cp2.setEmail("randi2@action.ms"); cp2.setPhone("1234567"); cp2.setSex(Gender.MALE); Person adminP = new Person(); adminP.setFirstname("Max"); adminP.setSurname("Administrator"); adminP.setEmail("randi2@action.ms"); adminP.setPhone("1234567"); adminP.setSex(Gender.MALE); Login adminL = new Login(); adminL.setUsername("admin@trialsite1.de"); adminL.setPassword(passwordEncoder.encodePassword("1$heidelberg", saltSourceUser.getSalt(adminL))); adminL.setPerson(adminP); adminL.setPrefLocale(Locale.GERMANY); adminL.addRole(Role.ROLE_ADMIN); adminL.setPrefLocale(Locale.GERMAN); entityManager.persist(adminL); TrialSite trialSite = new TrialSite(); trialSite.setCity("Heidelberg"); trialSite.setCountry("Germany"); trialSite.setName("Trial Site 1"); trialSite.setPostcode("69120"); trialSite.setStreet("INF"); trialSite.setPassword( passwordEncoder.encodePassword("1$heidelberg", saltSourceTrialSite.getSystemWideSalt())); trialSite.setContactPerson(cp1); trialSite.getMembers().add(adminP); entityManager.persist(trialSite); transaction.commit(); rolesAndRights.registerPerson(adminL); rolesAndRights.grantRights(adminL, trialSite); rolesAndRights.grantRights(trialSite, trialSite); entityManager.clear(); AnonymousAuthenticationToken authToken = new AnonymousAuthenticationToken("anonymousUser", adminL, new ArrayList<GrantedAuthority>(adminL.getAuthorities())); // Perform authentication SecurityContextHolder.getContext().setAuthentication(authToken); SecurityContextHolder.getContext().getAuthentication().setAuthenticated(true); Person userPInv = new Person(); userPInv.setFirstname("Maxi"); userPInv.setSurname("Investigator"); userPInv.setEmail("randi2@action.ms"); userPInv.setPhone("1234567"); // userPInv.setTrialSite(trialSite); Login userLInv = new Login(); userLInv.setUsername("investigator@trialsite1.de"); userLInv.setPassword("1$heidelberg"); userLInv.setPerson(userPInv); userLInv.setPrefLocale(Locale.GERMANY); userLInv.addRole(Role.ROLE_INVESTIGATOR); userLInv.setPrefLocale(Locale.GERMAN); userService.create(userLInv, trialSite); Person userPPInv = new Person(); userPPInv.setFirstname("Max"); userPPInv.setSurname("PInvestigator"); userPPInv.setEmail("randi2@action.ms"); userPPInv.setPhone("1234567"); userPPInv.setSex(Gender.MALE); // userPPInv.setTrialSite(trialSite); Login userLPInv = new Login(); userLPInv.setUsername("p_investigator@trialsite1.de"); userLPInv.setPassword("1$heidelberg"); userLPInv.setPerson(userPPInv); userLPInv.setPrefLocale(Locale.GERMANY); userLPInv.addRole(Role.ROLE_P_INVESTIGATOR); userLPInv.setPrefLocale(Locale.GERMAN); userService.create(userLPInv, trialSite); Person userP = new Person(); userP.setFirstname("Maxi"); userP.setSurname("Monitor"); userP.setEmail("randi2@action.ms"); userP.setPhone("1234567"); userP.setSex(Gender.FEMALE); // userP.setTrialSite(trialSite); Login userL = new Login(); userL.setUsername("monitor@trialsite1.de"); userL.setPassword("1$heidelberg"); userL.setPerson(userP); userL.setPrefLocale(Locale.GERMANY); userL.addRole(Role.ROLE_MONITOR); userL.setPrefLocale(Locale.GERMAN); userService.create(userL, trialSite); userP = new Person(); userP.setFirstname("Max"); userP.setSurname("Statistican"); userP.setEmail("randi2@action.ms"); userP.setPhone("1234567"); userP.setSex(Gender.MALE); // userP.setTrialSite(trialSite); userL = new Login(); userL.setUsername("statistican@trialsite1.de"); userL.setPassword("1$heidelberg"); userL.setPerson(userP); userL.setPrefLocale(Locale.GERMANY); userL.addRole(Role.ROLE_STATISTICAN); userL.setPrefLocale(Locale.GERMAN); userService.create(userL, trialSite); TrialSite trialSite1 = new TrialSite(); trialSite1.setCity("Heidelberg"); trialSite1.setCountry("Germany"); trialSite1.setName("Trial Site 2"); trialSite1.setPostcode("69120"); trialSite1.setStreet("INF"); trialSite1.setPassword("1$heidelberg"); trialSite1.setContactPerson(cp2); trialSiteService.create(trialSite1); // create test trial trialSite1 = trialSiteService.getObject(trialSite1.getId()); Person userPInv2 = new Person(); userPInv2.setFirstname("Max"); userPInv2.setSurname("Investigator"); userPInv2.setEmail("randi2@action.ms"); userPInv2.setPhone("1234567"); userPInv2.setSex(Gender.MALE); Login userLInv2 = new Login(); userLInv2.setUsername("investigator@trialsite2.de"); userLInv2.setPassword("1$heidelberg"); userLInv2.setPerson(userPInv2); userLInv2.setPrefLocale(Locale.GERMANY); userLInv2.addRole(Role.ROLE_INVESTIGATOR); userLInv2.setPrefLocale(Locale.GERMAN); userService.create(userLInv2, trialSite1); // create test trial System.out.println("create user: " + (System.nanoTime() - time1) / 1000000 + " ms"); time1 = System.nanoTime(); // create test trial authToken = new AnonymousAuthenticationToken("anonymousUser", userLPInv, new ArrayList<GrantedAuthority>(userLPInv.getAuthorities())); // Perform authentication SecurityContextHolder.getContext().setAuthentication(authToken); SecurityContextHolder.getContext().getAuthentication().setAuthenticated(true); trialSite1 = entityManager.find(TrialSite.class, trialSite1.getId()); Trial trial = new Trial(); trial.setAbbreviation("bs"); trial.setName("Block study"); trial.setDescription("Block study with two treatment arms and blocksize 8, stratified by trial site"); trial.setGenerateIds(true); trial.setStratifyTrialSite(true); trial.setSponsorInvestigator(userPPInv); trial.setLeadingSite(trialSite); trial.addParticipatingSite(trialSite); trial.addParticipatingSite(trialSite1); trial.setStartDate(new GregorianCalendar(2009, 0, 1)); trial.setEndDate(new GregorianCalendar(2010, 11, 1)); trial.setStatus(TrialStatus.ACTIVE); BlockRandomizationConfig randConf = new BlockRandomizationConfig(); randConf.setMaximum(8); randConf.setMinimum(8); randConf.setType(TYPE.ABSOLUTE); trial.setRandomizationConfiguration(randConf); TreatmentArm arm1 = new TreatmentArm(); arm1.setDescription("First Treatment"); arm1.setName("arm1"); arm1.setDescription("description"); arm1.setPlannedSubjects(200); TreatmentArm arm2 = new TreatmentArm(); arm2.setDescription("Second Treatment"); arm2.setName("arm2"); arm2.setDescription("description"); arm2.setPlannedSubjects(200); trial.setTreatmentArms(new HashSet<TreatmentArm>(Arrays.asList(arm1, arm2))); DichotomousCriterion cr = new DichotomousCriterion(); cr.setName("SEX"); cr.setOption1("M"); cr.setOption2("F"); DichotomousCriterion cr1 = new DichotomousCriterion(); cr1.setOption1("1"); cr1.setOption2("2"); cr1.setName("Tum.Status"); DichotomousCriterion cr2 = new DichotomousCriterion(); cr2.setOption1("1"); cr2.setOption2("2"); cr2.setName("Fit.Level"); try { cr.addStrata(new DichotomousConstraint(Arrays.asList(new String[] { "M" }))); cr.addStrata(new DichotomousConstraint(Arrays.asList(new String[] { "F" }))); cr1.addStrata(new DichotomousConstraint(Arrays.asList(new String[] { "1" }))); cr1.addStrata(new DichotomousConstraint(Arrays.asList(new String[] { "2" }))); cr2.addStrata(new DichotomousConstraint(Arrays.asList(new String[] { "1" }))); cr2.addStrata(new DichotomousConstraint(Arrays.asList(new String[] { "2" }))); trial.addCriterion(cr); trial.addCriterion(cr1); trial.addCriterion(cr2); } catch (ConstraintViolatedException e) { BoxedException.throwBoxed(e); } try { trialService.create(trial); } catch (ConstraintViolationException e) { // TODO: handle exception System.out.println(e.getMessage()); for (ConstraintViolation<?> v : e.getConstraintViolations()) { System.out.println(v.getPropertyPath() + " " + v.getMessage()); } } System.out.println("create trial: " + (System.nanoTime() - time1) / 1000000 + " ms"); time1 = System.nanoTime(); int countTS1 = 120; int countTS2 = 60; int countMo = (new GregorianCalendar()).get(GregorianCalendar.MONTH) + 1; int countAll = 0; // Objects for the while-loop Random rand = new Random(); GregorianCalendar date; int runs; boolean tr1; int count; // --- while (countTS1 != 0 || countTS2 != 0) { countAll++; date = new GregorianCalendar(2009, countAll % countMo, 1); runs = 0; tr1 = false; count = 0; if (rand.nextInt(2) == 0 && countTS1 != 0) { count = countTS1; tr1 = true; } else if (countTS2 != 0) { count = countTS2; } if (count >= 10) { runs = rand.nextInt(10) + 1; } else if (count != 0) { runs = rand.nextInt(count) + 1; } // Authorizing the investigator for upcoming randomization AnonymousAuthenticationToken at = tr1 ? new AnonymousAuthenticationToken("anonymousUser", userLInv, new ArrayList<GrantedAuthority>(userLInv.getAuthorities())) : new AnonymousAuthenticationToken("anonymousUser", userLInv2, new ArrayList<GrantedAuthority>(userLInv2.getAuthorities())); SecurityContextHolder.getContext().setAuthentication(at); SecurityContextHolder.getContext().getAuthentication().setAuthenticated(true); // --- for (int i = 0; i < runs; i++) { initRandBS(trial, date, rand); if (tr1) { countTS1--; } else { countTS2--; } } } System.out.println("added trial subjects: " + (System.nanoTime() - time1) / 1000000 + " ms"); }
From source file:com.espirit.moddev.examples.uxbridge.newsdrilldown.jpa.NewsHandler.java
/** * saves or updates a newscategory./* w w w .j av a 2 s .c om*/ * * @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.opencastproject.capture.admin.impl.CaptureAgentStateServiceImpl.java
/** * Removes an agent from the database.// w ww . j a va 2s . c om * * @param agentName * The name of the agent you wish to remove. */ private void deleteAgentFromDatabase(String agentName) throws NotFoundException { EntityManager em = null; EntityTransaction tx = null; try { em = emf.createEntityManager(); tx = em.getTransaction(); tx.begin(); String org = securityService.getOrganization().getId(); Agent existing = getAgentEntity(agentName, org, em); if (existing == null) throw new NotFoundException(); em.remove(existing); tx.commit(); agentCache.remove(agentName.concat(DELIMITER).concat(org)); } catch (RollbackException e) { logger.warn("Unable to commit to DB in deleteAgent."); } finally { if (em != null) em.close(); } }
From source file:org.apache.juddi.api.impl.JUDDIApiImpl.java
/** * Instructs the registry to perform a synchronous subscription * response.//from w ww .j a va 2 s. c om * @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:nl.b3p.kaartenbalie.service.servlet.CallScriptingServlet.java
/** * Processes the incoming request and calls the various methods to create * the right output stream./* w ww. j a va 2s . co m*/ * * @param request servlet request * @param response servlet response * * @throws ServletException * @throws IOException */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { long startTime = System.currentTimeMillis(); DataWrapper data = new DataWrapper(request, response); Object identity = null; EntityManager em; EntityTransaction tx = null; try { /* * Check IP lock */ checkRemoteIP(request); identity = MyEMFDatabase.createEntityManager(MyEMFDatabase.MAIN_EM); log.debug("Getting entity manager ......"); 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 { OGCScriptingRequest ogcrequest = calcOGCScriptingRequest(request); if (!ogcrequest.containsParameter(OGCScriptingRequest.COMMAND)) { throw new Exception("Bad request"); } data.setOgcrequest(ogcrequest); String serviceParam = ogcrequest.getParameter(OGCConstants.SERVICE); if (serviceParam != null || !"".equals(serviceParam)) { serviceName = serviceParam; } String iUrl = ogcrequest.getUrl(); String pcode = ogcrequest.getPersonalCode(); rr.startClientRequest(iUrl, iUrl.getBytes().length, startTime, request.getRemoteAddr(), request.getMethod()); User user = checkLogin(request, em, pcode); if (ogcrequest != null) { ogcrequest.checkRequestURL(); } rr.setUserAndOrganization(user, user.getMainOrganization()); data.setHeader("X-Kaartenbalie-User", user.getUsername()); this.httpRequest = request; if (ogcrequest.getParameter(OGCScriptingRequest.COMMAND) .equalsIgnoreCase(OGCScriptingRequest.GET_GROUP_XML)) { GroupParser groupParser = new GroupParser(); groupParser.getGroupsAsXML(response, data.getOutputStream()); } else { parseRequestAndData(data, user); } } catch (AccessDeniedException adex) { log.error("Access denied: " + adex.getLocalizedMessage()); rr.setClientRequestException(adex); response.addHeader("WWW-Authenticate", "Basic realm=\"Kaartenbalie login\""); response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Access denied to Kaartenbalie"); } catch (Exception ex) { log.error("Error while handling request: ", ex); rr.setClientRequestException(ex); response.sendError(400, "Bad Request. See API documentation"); } finally { rr.endClientRequest(serviceName, data.getOperation(), data.getContentLength(), System.currentTimeMillis() - startTime); } tx.commit(); } catch (Exception ex) { log.error("Error creating EntityManager: ", ex); try { tx.rollback(); } catch (Exception ex2) { log.error("Error trying to rollback: ", ex2); } } finally { //log.debug("Closing entity manager ....."); MyEMFDatabase.closeEntityManager(identity, MyEMFDatabase.MAIN_EM); } }
From source file:gr.upatras.ece.nam.baker.impl.BakerJpaController.java
public void deleteSubscribedResource(int smId) { EntityManager entityManager = entityManagerFactory.createEntityManager(); SubscribedResource sm = entityManager.find(SubscribedResource.class, smId); EntityTransaction entityTransaction = entityManager.getTransaction(); entityTransaction.begin(); entityManager.remove(sm);/*from ww w. ja v a 2s . c om*/ entityTransaction.commit(); }