Example usage for org.hibernate Session lock

List of usage examples for org.hibernate Session lock

Introduction

In this page you can find the example usage for org.hibernate Session lock.

Prototype

void lock(Object object, LockMode lockMode);

Source Link

Document

Obtain the specified lock level upon the given object.

Usage

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

License:Open Source License

@Override
public Points createPoints(Map<String, String[]> pointGiven, Submission submission, Participation participation,
        String publicComment, String internalComment, PointStatus pointStatus, Integer duplicate) {
    Session session = getSession();

    session.lock(submission, LockMode.UPGRADE);
    session.lock(submission.getTask(), LockMode.UPGRADE);

    boolean changed = false;

    // implement hacky solution since this will be a short list ;)
    PointGivenDAOIf pointGivenDAO = DAOFactory.PointGivenDAOIf(session);
    Iterator<PointGiven> pointsGivenIterator = pointGivenDAO.getPointsGivenOfSubmission(submission).iterator();
    PointGiven lastPointGiven = null;/*from   w ww  . j a v  a2 s.  c o  m*/
    if (pointsGivenIterator.hasNext()) {
        lastPointGiven = pointsGivenIterator.next();
    }
    int numPoints = 0;
    for (PointCategory category : submission.getTask().getPointCategories()) {
        while (lastPointGiven != null
                && category.getPointcatid() > lastPointGiven.getCategory().getPointcatid()) {
            if (pointsGivenIterator.hasNext()) {
                lastPointGiven = pointsGivenIterator.next();
            } else {
                lastPointGiven = null;
                break;
            }
        }
        int issuedPoints = 0;
        if (pointGiven.get("point_" + category.getPointcatid()) != null) {
            issuedPoints = Util.convertToPoints(pointGiven.get("point_" + category.getPointcatid())[0],
                    submission.getTask().getMinPointStep());
        }
        if (issuedPoints > category.getPoints()) {
            issuedPoints = category.getPoints();
        }
        if (lastPointGiven != null
                && category.getPointcatid() == lastPointGiven.getCategory().getPointcatid()) {
            if (issuedPoints == 0) {
                storeInHistory(submission, category.getDescription(),
                        Util.showPoints(lastPointGiven.getPoints()), "0", participation);
                pointGivenDAO.revokePointGiven(lastPointGiven);
                changed = true;
            } else {
                if (issuedPoints != lastPointGiven.getPoints()) {
                    storeInHistory(submission, category.getDescription(),
                            Util.showPoints(lastPointGiven.getPoints()), Util.showPoints(issuedPoints),
                            participation);
                    pointGivenDAO.revokePointGiven(lastPointGiven);
                    pointGivenDAO.givePoint(issuedPoints, submission, category);
                    changed = true;
                }
                numPoints += issuedPoints;
            }
        } else {
            if (issuedPoints > 0) {
                numPoints += issuedPoints;
                storeInHistory(submission, category.getDescription(), "0", Util.showPoints(issuedPoints),
                        participation);
                pointGivenDAO.givePoint(issuedPoints, submission, category);
                changed = true;
            }
        }
    }

    Points oldPoints = submission.getPoints();
    Points points = new Points();
    points.setPoints(numPoints);
    points.setPointStatus(pointStatus);
    points.setDuplicate(duplicate);
    points.setIssuedBy(participation);
    submission.setPoints(points);
    points.setPublicComment(publicComment);
    points.setInternalComment(internalComment);
    session.save(submission);

    // TODO: Attention: see @MarkApproved.java
    if (oldPoints != null) {
        if (!oldPoints.getPointStatus().equals(points.getPointStatus())) {
            storeInHistory(submission, "status", PointStatus.values()[oldPoints.getPointStatus()].toString(),
                    PointStatus.values()[points.getPointStatus()].toString(), participation);
            if (!((oldPoints.getPointStatus() == PointStatus.NICHT_ABGENOMMEN.ordinal()
                    && points.getPointStatus() == PointStatus.ABGENOMMEN.ordinal())
                    || (oldPoints.getPointStatus() == PointStatus.NICHT_ABGENOMMEN.ordinal()
                            && points.getPointStatus() == PointStatus.ABGENOMMEN_FAILED.ordinal()))) {
                changed = true;
            }
        }
        if (oldPoints.getDuplicate() != null || points.getDuplicate() != null) {
            if (oldPoints.getDuplicate() == null) {
                storeInHistory(submission, "duplicate", "", points.getDuplicate() + "", participation);
                changed = true;
            } else if (points.getDuplicate() == null) {
                storeInHistory(submission, "duplicate", oldPoints.getDuplicate() + "", "", participation);
                changed = true;
            } else if (!oldPoints.getDuplicate().equals(points.getDuplicate())) {
                storeInHistory(submission, "duplicate", oldPoints.getDuplicate() + "",
                        points.getDuplicate() + "", participation);
                changed = true;
            }
        }
        if (!oldPoints.getPoints().equals(points.getPoints())) {
            storeInHistory(submission, "points", Util.showPoints(oldPoints.getPoints()),
                    Util.showPoints(points.getPoints()), participation);
            changed = true;
        }
        if (oldPoints.getInternalComment() != null
                && !oldPoints.getInternalComment().equals(points.getInternalComment())) {
            storeInHistory(submission, "internalComment", oldPoints.getInternalComment(),
                    points.getInternalComment(), participation);
            changed = true;
        }
        if (oldPoints.getPublicComment() != null
                && !oldPoints.getPublicComment().equals(points.getPublicComment())) {
            storeInHistory(submission, "publicComment", oldPoints.getPublicComment(), points.getPublicComment(),
                    participation);
            changed = true;
        }
        if (changed && oldPoints.getIssuedBy().getUser().getUid() != participation.getUser().getUid()) {
            // HACK hardcoded URL
            MailSender.sendMail(oldPoints.getIssuedBy().getUser().getFullEmail(), "Mark-Change Notification",
                    "Hallo,\n\n" + participation.getUser().getFullName()
                            + " hat Deine Bewertung von <https://si.in.tu-clausthal.de/submissionsystem/servlets/ShowSubmission?sid="
                            + submission.getSubmissionid() + "> verndert.\n\n-- \nReply is not possible.");
        }
    } else {
        if (points.getPointStatus() != null) {
            storeInHistory(submission, "status", "", PointStatus.values()[points.getPointStatus()].toString(),
                    participation);
        }
        if (points.getDuplicate() != null) {
            storeInHistory(submission, "duplicate", "", points.getDuplicate() + "", participation);
        }
        if (points.getPoints() != null) {
            storeInHistory(submission, "points", "", Util.showPoints(points.getPoints()), participation);
        }
        if (points.getInternalComment() != null && !"".equals(points.getInternalComment())) {
            storeInHistory(submission, "internalComment", "", points.getInternalComment(), participation);
        }
        if (points.getPublicComment() != null && !"".equals(points.getPublicComment())) {
            storeInHistory(submission, "publicComment", "", points.getPublicComment(), participation);
        }
    }
    return points;
}

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

License:Open Source License

@Override
public boolean deleteIfNoFiles(Submission submission, File submissionPath) {
    Session session = getSession();
    session.lock(submission, LockMode.UPGRADE);
    boolean result = false;
    Util.recursiveDeleteEmptySubDirectories(submissionPath);
    if (submissionPath.listFiles().length == 0 && submissionPath.delete()) {
        session.delete(submission);//  w w  w. ja va 2  s .  c  o  m
        result = true;
    }
    return result;
}

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.  c  o  m
        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 ww . ja v a2 s.c  o  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;//  w w  w .j av  a  2s  .  c  o m
    }

    // 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:de.tudarmstadt.ukp.wikipedia.api.Category.java

License:Apache License

/**
 * This returns the internal id. Do not confuse this with the pageId.
 * @return Returns the internal id./*from   ww w. ja  v  a 2  s  . c  o  m*/
 */
public long __getId() {
    Session session = this.wiki.__getHibernateSession();
    session.beginTransaction();
    session.lock(hibernateCategory, LockMode.NONE);
    long id = hibernateCategory.getId();
    session.getTransaction().commit();
    return id;
}

From source file:de.tudarmstadt.ukp.wikipedia.api.Category.java

License:Apache License

/**
 * Returns a unique page id./*from w  w  w. j  a v  a  2  s.  c  om*/
 * @return A unique page id.
 */
public int getPageId() {
    Session session = this.wiki.__getHibernateSession();
    session.beginTransaction();
    session.lock(hibernateCategory, LockMode.NONE);
    int pageID = hibernateCategory.getPageId();
    session.getTransaction().commit();
    return pageID;
}

From source file:de.tudarmstadt.ukp.wikipedia.api.Category.java

License:Apache License

/**
 * Returns a set containing parents (supercategories) of this category.
 * @return A set containing parents (supercategories) of this category.
 *//* w w w  .ja  va 2  s .  c  o m*/
public Set<Category> getParents() {
    Session session = this.wiki.__getHibernateSession();
    session.beginTransaction();
    session.lock(hibernateCategory, LockMode.NONE);
    Set<Integer> tmpSet = new HashSet<Integer>(hibernateCategory.getInLinks());
    session.getTransaction().commit();

    Set<Category> categories = new HashSet<Category>();
    for (int pageID : tmpSet) {
        categories.add(this.wiki.getCategory(pageID));
    }
    return categories;
}

From source file:de.tudarmstadt.ukp.wikipedia.api.Category.java

License:Apache License

/**
 * @return A set containing the IDs of the parents of this category.
 *//*  w ww . j av a 2 s. c om*/
public Set<Integer> getParentIDs() {
    Session session = this.wiki.__getHibernateSession();
    session.beginTransaction();
    session.lock(hibernateCategory, LockMode.NONE);
    Set<Integer> tmpSet = new HashSet<Integer>(hibernateCategory.getInLinks());
    session.getTransaction().commit();
    return tmpSet;
}