List of usage examples for javax.persistence EntityManager getTransaction
public EntityTransaction getTransaction();
EntityTransaction
object. From source file:it.infn.ct.futuregateway.apiserver.v1.TaskService.java
/** * Uploads input files. The method store input files for the specified task. * Input files are provided as a <i>multipart form data</i> using the field * file. This can contains multiple file using the html input attribute * <i>multiple="multiple"</i> which allows to associate multiple files with * a single field./*from w w w.jav a 2 s. co m*/ * * @param id The task id retrieved from the url path * @param lstFiles List of file in the POST body */ @Path("/input") @POST @Consumes({ MediaType.MULTIPART_FORM_DATA }) public final void setInputFile(@PathParam("id") final String id, @FormDataParam("file") final List<FormDataBodyPart> lstFiles) { if (lstFiles == null || lstFiles.isEmpty()) { throw new BadRequestException("Input not accessible!"); } EntityManager em = getEntityManager(); Task task = em.find(Task.class, id); task.addObserver(new TaskObserver(getEntityManagerFactory(), getSubmissionThreadPool())); if (task == null) { throw new NotFoundException("Task " + id + " does not exist"); } for (FormDataBodyPart fdbp : lstFiles) { final String fName = fdbp.getFormDataContentDisposition().getFileName(); try { Storage store = getStorage(); store.storeFile(Storage.RESOURCE.TASKS, id, fdbp.getValueAs(InputStream.class), fName); EntityTransaction et = em.getTransaction(); try { et.begin(); task.updateInputFileStatus(fName, TaskFile.FILESTATUS.READY); et.commit(); } catch (RuntimeException re) { if (et != null && et.isActive()) { et.rollback(); } log.error(re); log.error("Impossible to update the task"); throw new InternalServerErrorException("Errore to update " + "the task"); } finally { em.close(); } } catch (IOException ex) { log.error(ex); throw new InternalServerErrorException("Errore to store input " + "files"); } } em.close(); }
From source file:com.espirit.moddev.examples.uxbridge.newsdrilldown.jpa.NewsHandler.java
/** * Deletes a newsdrilldown from the db./*from w ww .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.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 ww.jav a 2 s . co m 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:nl.b3p.kaartenbalie.service.servlet.CallScriptingServlet.java
/** * Processes the incoming request and calls the various methods to create * the right output stream.//from w ww .j a va2 s.c o 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:com.espirit.moddev.examples.uxbridge.newsdrilldown.jpa.NewsHandler.java
/** * saves or updates a newscategory./* w ww . j a v a2 s .co m*/ * * @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:de.iai.ilcd.model.dao.SourceDao.java
/** * Concrete implementation required for saving of digital files */// ww w. ja v a 2s . c o m @Override public boolean checkAndPersist(Source source, PersistType pType, PrintWriter out) { EntityManager em = PersistenceUtil.getEntityManager(); Source existingSource = this.getByUuid(source.getUuid().getUuid()); if (existingSource != null) { if (pType == PersistType.ONLYNEW) { out.println( "Warning: source data set with this uuid already exists in database; will ignore this data set"); return false; } } EntityTransaction t = em.getTransaction(); try { t.begin(); if (existingSource != null && (pType == PersistType.MERGE)) { // delete first the existing one, we will use the new one if (out != null) { out.println( "Notice: source data set with this uuid already exists in database; will merge this data set"); } em.remove(existingSource); this.deleteDigitalFiles(source); } em.persist(source); t.commit(); if (!super.setMostRecentVersionFlags(source.getUuidAsString())) { return false; } if (source != null && source.getId() != null) { if (!this.saveDigitalFiles(source, out)) { if (out != null) { out.println( "Warning: couldn't save all files of this source data set into database file directory: see messages above"); } } } return true; } catch (Exception e) { if (out != null) { out.println("Can't save source data file to database because of: " + e.getMessage()); } t.rollback(); return false; } }
From source file:com.gigglinggnus.controllers.ModifyAppointmentController.java
/** * * @param request servlet request/*from ww w . j ava 2 s. c o m*/ * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { EntityManager em = (EntityManager) request.getSession().getAttribute("em"); Clock clk = (Clock) (request.getSession().getAttribute("clock")); boolean modified = false; String userId = request.getParameter("userid"); User user = em.find(User.class, userId); String examId = request.getParameter("examid"); Exam exam = em.find(Exam.class, examId); Appointment appt = user.getAppointmentByExam(exam); String startTime = request.getParameter("startTime"); String seatZone = request.getParameter("seatingZone"); String seatNum = request.getParameter("seatNum"); String cancel = request.getParameter("cancel"); try { em.getTransaction().begin(); if (startTime != "") { appt.changeStartTime(Instant.parse(startTime), clk); em.persist(appt); modified = true; } if (seatZone != "") { appt.setSeatingZone(Seating.parse(seatZone)); em.persist(appt); modified = true; } if (seatNum != "") { appt.setSeatNum(Integer.parseInt(seatNum)); em.persist(appt); modified = true; } em.getTransaction().commit(); } catch (Exception e) { em.getTransaction().rollback(); request.setAttribute("msg", e); RequestDispatcher rd = request.getRequestDispatcher("/home.jsp"); rd.forward(request, response); } if (cancel != null) { request.setAttribute("msg", "Appointment cancelled"); RequestDispatcher rd = request.getRequestDispatcher("/home.jsp"); rd.forward(request, response); } if (modified == true) { request.setAttribute("msg", "Appointment modified"); RequestDispatcher rd = request.getRequestDispatcher("/home.jsp"); rd.forward(request, response); } else { request.setAttribute("msg", "Appointment unchanged"); RequestDispatcher rd = request.getRequestDispatcher("/home.jsp"); rd.forward(request, response); } }
From source file:gr.upatras.ece.nam.baker.impl.BakerJpaController.java
public InstalledBun updateInstalledBun(InstalledBun is) { EntityManager entityManager = entityManagerFactory.createEntityManager(); EntityTransaction entityTransaction = entityManager.getTransaction(); entityTransaction.begin();/* w ww . j a v a 2 s . c o m*/ InstalledBun resis = entityManager.merge(is); entityTransaction.commit(); return resis; }
From source file:gr.upatras.ece.nam.baker.impl.BakerJpaController.java
public void deleteInstalledBun(final InstalledBun message) { EntityManager entityManager = entityManagerFactory.createEntityManager(); EntityTransaction entityTransaction = entityManager.getTransaction(); entityTransaction.begin();/*from ww w. ja v a2 s . c om*/ entityManager.remove(message); entityTransaction.commit(); }
From source file:gr.upatras.ece.nam.baker.impl.BakerJpaController.java
public BakerUser updateBakerUser(BakerUser bu) { EntityManager entityManager = entityManagerFactory.createEntityManager(); EntityTransaction entityTransaction = entityManager.getTransaction(); entityTransaction.begin();/*from ww w.java 2s. c o m*/ BakerUser resis = entityManager.merge(bu); entityTransaction.commit(); return resis; }