List of usage examples for org.hibernate Session get
Object get(String entityName, Serializable id);
From source file:ca.mcgill.cs.swevo.qualyzer.model.Facade.java
License:Open Source License
/** * Try to delete the memo./*from w ww .ja v a 2 s.c o m*/ * * @param memo */ public void deleteMemo(Memo memo) { Object project = null; HibernateDBManager manager = QualyzerActivator.getDefault().getHibernateDBManagers() .get(memo.getProject().getFolderName()); Session session = null; Transaction t = null; try { session = manager.openSession(); t = session.beginTransaction(); /* * The following is ALL required in order to delete the object from the database. Don't ask me why, I don't * really understand it myself -JF. */ project = session.get(Project.class, memo.getProject().getPersistenceId()); Memo lMemo = (Memo) session.get(Memo.class, memo.getPersistenceId()); ((Project) project).getMemos().remove(lMemo); session.delete(lMemo); session.saveOrUpdate(project); session.flush(); t.commit(); fListenerManager.notifyMemoListeners(ChangeType.DELETE, new Memo[] { memo }, this); } catch (HibernateException e) { HibernateUtil.quietRollback(t); String key = "model.Facade.Memo.cannotDelete"; //$NON-NLS-1$ String errorMessage = Messages.getString(key); fLogger.error(key, e); throw new QualyzerException(errorMessage, e); } finally { HibernateUtil.quietClose(session); } }
From source file:ca.mcgill.cs.swevo.qualyzer.model.Facade.java
License:Open Source License
/** * Force a Transcript to load all its fields. * /* ww w . j ava 2 s .c o m*/ * @param transcript * @return */ public Transcript forceTranscriptLoad(Transcript transcript) { Transcript toReturn = null; HibernateDBManager manager = QualyzerActivator.getDefault().getHibernateDBManagers() .get(transcript.getProject().getFolderName()); Session s = manager.openSession(); try { Object object = s.get(Transcript.class, transcript.getPersistenceId()); toReturn = (Transcript) object; Hibernate.initialize(toReturn.getParticipants()); Hibernate.initialize(toReturn.getFragments()); Hibernate.initialize(toReturn.getTimestamps()); } finally { HibernateUtil.quietClose(s); } return toReturn; }
From source file:ca.mcgill.cs.swevo.qualyzer.model.Facade.java
License:Open Source License
/** * Force a Memo to load all of its fields. * //from w w w . ja v a 2 s . com * @param memo * @return */ public Memo forceMemoLoad(Memo memo) { Memo toReturn = null; HibernateDBManager manager = QualyzerActivator.getDefault().getHibernateDBManagers() .get(memo.getProject().getFolderName()); Session s = manager.openSession(); try { Object object = s.get(Memo.class, memo.getPersistenceId()); toReturn = (Memo) object; Hibernate.initialize(toReturn.getParticipants()); Hibernate.initialize(toReturn.getFragments()); } finally { HibernateUtil.quietClose(s); } return toReturn; }
From source file:ca.mcgill.cs.swevo.qualyzer.model.Facade.java
License:Open Source License
/** * Delete a code.//from www. ja v a 2 s. c om * @param code */ public void deleteCode(Code code) { Object project = null; HibernateDBManager manager = QualyzerActivator.getDefault().getHibernateDBManagers() .get(code.getProject().getFolderName()); Session session = null; Transaction t = null; try { session = manager.openSession(); t = session.beginTransaction(); /* * The following is ALL required in order to delete the object from the database. Don't ask me why, I don't * really understand it myself -JF. */ project = session.get(Project.class, code.getProject().getPersistenceId()); Object lCode = session.get(Code.class, code.getPersistenceId()); ((Project) project).getCodes().remove(lCode); session.delete(lCode); session.saveOrUpdate(project); session.flush(); t.commit(); fListenerManager.notifyCodeListeners(ChangeType.DELETE, new Code[] { (Code) lCode }, this); } catch (HibernateException e) { HibernateUtil.quietRollback(t); String errorMessage = Messages.getString("model.Facade.code.cannotDelete"); //$NON-NLS-1$ fLogger.error(errorMessage, e); throw new QualyzerException(errorMessage, e); } finally { HibernateUtil.quietClose(session); } }
From source file:ca.mcgill.cs.swevo.qualyzer.model.FacadeTest.java
License:Open Source License
/** * //from w w w.j a va 2 s . com * Verifies that a transcript can be deleted. * */ @Test public void testDeleteTranscript() { String pId = "p1"; String pName = "Toto"; String transcriptName = "t1"; Participant participant = fFacade.createParticipant(pId, pName, fProject); List<Participant> participants = new ArrayList<Participant>(); participants.add(participant); Transcript transcript = fFacade.createTranscript(transcriptName, "6/26/2010", "", participants, fProject); Fragment fragment = fFacade.createFragment(transcript, 1, 1); fFacade.saveTranscript(transcript); long id = fragment.getPersistenceId(); fFacade.deleteTranscript( PersistenceManager.getInstance().getProject(fProject.getName()).getTranscripts().get(0)); // event 0: create part, 1: create tr, 2: create fr., 3: modify tr, 4: delete tr. ListenerEvent event = fListener.getEvents().get(4); assertEquals(ChangeType.DELETE, event.getChangeType()); assertArrayEquals(new Transcript[] { transcript }, (Object[]) event.getObject()); assertEquals(0, PersistenceManager.getInstance().getProject(fProject.getName()).getTranscripts().size()); // Test Fragment HibernateDBManager dbManager = QualyzerActivator.getDefault().getHibernateDBManagers() .get(TEST_PROJECT_NAME); Session session = dbManager.openSession(); // It should be impossible to retrieve the fragment. try { assertNull(session.get(Fragment.class, id)); } finally { HibernateUtil.quietClose(session); } }
From source file:ca.mcgill.cs.swevo.qualyzer.model.FacadeTest.java
License:Open Source License
/** * /*from w w w. j a v a 2 s. c o m*/ * Verifies that a memo can be deleted. * */ @Test public void testDeleteMemo() { String pId = "p1"; String pName = "Toto"; String memoName = "t1"; Participant participant = fFacade.createParticipant(pId, pName, fProject); List<Participant> participants = new ArrayList<Participant>(); participants.add(participant); Investigator inves = fProject.getInvestigators().get(0); Memo memo = fFacade.createMemo(memoName, "6/26/2010", inves, participants, fProject, null, null); Fragment fragment = fFacade.createFragment(memo, 1, 1); fFacade.saveMemo(memo); long id = fragment.getPersistenceId(); fFacade.deleteMemo(PersistenceManager.getInstance().getProject(fProject.getName()).getMemos().get(0)); // event 0: create part, 1: create memo, 2: create fr., 3: modify memo, 4: delete memo. ListenerEvent event = fListener.getEvents().get(4); assertEquals(ChangeType.DELETE, event.getChangeType()); assertArrayEquals(new Memo[] { memo }, (Object[]) event.getObject()); assertEquals(0, PersistenceManager.getInstance().getProject(fProject.getName()).getMemos().size()); // Test Fragment HibernateDBManager dbManager = QualyzerActivator.getDefault().getHibernateDBManagers() .get(TEST_PROJECT_NAME); Session session = dbManager.openSession(); // It should be impossible to retrieve the fragment. try { assertNull(session.get(Fragment.class, id)); } finally { HibernateUtil.quietClose(session); } }
From source file:ca.myewb.frame.servlet.AjaxServlet.java
License:Open Source License
private void groupFiles(HttpServletRequest request, Logger log, Session s, UserModel currentUser, Context ctx) throws Exception { GroupModel theGroup = (GroupModel) s.get(GroupModel.class, new Integer(request.getParameter("groupId"))); if (theGroup == null) { throw new RedirectionException( Controller.path + "/mailing/ListInfo/" + request.getParameter("groupId")); }//from ww w. ja v a 2 s . com if (currentUser.getUsername().equals("guest")) { log.warn("Guest tried to view files belonging to " + theGroup.getShortname()); throw new RedirectionException(Helpers.getAppPrefix() + "/ajax/keepalive"); } String action = request.getParameter("action"); String decodedPath = URLDecoder.decode(request.getParameter("path"), "UTF-8"); if (action.equals("delete") && (Permissions.canManageFilesInGroup(currentUser, theGroup))) { File file = new File(Helpers.getUserFilesDir() + "groupfiles/" + request.getParameter("groupId") + "/" + decodedPath); File trashFile = new File(Helpers.getUserFilesDir() + "groupfiles/" + request.getParameter("groupId") + "/.trash/" + decodedPath); // Re-create directory structure in .trash if (!trashFile.getParentFile().exists()) { trashFile.getParentFile().mkdirs(); } // Delete old file in .trash else if (trashFile.exists()) { deleteDir(trashFile); } // Attempt to move into trash if (!file.renameTo(trashFile)) { log.error("File rename failed for " + file.getAbsolutePath()); } throw new RedirectionException(Helpers.getAppPrefix() + "/ajax/keepalive"); } else if (action.equals("showDirectory") && Permissions.canReadFilesInGroup(currentUser, theGroup)) { File dirRoot = new File(Helpers.getUserFilesDir() + "groupfiles/" + request.getParameter("groupId") + "/" + decodedPath); LinkedList<FileNameWrapper> directories = new LinkedList<FileNameWrapper>(); LinkedList<FileNameWrapper> files = new LinkedList<FileNameWrapper>(); log.info("Using the directory " + dirRoot.getAbsolutePath()); if (!dirRoot.exists()) { throw new RedirectionException(Controller.path + "/ajax/keepalive"); } // Read entire directory, and stuff into directories/files lists TreeSet<File> dirList = new TreeSet<File>(Arrays.asList(dirRoot.listFiles())); for (File f : dirList) { if (!f.getName().equals(".trash")) { if (f.isDirectory()) { directories.add(new FileNameWrapper(f)); } else if (f.isFile()) { files.add(new FileNameWrapper(f)); } } } //Set up velocity stuff ctx.put("directories", directories); ctx.put("files", files); ctx.put("pathHash", new FileNameWrapper(dirRoot).getMD5Hash()); ctx.put("relPath", new FileNameWrapper(dirRoot).getRelativePath()); ctx.put("groupID", request.getParameter("groupId")); ctx.put("base", Helpers.getAppPrefix()); ctx.put("canEdit", Permissions.canManageFilesInGroup(currentUser, theGroup)); } else { throw new RedirectionException( Controller.path + "/mailing/ListInfo/" + request.getParameter("groupId")); } }
From source file:ca.myewb.frame.servlet.FileServlet.java
License:Open Source License
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { Logger log = Logger.getLogger(this.getClass()); log.info("****** (post/whiteboard file)"); log.info("requestURI= " + req.getRequestURI()); log.info("referer= " + req.getHeader("Referer")); log.info("user-agent= " + req.getHeader("User-Agent")); try {//from w ww .ja v a 2 s. co m Session s = HibernateUtil.currentSession(); HttpSession httpSession = req.getSession(); log.info("request URI = " + req.getRequestURI()); String[] path = Helpers.getURIComponents(req.getRequestURI()); String prefix = path[0]; String id = path[1]; String file = ""; log.info("Prefix: " + prefix + ", ID: " + id); for (int i = 2; i < path.length; i++) { file += "/" + path[i]; } file = URLDecoder.decode(file, "UTF-8"); UserModel currentUser = WrapperServlet.getUser(Helpers.getDefaultURL(), log, s, httpSession); String internalFolder = ""; if (prefix.equals("postfile")) { internalFolder = "/posts/"; PostModel thePost = (PostModel) s.get(PostModel.class, new Integer(id)); if ((thePost == null) || !Permissions.canReadPost(currentUser, thePost)) { log.debug((thePost == null) ? "The post is null" : currentUser.getUsername() + " does not have permission to see post number " + thePost.getId() + " belonging to " + thePost.getGroup().getName()); throw new RedirectionException(Controller.path + "/home/ShowPost/" + id); } } else if (prefix.equals("whiteboardfile")) { internalFolder = "/whiteboards/"; WhiteboardModel theWhiteboard = (WhiteboardModel) s.get(WhiteboardModel.class, new Integer(id)); if (theWhiteboard == null || !theWhiteboard.isEnabled()) { throw new RedirectionException(Controller.path + "/events/EditWhiteboard/-1"); } if (!Permissions.canUpdateWhiteboard(currentUser, theWhiteboard)) { throw new RedirectionException( Controller.path + "/events/EventInfo/" + theWhiteboard.getParentEvent().getId()); } } else if (prefix.equals("groupfiles")) { if (currentUser.getUsername().equals("guest")) { log.info("A guest tried to get to files in group number " + id); throw new RedirectionException(Controller.path + "/mailing/ShowGroupFiles/" + id); } internalFolder = "/groupfiles/"; GroupModel theGroup = (GroupModel) s.get(GroupModel.class, new Integer(id)); if ((theGroup == null) || !Permissions.canReadFilesInGroup(currentUser, theGroup)) { throw new RedirectionException(Controller.path + "/mailing/ListInfo/" + id); } } else { httpSession.setAttribute("message", new ErrorMessage("The URL you requested is invalid.")); throw new RedirectionException(Helpers.getDefaultURL()); } /////// SECURITY CHECKS COMPLETE File theFile = new File(Helpers.getUserFilesDir() + internalFolder + id + file); OutputStream out = res.getOutputStream(); InputStream in = null; try { in = new BufferedInputStream(new FileInputStream(theFile)); String name = theFile.getName(); boolean forceDownload = true; if (name.endsWith(".doc")) { res.setContentType("application/msword"); } else if (name.endsWith(".zip")) { res.setContentType("application/zip"); } else if (name.endsWith(".html") || name.endsWith(".html")) { res.setContentType("text/html"); } else if (name.endsWith(".xls")) { res.setContentType("application/vnd.ms-excel"); } else if (name.endsWith(".ppt")) { res.setContentType("application/vnd.ms-powerpoint"); } else if (name.endsWith(".ppt")) { res.setContentType("application/vnd.ms-powerpoint"); } else if (name.endsWith(".pdf")) { res.setContentType("application/pdf"); forceDownload = false; } else if (name.endsWith(".jpg") || name.endsWith(".jpeg")) { res.setContentType("image/jpeg"); forceDownload = false; } else if (name.endsWith(".gif")) { res.setContentType("image/gif"); forceDownload = false; } else if (name.endsWith(".png")) { res.setContentType("image/png"); forceDownload = false; } else { res.setContentType("application/x-download"); } if (forceDownload) { res.setHeader("Content-Disposition", "attachment; filename=\"" + name + "\""); } res.setContentLength((int) theFile.length()); byte[] buf = new byte[4 * 1024]; // 4K buffer int bytesRead; while ((bytesRead = in.read(buf)) != -1) { out.write(buf, 0, bytesRead); } } catch (FileNotFoundException ex) { // If it was not a subdirectory-related problem, // keep throwing the error if (file.indexOf('/') == -1) throw ex; } finally { if (in != null) { in.close(); } } } catch (RedirectionException re) { log.info("Clean redirect: " + re.getTargetURL(), re); res.sendRedirect(re.getTargetURL()); } catch (Exception e) { log.error("FileServletError!", e); res.sendError(500, e.toString()); } }
From source file:ca.myewb.frame.servlet.GraphServlet.java
License:Open Source License
private JFreeChart getChapterRankPie(Session s, String url) { String[] path = url.split("/"); String lastPiece = path[path.length - 1]; Integer chapterId = new Integer(lastPiece.substring(0, lastPiece.length() - 4)); GroupChapterModel chapter = (GroupChapterModel) s.get(GroupChapterModel.class, chapterId); JFreeChart chart;/*from www .j a v a 2s .c o m*/ DefaultPieDataset ds = new DefaultPieDataset(); String query = "select count(*) as num from roles r1, roles r2 " + "where r1.userid=r2.userid and r1.groupid=? and r1.level='m' and r2.level='m' " + "and r1.end is null and r2.end is null and r2.groupid=?"; int numRegular = ((Integer) s.createSQLQuery(query).addScalar("num", Hibernate.INTEGER) .setInteger(0, chapter.getId()).setInteger(1, Helpers.getGroup("Regular").getId()).list().get(0)) .intValue(); int numAssociate = ((Integer) s.createSQLQuery(query).addScalar("num", Hibernate.INTEGER) .setInteger(0, chapter.getId()).setInteger(1, Helpers.getGroup("Associate").getId()).list().get(0)) .intValue(); int numUsers = chapter.getNumMembers(); ds.setValue("Regular Members", numRegular); ds.setValue("Associate Members", numAssociate); ds.setValue("Mailing list Members", numUsers - numAssociate - numRegular); chart = ChartFactory.createPieChart("Status breakdown for " + numUsers + " chapter members", ds, false, false, false); PiePlot plot = ((PiePlot) chart.getPlot()); StandardPieItemLabelGenerator n = new StandardPieItemLabelGenerator("{0} = {1} ({2})", new DecimalFormat("0"), new DecimalFormat("0.0%")); plot.setLabelGenerator(n); return chart; }
From source file:ca.myewb.frame.servlet.GraphServlet.java
License:Open Source License
private JFreeChart getListMemberships(Session s, int groupId, UserModel currentUser) { final int NUM_MONTHS = 6; Logger log = Logger.getLogger(this.getClass()); JFreeChart chart;// w w w. j a va2 s . c o m Date startDate; TreeMap<Day, Integer> memberChange = new TreeMap<Day, Integer>(); GroupModel g = (GroupModel) s.get(GroupModel.class, groupId); if (g == null) { log.warn("Someone requested chapter stats with a bad group id"); } else if (!Permissions.canAdministerGroupMembership(currentUser, g)) { log.warn(currentUser.getUsername() + "tried to access list memberships graph!"); } Calendar cal = GregorianCalendar.getInstance(); Date now = cal.getTime(); cal.set(Calendar.HOUR, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 1); cal.add(Calendar.MONTH, -NUM_MONTHS); startDate = cal.getTime(); //Set Initial Number of Members int initMembers = g.getNumMembers() + g.getNumRecipients(); //Pull a list of all of the membership start dates List starts = s.createQuery("SELECT rm.start, count(*) " + "FROM RoleModel as rm " + "WHERE rm.group = :group " + "AND (rm.level = 'r' OR rm.level = 'm') " + "AND rm.start > :startDate " + "GROUP BY rm.start ").setEntity("group", g) .setDate("startDate", startDate).list(); for (Object o : starts) { Day date = new Day((Date) (((Object[]) o)[0])); int change = ((Long) (((Object[]) o)[1])).intValue(); memberChange.put(date, change); initMembers -= change; } //Pull a list of all of the membership end dates List ends = s.createQuery("SELECT rm.end, count(*) " + "FROM RoleModel as rm " + "WHERE rm.group = :group " + "AND (rm.level = 'r' OR rm.level = 'm') " + "AND rm.end > :startDate " + "GROUP BY rm.end ") .setEntity("group", g).setDate("startDate", startDate).list(); for (Object o : ends) { Day date = new Day((Date) (((Object[]) o)[0])); int change = ((Long) (((Object[]) o)[1])).intValue(); if (memberChange.containsKey(date)) { memberChange.put(date, memberChange.get(date) - change); } else { memberChange.put(date, -change); } initMembers += change; } TimeSeriesCollection theData = new TimeSeriesCollection(); TimeSeries signups = new TimeSeries("List Membership", Day.class); theData.addSeries(signups); while (startDate.before(now)) { Day d = new Day(startDate); if (memberChange.containsKey(d)) { initMembers += memberChange.get(d); } signups.add(d, initMembers); cal.add(Calendar.DATE, 1); startDate = cal.getTime(); } chart = ChartFactory.createTimeSeriesChart("List Members", "Day", "Number of Members", theData, true, true, true); XYPlot plot = (XYPlot) chart.getPlot(); XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) plot.getRenderer(); renderer.setSeriesStroke(0, new BasicStroke(2.0f)); return chart; }