Example usage for org.hibernate LockMode UPGRADE

List of usage examples for org.hibernate LockMode UPGRADE

Introduction

In this page you can find the example usage for org.hibernate LockMode UPGRADE.

Prototype

LockMode UPGRADE

To view the source code for org.hibernate LockMode UPGRADE.

Click Source Link

Document

An upgrade lock.

Usage

From source file:de.tuclausthal.submissioninterface.persistence.dao.impl.TestDAO.java

License:Open Source License

@Override
public Test takeTest() {
    Session session = getSession();/*from  w w  w  . j  a  va2  s  .c  o  m*/
    Transaction tx = session.beginTransaction();
    Test test = (Test) session.createCriteria(Test.class).add(Restrictions.eq("forTutors", true))
            .add(Restrictions.eq("needsToRun", true)).setLockMode(LockMode.UPGRADE).createCriteria("task")
            .add(Restrictions.le("deadline", Util.correctTimezone(new Date()))).setMaxResults(1).uniqueResult();
    if (test != null) {
        test.setNeedsToRun(false);
        session.save(test);
    }
    tx.commit();
    return test;
}

From source file:de.tuclausthal.submissioninterface.persistence.dao.impl.TestResultDAO.java

License:Open Source License

@Override
public TestResult getResultLocked(Test test, Submission submission) {
    return (TestResult) getSession().createCriteria(TestResult.class).add(Restrictions.eq("test", test))
            .add(Restrictions.eq("submission", submission)).setLockMode(LockMode.UPGRADE).uniqueResult();
}

From source file:de.tuclausthal.submissioninterface.persistence.dao.impl.UserDAO.java

License:Open Source License

@Override
public User createUser(String email, String firstName, String lastName) {
    Session session = getSession();// ww  w  . j  av  a2s.  c o  m
    Transaction tx = session.beginTransaction();
    User user = (User) session.createCriteria(User.class).add(Restrictions.eq("email", email))
            .setLockMode(LockMode.UPGRADE).setMaxResults(1).uniqueResult();
    if (user == null) {
        user = new User();
        user.setFirstName(firstName);
        user.setLastName(lastName);
        user.setEmail(email);
        session.save(user);
    }
    tx.commit();
    return user;
}

From source file:de.tuclausthal.submissioninterface.persistence.dao.impl.UserDAO.java

License:Open Source License

@Override
public User createUser(String email, String firstName, String lastName, int matrikelno) {
    Session session = getSession();/*from  w  w w  . j a  v a  2s. c  o m*/
    Transaction tx = session.beginTransaction();
    User user = (User) session.createCriteria(User.class).add(Restrictions.eq("email", email))
            .setLockMode(LockMode.UPGRADE).setMaxResults(1).uniqueResult();
    if (user == null) {
        Student student = new Student();
        student.setEmail(email);
        student.setFirstName(firstName);
        student.setLastName(lastName);
        student.setMatrikelno(matrikelno);
        session.save(student);
        user = student;
    }
    tx.commit();
    return user;
}

From source file:de.tuclausthal.submissioninterface.servlets.controller.DeleteFile.java

License:Open Source License

@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    Session session = RequestAdapter.getSession(request);
    SubmissionDAOIf submissionDAO = DAOFactory.SubmissionDAOIf(session);
    Submission submission = submissionDAO.getSubmission(Util.parseInteger(request.getParameter("sid"), 0));

    ContextAdapter contextAdapter = new ContextAdapter(getServletContext());

    if (submission == null) {
        request.setAttribute("title", "Abgabe nicht gefunden");
        request.getRequestDispatcher("/" + contextAdapter.getServletsPath() + "/MessageView").forward(request,
                response);//from   w ww.j a  v  a2 s  .  com
        return;
    }

    Task task = submission.getTask();

    // check Lecture Participation
    ParticipationDAOIf participationDAO = DAOFactory.ParticipationDAOIf(session);
    Participation participation = participationDAO.getParticipation(RequestAdapter.getUser(request),
            task.getTaskGroup().getLecture());
    if (participation == null) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN, "insufficient rights");
        return;
    }

    Submission checkSubmission = submissionDAO.getSubmission(task, RequestAdapter.getUser(request));
    if (checkSubmission == null || submission.getSubmissionid() != checkSubmission.getSubmissionid()) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN, "insufficient rights");
        return;
    }

    if (task.getDeadline().before(Util.correctTimezone(new Date()))) {
        request.setAttribute("title", "Abgabe nicht mehr mglich");
        request.getRequestDispatcher("/" + contextAdapter.getServletsPath() + "/MessageView").forward(request,
                response);
        return;
    }

    if (request.getPathInfo() == null) {
        request.setAttribute("title", "Ungltige Anfrage");
        request.getRequestDispatcher("/" + contextAdapter.getServletsPath() + "/MessageView").forward(request,
                response);
        return;
    }

    File path = new File(contextAdapter.getDataPath().getAbsolutePath() + System.getProperty("file.separator")
            + task.getTaskGroup().getLecture().getId() + System.getProperty("file.separator") + task.getTaskid()
            + System.getProperty("file.separator") + submission.getSubmissionid()
            + System.getProperty("file.separator"));
    File file = new File(path, request.getPathInfo().substring(1));
    if (file.exists() && file.isFile() && file.delete()) {
        new LogDAO(session).createLogEntry(participation.getUser(), null, submission.getTask(),
                LogAction.DELETE_FILE, null, null);
        Transaction tx = session.beginTransaction();
        session.lock(submission, LockMode.UPGRADE);
        if (!submissionDAO.deleteIfNoFiles(submission, path)) {
            submission.setLastModified(new Date());
            submissionDAO.saveSubmission(submission);
        }
        tx.commit();

        response.sendRedirect(response.encodeRedirectURL(request.getContextPath() + "/"
                + contextAdapter.getServletsPath() + "/ShowTask?taskid=" + task.getTaskid()));
        return;
    }

    request.setAttribute("title", "Datei nicht gefunden");
    request.getRequestDispatcher("/" + contextAdapter.getServletsPath() + "/MessageView").forward(request,
            response);
    return;
}

From source file:de.tuclausthal.submissioninterface.servlets.controller.EditGroup.java

License:Open Source License

@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    Session session = RequestAdapter.getSession(request);
    GroupDAOIf groupDAO = DAOFactory.GroupDAOIf(session);
    Group group = groupDAO.getGroup(Util.parseInteger(request.getParameter("groupid"), 0));
    if (group == null) {
        request.setAttribute("title", "Gruppe nicht gefunden");
        request.getRequestDispatcher("MessageView").forward(request, response);
        return;//from  w  w w.j  a  v  a  2 s . co m
    }

    // check Lecture Participation
    ParticipationDAOIf participationDAO = DAOFactory.ParticipationDAOIf(session);
    Participation participation = participationDAO.getParticipation(RequestAdapter.getUser(request),
            group.getLecture());
    if (participation == null || participation.getRoleType().compareTo(ParticipationRole.TUTOR) < 0) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN, "insufficient rights");
        return;
    }

    if ("removeFromGroup".equals(request.getParameter("action"))
            && request.getParameter("participationid") != null) {
        Transaction tx = session.beginTransaction();
        Participation memberParticipation = participationDAO
                .getParticipationLocked(Util.parseInteger(request.getParameter("participationid"), 0));
        if (memberParticipation != null
                && (participation.getRoleType().compareTo(ParticipationRole.ADVISOR) == 0
                        || memberParticipation.getRoleType().compareTo(ParticipationRole.NORMAL) == 0)) {
            memberParticipation.setGroup(null);
            participationDAO.saveParticipation(memberParticipation);
        }
        tx.commit();
        response.sendRedirect(response.encodeRedirectURL(
                "ShowLecture?lecture=" + group.getLecture().getId() + "#group" + group.getGid()));
        return;
    } else if ("removeTutorFromGroup".equals(request.getParameter("action"))) {
        if (participation.getRoleType().compareTo(ParticipationRole.ADVISOR) == 0) {
            Transaction tx = session.beginTransaction();
            session.lock(group, LockMode.UPGRADE);
            Participation memberParticipation = participationDAO
                    .getParticipationLocked(Util.parseInteger(request.getParameter("participationid"), 0));
            if (memberParticipation != null) {
                group.getTutors().remove(memberParticipation);
                groupDAO.saveGroup(group);
            }
            tx.commit();
            response.sendRedirect(response.encodeRedirectURL(
                    "ShowLecture?lecture=" + group.getLecture().getId() + "#group" + group.getGid()));
            return;
        }
        response.sendError(HttpServletResponse.SC_FORBIDDEN, "insufficient rights");
        return;
    } else if ("editGroup".equals(request.getParameter("action"))) { // add member or edit group
        Transaction tx = session.beginTransaction();
        session.lock(group, LockMode.UPGRADE);
        session.lock(participation, LockMode.UPGRADE);
        if (participation.getRoleType().compareTo(ParticipationRole.ADVISOR) == 0) {
            group.setName(request.getParameter("title"));
            group.setAllowStudentsToSignup(request.getParameter("allowStudentsToSignup") != null);
            group.setAllowStudentsToQuit(request.getParameter("allowStudentsToQuit") != null);
            group.setSubmissionGroup(request.getParameter("submissionGroup") != null);
            group.setMaxStudents(Util.parseInteger(request.getParameter("maxStudents"), 0));
            groupDAO.saveGroup(group);

            // add tutors
            if (request.getParameterValues("tutors") != null
                    && request.getParameterValues("tutors").length > 0) {
                for (String newMember : request.getParameterValues("tutors")) {
                    Participation memberParticipation = participationDAO
                            .getParticipationLocked(Util.parseInteger(newMember, 0));
                    if (memberParticipation != null
                            && memberParticipation.getRoleType().compareTo(ParticipationRole.TUTOR) >= 0) {
                        group.getTutors().add(memberParticipation);
                        groupDAO.saveGroup(group);
                    }
                }
            }
        }
        if (request.getParameterValues("members") != null && request.getParameterValues("members").length > 0) {
            for (String newMember : request.getParameterValues("members")) {
                Participation memberParticipation = participationDAO
                        .getParticipationLocked(Util.parseInteger(newMember, 0));
                if (memberParticipation != null
                        && memberParticipation.getRoleType().compareTo(ParticipationRole.NORMAL) == 0) {
                    memberParticipation.setGroup(group);
                    participationDAO.saveParticipation(memberParticipation);
                }
            }
        }
        tx.commit();
        response.sendRedirect(response.encodeRedirectURL(
                "ShowLecture?lecture=" + group.getLecture().getId() + "#group" + group.getGid()));
        return;
    }

    request.setAttribute("participation", participation);
    request.setAttribute("group", group);
    request.getRequestDispatcher("EditGroupFormView").forward(request, response);
}

From source file:de.tuclausthal.submissioninterface.servlets.controller.PublishGrades.java

License:Open Source License

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    Session session = RequestAdapter.getSession(request);

    TaskDAOIf taskDAO = DAOFactory.TaskDAOIf(session);
    Task task = taskDAO.getTask(Util.parseInteger(request.getParameter("taskid"), 0));
    if (task == null) {
        request.setAttribute("title", "Aufgabe nicht gefunden");
        request.getRequestDispatcher("MessageView").forward(request, response);
        return;//from  www.  j a v  a  2s .c  om
    }

    // check Lecture Participation
    ParticipationDAOIf participationDAO = DAOFactory.ParticipationDAOIf(session);
    Participation participation = participationDAO.getParticipation(RequestAdapter.getUser(request),
            task.getTaskGroup().getLecture());
    if (participation == null || participation.getRoleType().compareTo(ParticipationRole.ADVISOR) != 0) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN, "insufficient rights");
        return;
    }

    if (task.getDeadline().after(Util.correctTimezone(new Date())) || task.getShowPoints() != null) {
        request.setAttribute("title", "Ungltige Anfrage");
        request.getRequestDispatcher("MessageView").forward(request, response);
        return;
    }

    Transaction tx = session.beginTransaction();
    session.lock(task, LockMode.UPGRADE);
    if (request.getParameter("mail") != null) {
        for (Submission submission : task.getSubmissions()) {
            for (Participation submitterParticipation : submission.getSubmitters()) {
                if (submission.getPoints() != null && submission.getPoints().getPointsOk()) {
                    // HACK hardcoded URL
                    MailSender.sendMail(submitterParticipation.getUser().getFullEmail(), "Bewertung erfolgt",
                            "Hallo " + submitterParticipation.getUser().getFullName()
                                    + ",\n\neine Ihrer Abgaben wurde bewertet.\n\nEinsehen: <https://si.in.tu-clausthal.de/submissionsystem/servlets/ShowTask?taskid="
                                    + task.getTaskid() + ">.\n\n-- \nReply is not possible.");
                }
            }
        }
    }
    task.setShowPoints(task.getDeadline());
    session.saveOrUpdate(task);
    tx.commit();

    response.sendRedirect(response.encodeRedirectURL("ShowTask?taskid=" + task.getTaskid()));
}

From source file:de.tuclausthal.submissioninterface.servlets.controller.TaskManager.java

License:Open Source License

@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    Session session = RequestAdapter.getSession(request);
    Lecture lecture = DAOFactory.LectureDAOIf(session)
            .getLecture(Util.parseInteger(request.getParameter("lecture"), 0));
    if (lecture == null) {
        request.setAttribute("title", "Veranstaltung nicht gefunden");
        request.getRequestDispatcher("MessageView").forward(request, response);
        return;//from w  w  w  .  jav a 2s  . c  o m
    }

    ParticipationDAOIf participationDAO = DAOFactory.ParticipationDAOIf(session);
    Participation participation = participationDAO.getParticipation(RequestAdapter.getUser(request), lecture);
    if (participation == null || participation.getRoleType() != ParticipationRole.ADVISOR) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN, "insufficient rights");
        return;
    }

    if (request.getParameter("action") != null && ((request.getParameter("action").equals("editTask")
            && request.getParameter("taskid") != null)
            || (request.getParameter("action").equals("newTask") && request.getParameter("lecture") != null))) {
        boolean editTask = request.getParameter("action").equals("editTask");
        Task task;
        if (editTask == true) {
            TaskDAOIf taskDAO = DAOFactory.TaskDAOIf(session);
            task = taskDAO.getTask(Util.parseInteger(request.getParameter("taskid"), 0));
            if (task == null) {
                request.setAttribute("title", "Aufgabe nicht gefunden");
                request.getRequestDispatcher("MessageView").forward(request, response);
                return;
            }
        } else {
            if (lecture.getTaskGroups().size() == 0) {
                request.setAttribute("title", "Es wurde noch keine Aufgabengruppe angelegt");
                request.getRequestDispatcher("MessageView").forward(request, response);
                return;
            }
            // temp. Task for code-reuse
            task = new Task();
            task.setStart(new Date());
            task.setDeadline(new Date(new Date().getTime() + 3600 * 24 * 7 * 1000));
            task.setShowPoints(task.getDeadline());
            task.setTaskGroup(lecture.getTaskGroups().get(lecture.getTaskGroups().size() - 1));
        }

        request.setAttribute("task", task);
        request.setAttribute("advisorFiles", Util.listFilesAsRelativeStringList(
                new File(new ContextAdapter(getServletContext()).getDataPath().getAbsolutePath()
                        + System.getProperty("file.separator") + task.getTaskGroup().getLecture().getId()
                        + System.getProperty("file.separator") + task.getTaskid()
                        + System.getProperty("file.separator") + "advisorfiles"
                        + System.getProperty("file.separator"))));
        request.getRequestDispatcher("TaskManagerView").forward(request, response);
    } else if (request.getParameter("action") != null && (request.getParameter("action").equals("saveNewTask")
            || request.getParameter("action").equals("saveTask"))) {
        TaskDAOIf taskDAO = DAOFactory.TaskDAOIf(session);
        TaskGroup taskGroup = DAOFactory.TaskGroupDAOIf(session)
                .getTaskGroup(Util.parseInteger(request.getParameter("taskGroup"), 0));
        if (taskGroup == null) {
            request.setAttribute("title", "Aufgabengruppe nicht gefunden");
            request.getRequestDispatcher("MessageView").forward(request, response);
        }
        Task task;
        if (request.getParameter("action").equals("saveTask")) {
            task = taskDAO.getTask(Util.parseInteger(request.getParameter("taskid"), 0));
            if (task == null) {
                request.setAttribute("title", "Aufgabe nicht gefunden");
                request.getRequestDispatcher("MessageView").forward(request, response);
                return;
            }
            task.setMinPointStep(Util.convertToPoints(request.getParameter("minpointstep")));
            if (task.getPointCategories().size() == 0) {
                task.setMaxPoints(
                        Util.convertToPoints(request.getParameter("maxpoints"), task.getMinPointStep()));
            }
            task.setTitle(request.getParameter("title").trim());
            task.setDescription(request.getParameter("description"));
            task.setMaxSubmitters(Util.parseInteger(request.getParameter("maxSubmitters"), 1));
            task.setAllowSubmittersAcrossGroups(request.getParameter("allowSubmittersAcrossGroups") != null);
            task.setFilenameRegexp(request.getParameter("filenameregexp"));
            task.setArchiveFilenameRegexp(request.getParameter("archivefilenameregexp"));
            task.setFeaturedFiles(request.getParameter("featuredfiles"));
            task.setShowTextArea(request.getParameter("showtextarea") != null);
            task.setTutorsCanUploadFiles(request.getParameter("tutorsCanUploadFiles") != null);
            task.setStart(parseDate(request.getParameter("startdate"), new Date()));
            task.setDeadline(parseDate(request.getParameter("deadline"), new Date()));
            if (task.getDeadline().before(task.getStart())) {
                task.setDeadline(task.getStart());
            }
            if (request.getParameter("pointsmanual") != null) {
                task.setShowPoints(null);
            } else {
                task.setShowPoints(parseDate(request.getParameter("pointsdate"), new Date()));
                if (task.getShowPoints().before(task.getDeadline())) {
                    task.setShowPoints(task.getDeadline());
                }
            }
            task.setTaskGroup(taskGroup);
            taskDAO.saveTask(task);
            if (request.getParameter("dynamictaskpreview") != null) {
                response.sendRedirect(response
                        .encodeRedirectURL("TaskManager?lecture=" + task.getTaskGroup().getLecture().getId()
                                + "&taskid=" + task.getTaskid() + "&action=dynamictaskpreview"));
            } else {
                response.sendRedirect(response.encodeRedirectURL("ShowTask?taskid=" + task.getTaskid()));
            }
        } else {
            Date startdate = parseDate(request.getParameter("startdate"), new Date());
            Date deadline = parseDate(request.getParameter("deadline"), new Date());
            Date pointsdate = parseDate(request.getParameter("pointsdate"), new Date());
            if (deadline.before(startdate)) {
                deadline = startdate;
            }
            Date showPoints = parseDate(request.getParameter("pointsdate"), new Date());
            if (showPoints.before(deadline)) {
                showPoints = deadline;
            }
            if (request.getParameter("pointsmanual") != null) {
                pointsdate = null;
            } else if (pointsdate.before(deadline)) {
                pointsdate = deadline;
            }
            String dynamicTask = null;
            if (DynamicTaskStrategieFactory.IsValidStrategieName(request.getParameter("dynamicTask"))) {
                dynamicTask = request.getParameter("dynamicTask");
            }
            task = taskDAO.newTask(request.getParameter("title"),
                    Util.convertToPoints(request.getParameter("maxpoints"),
                            Util.convertToPoints(request.getParameter("minpointstep"))),
                    Util.convertToPoints(request.getParameter("minpointstep")), startdate, deadline,
                    request.getParameter("description"), taskGroup, showPoints,
                    request.getParameter("filenameregexp"), request.getParameter("archivefilenameregexp"),
                    request.getParameter("showtextarea") != null, request.getParameter("featuredfiles"),
                    request.getParameter("tutorsCanUploadFiles") != null,
                    Util.parseInteger(request.getParameter("maxSubmitters"), 1),
                    request.getParameter("allowSubmittersAcrossGroups") != null, dynamicTask, pointsdate);
            response.sendRedirect(
                    response.encodeRedirectURL("TaskManager?lecture=" + task.getTaskGroup().getLecture().getId()
                            + "&taskid=" + task.getTaskid() + "&action=editTask"));
        }
        return;
    } else if ("deleteTask".equals(request.getParameter("action"))) {
        TaskDAOIf taskDAO = DAOFactory.TaskDAOIf(session);
        Task task = taskDAO.getTask(Util.parseInteger(request.getParameter("taskid"), 0));
        if (task == null) {
            request.setAttribute("title", "Aufgabe nicht gefunden");
            request.getRequestDispatcher("MessageView").forward(request, response);
        } else {
            taskDAO.deleteTask(task);
        }
        response.sendRedirect(response.encodeRedirectURL("ShowLecture?lecture=" + lecture.getId()));
        return;
    } else if ("dynamictaskpreview".equals(request.getParameter("action"))) {
        TaskDAOIf taskDAO = DAOFactory.TaskDAOIf(session);
        Task task = taskDAO.getTask(Util.parseInteger(request.getParameter("taskid"), 0));
        if (task == null) {
            request.setAttribute("title", "Aufgabe nicht gefunden");
            request.getRequestDispatcher("MessageView").forward(request, response);
            return;
        }
        if (!task.isADynamicTask()) {
            request.setAttribute("title", "Aufgabe ist keine dynamische Aufgabe");
            request.getRequestDispatcher("MessageView").forward(request, response);
            return;
        }

        DynamicTaskStrategieIf dts = task.getDynamicTaskStrategie(session);
        List<TaskNumber> taskNumbers = dts.getVariables((Participation) null);
        List<String> correctResults = dts.getCorrectResults(taskNumbers, true);

        task.setDescription(dts.getTranslatedDescription(taskNumbers));
        request.setAttribute("task", task);
        request.setAttribute("variableNames", dts.getVariableNames());
        request.setAttribute("taskNumbers", taskNumbers);
        request.setAttribute("correctResults", correctResults);
        request.setAttribute("resultFields", dts.getResultFields(true));

        request.getRequestDispatcher("TaskManagerDynamicTaskPreView").forward(request, response);
    } else if ("uploadTaskFile".equals(request.getParameter("action"))) {
        Template template = TemplateFactory.getTemplate(request, response);
        PrintWriter out = response.getWriter();

        TaskDAOIf taskDAO = DAOFactory.TaskDAOIf(session);
        Task task = taskDAO.getTask(Util.parseInteger(request.getParameter("taskid"), 0));
        if (task == null) {
            request.setAttribute("title", "Aufgabe nicht gefunden");
            request.getRequestDispatcher("MessageView").forward(request, response);
        }
        ContextAdapter contextAdapter = new ContextAdapter(getServletContext());

        File path = new File(contextAdapter.getDataPath().getAbsolutePath()
                + System.getProperty("file.separator") + task.getTaskGroup().getLecture().getId()
                + System.getProperty("file.separator") + task.getTaskid() + System.getProperty("file.separator")
                + "advisorfiles" + System.getProperty("file.separator"));
        if (path.exists() == false) {
            path.mkdirs();
        }

        Part file = request.getPart("file");
        if (file == null) {
            request.setAttribute("title", "Keine Datei gefunden.");
            request.getRequestDispatcher("MessageView").forward(request, response);
            return;
        }
        // Process a file upload
        Pattern pattern = Pattern.compile("^(?:.*?[\\\\/])?([a-zA-Z0-9_. -]+)$");
        StringBuffer submittedFileName = new StringBuffer(Util.getUploadFileName(file));
        Util.lowerCaseExtension(submittedFileName);
        Matcher m = pattern.matcher(submittedFileName);
        if (!m.matches()) {
            System.out.println("SubmitSolutionProblem2: file;" + submittedFileName + ";" + pattern.pattern());
            template.printTemplateHeader("Ungltige Anfrage");
            out.println(
                    "Dateiname ungltig bzw. entspricht nicht der Vorgabe (ist ein Klassenname vorgegeben, so muss die Datei genauso heien).<br>Tipp: Nur A-Z, a-z, 0-9, ., - und _ sind erlaubt.");
            template.printTemplateFooter();
            return;
        }
        String fileName = m.group(1);

        File uploadedFile = new File(path, fileName);
        Util.copyInputStreamAndClose(file.getInputStream(),
                new BufferedOutputStream(new FileOutputStream(uploadedFile)));

        response.sendRedirect(response.encodeRedirectURL("TaskManager?lecture="
                + task.getTaskGroup().getLecture().getId() + "&action=editTask&taskid=" + task.getTaskid()));
    } else if ((("editTaskGroup".equals(request.getParameter("action"))
            && request.getParameter("taskgroupid") != null)
            || (request.getParameter("action").equals("newTaskGroup")
                    && request.getParameter("lecture") != null))) {
        boolean editTaskGroup = request.getParameter("action").equals("editTaskGroup");
        TaskGroup taskGroup;
        if (editTaskGroup == true) {
            TaskGroupDAOIf taskDAO = DAOFactory.TaskGroupDAOIf(session);
            taskGroup = taskDAO.getTaskGroup(Util.parseInteger(request.getParameter("taskgroupid"), 0));
            if (taskGroup == null) {
                request.setAttribute("title", "Aufgabengruppe nicht gefunden");
                request.getRequestDispatcher("MessageView").forward(request, response);
                return;
            }
        } else {
            // temp. Task for code-reuse
            taskGroup = new TaskGroup();
            taskGroup.setLecture(lecture);
        }
        request.setAttribute("taskGroup", taskGroup);
        request.getRequestDispatcher("TaskGroupManagerView").forward(request, response);
    } else if (("saveNewTaskGroup".equals(request.getParameter("action"))
            || "saveTaskGroup".equals(request.getParameter("action")))) {
        TaskGroupDAOIf taskGroupDAO = DAOFactory.TaskGroupDAOIf(session);
        TaskGroup taskGroup;
        if (request.getParameter("action").equals("saveTaskGroup")) {
            taskGroup = taskGroupDAO.getTaskGroup(Util.parseInteger(request.getParameter("taskgroupid"), 0));
            if (taskGroup == null) {
                request.setAttribute("title", "Aufgabengruppe nicht gefunden");
                request.getRequestDispatcher("MessageView").forward(request, response);
                return;
            }
            taskGroup.setTitle(request.getParameter("title"));
            Transaction tx = session.beginTransaction();
            taskGroupDAO.saveTaskGroup(taskGroup);
            tx.commit();
        } else {
            Transaction tx = session.beginTransaction();
            taskGroupDAO.newTaskGroup(request.getParameter("title"), lecture);
            tx.commit();
        }
        response.sendRedirect(response.encodeRedirectURL("ShowLecture?lecture=" + lecture.getId()));
        return;
    } else if ("deleteTaskGroup".equals(request.getParameter("action"))) {
        TaskGroupDAOIf taskGroupDAO = DAOFactory.TaskGroupDAOIf(session);
        TaskGroup taskGroup = taskGroupDAO
                .getTaskGroup(Util.parseInteger(request.getParameter("taskgroupid"), 0));
        if (taskGroup == null) {
            request.setAttribute("title", "Aufgabengruppe nicht gefunden");
            request.getRequestDispatcher("MessageView").forward(request, response);
        } else {
            Transaction tx = session.beginTransaction();
            taskGroupDAO.deleteTaskGroup(taskGroup);
            tx.commit();
        }
        response.sendRedirect(response.encodeRedirectURL("ShowLecture?lecture=" + lecture.getId()));
        return;
    } else if ("deletePointCategory".equals(request.getParameter("action"))) {
        PointCategoryDAOIf pointCategoryDAO = DAOFactory.PointCategoryDAOIf(session);
        PointCategory pointCategory = pointCategoryDAO
                .getPointCategory(Util.parseInteger(request.getParameter("pointCategoryId"), 0));
        if (pointCategory == null) {
            request.setAttribute("title", "Punktkategorie nicht gefunden");
            request.getRequestDispatcher("MessageView").forward(request, response);
        } else {
            Transaction tx = session.beginTransaction();
            // TODO make nice! and use DAOs
            Task task = pointCategory.getTask();
            session.lock(task, LockMode.UPGRADE);
            pointCategoryDAO.deletePointCategory(pointCategory);
            task.setMaxPoints(pointCategoryDAO.countPoints(task));
            session.update(task);
            tx.commit();
        }
        response.sendRedirect(response.encodeRedirectURL(
                "TaskManager?lecture=" + pointCategory.getTask().getTaskGroup().getLecture().getId()
                        + "&action=editTask&taskid=" + pointCategory.getTask().getTaskid()));
        return;
    } else if ("newPointCategory".equals(request.getParameter("action"))) {
        PointCategoryDAOIf pointCategoryDAO = DAOFactory.PointCategoryDAOIf(session);
        TaskDAOIf taskDAO = DAOFactory.TaskDAOIf(session);
        Task task = taskDAO.getTask(Util.parseInteger(request.getParameter("taskid"), 0));
        if (task == null) {
            request.setAttribute("title", "Aufgabe nicht gefunden");
            request.getRequestDispatcher("MessageView").forward(request, response);
        }
        if (Util.convertToPoints(request.getParameter("points"), task.getMinPointStep()) > 0) {
            // TODO make nice! and use DAOs
            Transaction tx = session.beginTransaction();
            session.lock(task, LockMode.UPGRADE);
            pointCategoryDAO.newPointCategory(task, Util.convertToPoints(request.getParameter("points")),
                    request.getParameter("description"), request.getParameter("optional") != null);
            task.setMaxPoints(pointCategoryDAO.countPoints(task));
            session.update(task);
            tx.commit();
            response.sendRedirect(response.encodeRedirectURL(
                    "TaskManager?lecture=" + lecture.getId() + "&action=editTask&taskid=" + task.getTaskid()));
        } else {
            request.setAttribute("title", "Punkte ungltig.");
            request.getRequestDispatcher("MessageView").forward(request, response);
        }
        return;
    } else {
        request.setAttribute("title", "Ungltiger Aufruf");
        request.getRequestDispatcher("MessageView").forward(request, response);

    }
}

From source file:es.sm2.openppm.utils.hibernate.dao.AbstractGenericHibernateDAO.java

License:Open Source License

/********************************************/

@SuppressWarnings("unchecked")
public T findById(ID id, boolean lock) {
    T entity;//w  ww .j a  v  a2 s .co m
    if (lock) {
        entity = (T) getSession().get(getPersistentClass(), id, LockMode.UPGRADE);
    } else {
        entity = (T) getSession().get(getPersistentClass(), id);
    }
    return entity;
}

From source file:hibernate.GenericHibernateDAO.java

@SuppressWarnings("unchecked")
public T findById(ID id, boolean lock) {
    T entity;/*from  www  . j  ava 2  s. c om*/
    if (lock)
        //entity = (T) getSession().load(getPersistentClass(), id, LockMode.UPGRADE);
        entity = (T) getSession().get(getPersistentClass(), id, LockMode.UPGRADE);
    else
        //entity = (T) getSession().load(getPersistentClass(), id);
        entity = (T) getSession().get(getPersistentClass(), id);
    return entity;
}