Example usage for java.util Hashtable isEmpty

List of usage examples for java.util Hashtable isEmpty

Introduction

In this page you can find the example usage for java.util Hashtable isEmpty.

Prototype

public synchronized boolean isEmpty() 

Source Link

Document

Tests if this hashtable maps no keys to values.

Usage

From source file:com.concursive.connect.web.webdav.servlets.WebdavServlet.java

/**
 * Delete a resource.//from   ww  w.ja v a  2s . com
 *
 * @param path      Path of the resource which is to be deleted
 * @param req       Servlet request
 * @param resp      Servlet response
 * @param setStatus Should the response status be set on
 *                  successful completion
 * @return Description of the Return Value
 * @throws javax.servlet.ServletException Description of the Exception
 * @throws java.io.IOException            Description of the Exception
 */
private boolean deleteResource(String path, HttpServletRequest req, HttpServletResponse resp, boolean setStatus)
        throws ServletException, IOException {

    if ((path.toUpperCase().startsWith("/WEB-INF")) || (path.toUpperCase().startsWith("/META-INF"))) {
        resp.sendError(WebdavStatus.SC_FORBIDDEN);
        return false;
    }

    String ifHeader = req.getHeader("If");
    if (ifHeader == null) {
        ifHeader = "";
    }

    String lockTokenHeader = req.getHeader("Lock-Token");
    if (lockTokenHeader == null) {
        lockTokenHeader = "";
    }

    if (isLocked(path, ifHeader + lockTokenHeader)) {
        resp.sendError(WebdavStatus.SC_LOCKED);
        return false;
    }

    // Retrieve the resources
    DirContext resources = getResources();

    if (resources == null) {
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return false;
    }

    boolean exists = true;
    Object object = null;
    try {
        object = resources.lookup(path);
    } catch (NamingException e) {
        exists = false;
    }

    if (!exists) {
        resp.sendError(WebdavStatus.SC_NOT_FOUND);
        return false;
    }

    boolean collection = (object instanceof DirContext);

    if (!collection) {
        try {
            resources.unbind(path);
        } catch (NamingException e) {
            resp.sendError(WebdavStatus.SC_INTERNAL_SERVER_ERROR);
            return false;
        }
    } else {

        Hashtable errorList = new Hashtable();

        deleteCollection(req, resources, path, errorList);
        try {
            resources.unbind(path);
        } catch (NamingException e) {
            errorList.put(path, new Integer(WebdavStatus.SC_INTERNAL_SERVER_ERROR));
        }

        if (!errorList.isEmpty()) {

            sendReport(req, resp, errorList);
            return false;
        }
    }
    if (setStatus) {
        resp.setStatus(WebdavStatus.SC_NO_CONTENT);
    }
    return true;
}

From source file:com.crushpaper.DbLogic.java

/**
 * API method. Starts its own transaction. Returns true if the DB is
 * internally consistent. If this returns true then either: 1) there is a
 * bug in the application code, 2) there is a bug in the DB code, 3) the DB
 * was tampered with by another application 4) the DB has been corrupted.
 *//* w ww  . j av  a  2  s  .  co m*/
public boolean hasErrors(Errors errors) {
    if (errors == null)
        return false;

    // Iterate over all entries.
    List<?> entries = getAllEntries();
    for (Object entryUncasted : entries) {
        Entry entry = (Entry) entryUncasted;

        // Make sure it has an id.
        final String id = entry.getId();
        if (id == null || id.isEmpty()) {
            errors.add(errorMessages.errorDbTheEntryHadNoId());
            continue;
        }

        final String userId = entry.getUserId();
        if (userId == null || userId.isEmpty()) {
            errors.add(errorMessages.errorDbTheEntryIsRelatedTheWrongNumberOfUsers(id, 0));
            continue;
        }

        // Make sure it is linked to a user.
        User user = getUserById(userId);
        if (user == null) {
            errors.add(errorMessages.errorDbTheEntryIsRelatedTheWrongNumberOfUsers(id, 0));
            continue;
        }

        Entry parent = getEntryById(entry.getParentId());

        // If it has a parent id that parent must be linked.
        if (entry.hasParentId() && parent == null) {
            errors.add(
                    errorMessages.errorDbTheEntryAParentIdButNoParentRelationship(entry.getParentId(""), id));
        }

        // If it has a first child id then last child id must be set.
        if (entry.hasLastChildId() && !entry.hasFirstChildId()) {
            errors.add(errorMessages.errorDbTheEntryHasALastChildIdButNoFirstChildId(entry.getLastChildId(""),
                    id));
        }

        // If it has a last child id then first child id must be set.
        if (entry.hasFirstChildId() && !entry.hasLastChildId()) {
            errors.add(errorMessages.errorDbTheEntryHasAFirstChildIdButNoLastChildId(entry.getFirstChildId(""),
                    id));
        }

        // If the parent's lastChildId is this then this entry may have
        // no nextSiblingId.
        if (parent != null && parent.getLastChildId("").equals(id) && entry.hasNextSiblingId()) {
            errors.add(errorMessages.errorDbTheEntryIsTheParentsLastChildButHasANextSibling(id));
        }

        // If the parent's firstChildId is this then this entry may have
        // no previousSiblingId.
        if (parent != null && parent.getFirstChildId("").equals(id) && entry.hasPreviousSiblingId()) {
            errors.add(errorMessages.errorDbTheEntryIsTheParentsFirstChildButHasAPreviousSibling(id));
        }

        final Hashtable<String, Entry> children = new Hashtable<String, Entry>();
        Entry firstChild = null;
        for (Object objectChild : getEntriesByParentId(entry.getId())) {
            Entry child = (Entry) objectChild;
            children.put(child.getId(), child);
            if (!child.hasPreviousSiblingId()) {
                if (firstChild != null) {
                    errors.add(errorMessages.errorDbTheEntryHasMoreThanOneChildWithoutAPreviousSiblingId(id));
                }

                firstChild = child;
            }
        }

        // Make sure first child is is consistent.
        if (entry.hasFirstChildId() && children.isEmpty()) {
            errors.add(errorMessages.errorDbTheEntryHasAFirstChildIdButNoChildren(id));
        }

        if (!entry.hasFirstChildId() && !children.isEmpty()) {
            errors.add(errorMessages.errorDbTheEntryHasAFirstChildIdButNoChildren(id));
        }

        if (!children.isEmpty()) {
            if (firstChild == null) {
                errors.add(errorMessages.errorDbTheEntryHasNoChildWithoutAPreviousSiblingId(id));
            } else {
                if (!firstChild.getId("").equals(entry.getFirstChildId(""))) {
                    errors.add(errorMessages.errorDbTheEntryHasAChildWithoutAPreviousSiblingId(id));
                }
            }

            Entry child = firstChild;
            Entry lastChild = null;
            int i = 0;
            for (; i < children.size(); ++i) {
                if (child == null) {
                    break;
                }

                if (!child.hasNextSiblingId()) {
                    lastChild = child;
                    break;
                }

                final String previousId = child.getId("");

                final String nextId = child.getNextSiblingId();
                child = children.get(nextId);
                if (child == null) {
                    errors.add(errorMessages.errorDbTheEntryHasAChildWithASiblingThatIsNotRelated(id, nextId));
                } else if (!child.getPreviousSiblingId("").equals(previousId)) {
                    errors.add(errorMessages.errorDbTheEntryHasAChildWhosePreviousDoesNotMatch(id,
                            child.getPreviousSiblingId(""), previousId));
                }
            }

            if (i != children.size() - 1) {
                errors.add(errorMessages.errorDbTheEntryHasExtraChildren(id, children.size() - i));
            }

            if (lastChild == null) {
                errors.add(errorMessages.errorDbTheEntryHasNoChildrenWithoutANextSiblingId(id));
            } else {
                if (!lastChild.getId("").equals(entry.getLastChildId(""))) {
                    errors.add(errorMessages.errorDbTheEntryHasAChildWithoutANextSiblingIdThatIsNotItsLastChild(
                            id, lastChild.getId("")));
                }
            }
        }
    }

    return errors.hasErrors();
}

From source file:org.unitime.timetable.util.SessionRollForward.java

public void rollCurriculaForward(ActionMessages errors, RollForwardSessionForm rollForwardSessionForm) {
    Session toSession = Session.getSessionById(rollForwardSessionForm.getSessionToRollForwardTo());
    Session fromSession = Session.getSessionById(rollForwardSessionForm.getSessionToRollCurriculaForwardFrom());

    org.hibernate.Session hibSession = CurriculumDAO.getInstance().getSession();

    // roll forward academic areas, if needed
    Hashtable<String, AcademicArea> areas = new Hashtable<String, AcademicArea>();
    for (AcademicArea area : AcademicAreaDAO.getInstance().findBySession(hibSession, toSession.getUniqueId())) {
        areas.put(area.getAcademicAreaAbbreviation(), area);
    }// w  w  w .j  a v  a 2 s. c  om
    if (areas.isEmpty()) {
        for (AcademicArea area : AcademicAreaDAO.getInstance().findBySession(hibSession,
                fromSession.getUniqueId())) {
            AcademicArea newArea = (AcademicArea) area.clone();
            newArea.setSession(toSession);
            newArea.setPosMajors(new HashSet<PosMajor>());
            newArea.setPosMinors(new HashSet<PosMinor>());
            hibSession.save(newArea);
            areas.put(newArea.getAcademicAreaAbbreviation(), newArea);
        }
    }

    // roll forward academic classifications, if needed
    Hashtable<String, AcademicClassification> classifications = new Hashtable<String, AcademicClassification>();
    for (AcademicClassification clasf : AcademicClassificationDAO.getInstance().findBySession(hibSession,
            toSession.getUniqueId())) {
        classifications.put(clasf.getCode(), clasf);
    }
    if (classifications.isEmpty()) {
        for (AcademicClassification clasf : AcademicClassificationDAO.getInstance().findBySession(hibSession,
                fromSession.getUniqueId())) {
            AcademicClassification newClasf = (AcademicClassification) clasf.clone();
            newClasf.setSession(toSession);
            hibSession.save(newClasf);
            classifications.put(newClasf.getCode(), newClasf);
        }
    }

    // roll forward majors, if needed
    Hashtable<String, Hashtable<String, PosMajor>> majors = new Hashtable<String, Hashtable<String, PosMajor>>();
    for (PosMajor major : PosMajorDAO.getInstance().findBySession(hibSession, toSession.getUniqueId())) {
        for (AcademicArea area : major.getAcademicAreas()) {
            Hashtable<String, PosMajor> code2major = majors.get(area.getAcademicAreaAbbreviation());
            if (code2major == null) {
                code2major = new Hashtable<String, PosMajor>();
                majors.put(area.getAcademicAreaAbbreviation(), code2major);
            }
            code2major.put(major.getCode(), major);
        }
    }
    if (majors.isEmpty()) {
        for (PosMajor major : PosMajorDAO.getInstance().findBySession(hibSession, fromSession.getUniqueId())) {
            Set<AcademicArea> newAreas = new HashSet<AcademicArea>();
            for (AcademicArea area : major.getAcademicAreas()) {
                AcademicArea newArea = areas.get(area.getAcademicAreaAbbreviation());
                if (newArea != null)
                    newAreas.add(newArea);
            }
            if (newAreas.isEmpty())
                continue;
            PosMajor newMajor = (PosMajor) major.clone();
            newMajor.setSession(toSession);
            newMajor.setAcademicAreas(newAreas);
            for (AcademicArea newArea : newAreas) {
                newArea.getPosMajors().add(newMajor);
                Hashtable<String, PosMajor> code2major = majors.get(newArea.getAcademicAreaAbbreviation());
                if (code2major == null) {
                    code2major = new Hashtable<String, PosMajor>();
                    majors.put(newArea.getAcademicAreaAbbreviation(), code2major);
                }
                code2major.put(newMajor.getCode(), newMajor);
            }
            hibSession.save(newMajor);
        }
    }

    // roll forward minors, if needed
    Hashtable<String, Hashtable<String, PosMinor>> minors = new Hashtable<String, Hashtable<String, PosMinor>>();
    for (PosMinor minor : PosMinorDAO.getInstance().findBySession(hibSession, toSession.getUniqueId())) {
        for (AcademicArea area : minor.getAcademicAreas()) {
            Hashtable<String, PosMinor> code2minor = minors.get(area.getAcademicAreaAbbreviation());
            if (code2minor == null) {
                code2minor = new Hashtable<String, PosMinor>();
                minors.put(area.getAcademicAreaAbbreviation(), code2minor);
            }
            code2minor.put(minor.getCode(), minor);
        }
    }
    if (minors.isEmpty()) {
        for (PosMinor minor : PosMinorDAO.getInstance().findBySession(hibSession, fromSession.getUniqueId())) {
            Set<AcademicArea> newAreas = new HashSet<AcademicArea>();
            for (AcademicArea area : minor.getAcademicAreas()) {
                AcademicArea newArea = areas.get(area.getAcademicAreaAbbreviation());
                if (newArea != null)
                    newAreas.add(newArea);
            }
            if (newAreas.isEmpty())
                continue;
            PosMinor newMinor = (PosMinor) minor.clone();
            newMinor.setSession(toSession);
            newMinor.setAcademicAreas(newAreas);
            for (AcademicArea newArea : newAreas) {
                newArea.getPosMinors().add(newMinor);
                Hashtable<String, PosMinor> code2minor = minors.get(newArea.getAcademicAreaAbbreviation());
                if (code2minor == null) {
                    code2minor = new Hashtable<String, PosMinor>();
                    minors.put(newArea.getAcademicAreaAbbreviation(), code2minor);
                }
                code2minor.put(newMinor.getCode(), newMinor);
            }
            hibSession.save(newMinor);
        }
    }

    // course translation table
    Hashtable<Long, CourseOffering> courses = new Hashtable<Long, CourseOffering>();
    for (CourseOffering course : (List<CourseOffering>) hibSession
            .createQuery(
                    "select co from CourseOffering co " + "where co.uniqueIdRolledForwardFrom is not null and "
                            + "co.subjectArea.session.uniqueId = :sessionId")
            .setLong("sessionId", toSession.getUniqueId()).list()) {
        courses.put(course.getUniqueIdRolledForwardFrom(), course);
    }

    // cleanup all curricula
    for (Iterator<Curriculum> i = hibSession
            .createQuery("select c from Curriculum c where c.department.session=:sessionId")
            .setLong("sessionId", toSession.getUniqueId()).list().iterator(); i.hasNext();) {
        hibSession.delete(i.next());
    }
    hibSession.flush();

    // roll forward curricula
    Department tempDept = null;
    curricula: for (Curriculum curriculum : (List<Curriculum>) hibSession
            .createQuery("select c from Curriculum c where c.department.session=:sessionId")
            .setLong("sessionId", fromSession.getUniqueId()).list()) {
        Curriculum newCurriculum = new Curriculum();
        newCurriculum.setAbbv(curriculum.getAbbv());
        newCurriculum.setName(curriculum.getName());
        newCurriculum.setMultipleMajors(curriculum.isMultipleMajors());
        AcademicArea area = areas.get(curriculum.getAcademicArea().getAcademicAreaAbbreviation());
        if (area == null)
            continue;
        newCurriculum.setAcademicArea(area);
        Department dept = curriculum.getDepartment().findSameDepartmentInSession(toSession);
        if (dept == null) {
            if (tempDept == null) {
                tempDept = Department.findByDeptCode("TEMP", toSession.getUniqueId());
                if (tempDept == null) {
                    tempDept = new Department();
                    tempDept.setAbbreviation("TEMP");
                    tempDept.setAllowReqRoom(new Boolean(false));
                    tempDept.setAllowReqTime(new Boolean(false));
                    tempDept.setAllowReqDistribution(new Boolean(false));
                    tempDept.setDeptCode("TEMP");
                    tempDept.setExternalManager(new Boolean(false));
                    tempDept.setExternalUniqueId(null);
                    tempDept.setName("Temp Department For New Curricula");
                    tempDept.setSession(toSession);
                    tempDept.setDistributionPrefPriority(new Integer(0));
                    tempDept.setInheritInstructorPreferences(true);
                    tempDept.setAllowEvents(false);
                    tempDept.setAllowStudentScheduling(false);
                    toSession.addTodepartments(tempDept);
                    hibSession.save(tempDept);
                }
            }
            dept = tempDept;
        }
        newCurriculum.setDepartment(dept);
        newCurriculum.setMajors(new HashSet<PosMajor>());
        Hashtable<String, PosMajor> code2major = majors.get(area.getAcademicAreaAbbreviation());
        for (PosMajor major : curriculum.getMajors()) {
            PosMajor newMajor = (code2major == null ? null : code2major.get(major.getCode()));
            if (newMajor == null)
                continue curricula;
            newCurriculum.getMajors().add(newMajor);
        }
        newCurriculum.setClassifications(new HashSet<CurriculumClassification>());
        Hashtable<Long, CurriculumCourseGroup> createdGroups = new Hashtable<Long, CurriculumCourseGroup>();
        for (CurriculumClassification clasf : curriculum.getClassifications()) {
            CurriculumClassification newClasf = new CurriculumClassification();
            AcademicClassification f = classifications.get(clasf.getAcademicClassification().getCode());
            if (f == null)
                continue;
            newClasf.setAcademicClassification(f);
            newClasf.setCurriculum(newCurriculum);
            newClasf.setName(clasf.getName());
            newClasf.setNrStudents(clasf.getNrStudents());
            newClasf.setOrd(clasf.getOrd());
            newClasf.setCourses(new HashSet<CurriculumCourse>());
            newCurriculum.getClassifications().add(newClasf);
            for (CurriculumCourse course : clasf.getCourses()) {
                CurriculumCourse newCourse = new CurriculumCourse();
                newCourse.setOrd(course.getOrd());
                newCourse.setPercShare(course.getPercShare());
                CourseOffering co = courses.get(course.getCourse().getUniqueId());
                if (co == null)
                    continue;
                newCourse.setCourse(co);
                newCourse.setClassification(newClasf);
                newClasf.getCourses().add(newCourse);
                newCourse.setGroups(new HashSet<CurriculumCourseGroup>());
                for (CurriculumCourseGroup group : course.getGroups()) {
                    CurriculumCourseGroup newGroup = createdGroups.get(group.getUniqueId());
                    if (newGroup == null) {
                        newGroup = new CurriculumCourseGroup();
                        newGroup.setColor(group.getColor());
                        newGroup.setName(group.getName());
                        newGroup.setType(group.getType());
                        newGroup.setCurriculum(newCurriculum);
                        createdGroups.put(group.getUniqueId(), newGroup);
                    }
                    newCourse.getGroups().add(newGroup);
                }
            }
        }

        hibSession.save(newCurriculum);
        for (CurriculumCourseGroup g : createdGroups.values())
            hibSession.saveOrUpdate(g);
    }

    // roll forward projection rules (if empty)
    if (hibSession.createQuery(
            "select r from CurriculumProjectionRule r where r.academicArea.session.uniqueId = :sessionId")
            .setLong("sessionId", toSession.getUniqueId()).list().isEmpty()) {
        rules: for (CurriculumProjectionRule rule : (List<CurriculumProjectionRule>) hibSession
                .createQuery("select r from CurriculumProjectionRule r "
                        + "where r.academicArea.session.uniqueId = :sessionId")
                .setLong("sessionId", fromSession.getUniqueId()).list()) {
            CurriculumProjectionRule newRule = new CurriculumProjectionRule();
            AcademicArea area = areas.get(rule.getAcademicArea().getAcademicAreaAbbreviation());
            if (area == null)
                continue;
            newRule.setAcademicArea(area);
            AcademicClassification clasf = classifications.get(rule.getAcademicClassification().getCode());
            if (clasf == null)
                continue;
            newRule.setAcademicClassification(clasf);
            if (rule.getMajor() != null) {
                Hashtable<String, PosMajor> code2major = majors.get(area.getAcademicAreaAbbreviation());
                PosMajor major = (code2major == null ? null : code2major.get(rule.getMajor().getCode()));
                if (major == null)
                    continue rules;
                newRule.setMajor(major);
            }
            newRule.setProjection(rule.getProjection());
            hibSession.save(newRule);
        }
    }

    hibSession.flush();
    hibSession.clear();
}

From source file:org.unitime.timetable.test.BatchStudentSectioningLoader.java

public void load(Session session) {
    org.hibernate.Session hibSession = new SessionDAO().getSession();
    Transaction tx = hibSession.beginTransaction();

    try {//from w  ww .  java 2  s.  c o m

        Hashtable courseTable = new Hashtable();
        Hashtable classTable = new Hashtable();
        List offerings = hibSession
                .createQuery("select distinct io from InstructionalOffering io "
                        + "left join fetch io.courseOfferings as co "
                        + "left join fetch io.instrOfferingConfigs as ioc "
                        + "left join fetch ioc.schedulingSubparts as ss " + "left join fetch ss.classes as c "
                        + "where " + "io.session.uniqueId=:sessionId and io.notOffered=false")
                .setLong("sessionId", session.getUniqueId().longValue()).setFetchSize(1000).list();
        for (Iterator i = offerings.iterator(); i.hasNext();) {
            InstructionalOffering io = (InstructionalOffering) i.next();
            Offering offering = loadOffering(io, courseTable, classTable);
            if (offering != null)
                getModel().addOffering(offering);
        }

        HashSet loadedStudentIds = new HashSet();
        if (iIncludeCourseDemands) {
            List students = hibSession
                    .createQuery("select distinct s from Student s " + "left join fetch s.courseDemands as cd "
                            + "left join fetch cd.courseRequests as cr "
                            + "where s.session.uniqueId=:sessionId")
                    .setLong("sessionId", session.getUniqueId().longValue()).setFetchSize(1000).list();
            for (Iterator i = students.iterator(); i.hasNext();) {
                org.unitime.timetable.model.Student s = (org.unitime.timetable.model.Student) i.next();
                if (s.getCourseDemands().isEmpty())
                    continue;
                Student student = loadStudent(s, courseTable, classTable);
                if (student != null)
                    getModel().addStudent(student);
                if (s.getExternalUniqueId() != null)
                    loadedStudentIds.add(s.getExternalUniqueId());
            }
        }

        if (iIncludeLastLikeStudents) {
            Hashtable classAssignments = null;
            if (iIncludeUseCommittedAssignments) {
                classAssignments = new Hashtable();
                for (Iterator i = hibSession.createQuery(
                        "select distinct se.studentId, se.clazz.uniqueId from StudentEnrollment se where "
                                + "se.solution.commited=true and se.solution.owner.session.uniqueId=:sessionId")
                        .setLong("sessionId", session.getUniqueId().longValue()).iterate(); i.hasNext();) {
                    Object[] o = (Object[]) i.next();
                    Long studentId = (Long) o[0];
                    Long classId = (Long) o[1];
                    HashSet classIds = (HashSet) classAssignments.get(studentId);
                    if (classIds == null) {
                        classIds = new HashSet();
                        classAssignments.put(studentId, classIds);
                    }
                    classIds.add(classId);
                }
            }

            Hashtable lastLikeStudentTable = new Hashtable();
            for (Iterator i = hibSession.createQuery(
                    "select d, c.uniqueId from LastLikeCourseDemand d left join fetch d.student s, CourseOffering c left join c.demandOffering cx "
                            + "where d.subjectArea.session.uniqueId=:sessionId and c.subjectArea.session.uniqueId=:sessionId and "
                            + "((c.permId=null and d.subjectArea=c.subjectArea and d.courseNbr=c.courseNbr ) or "
                            + " (c.permId!=null and c.permId=d.coursePermId) or "
                            + " (cx.permId=null and d.subjectArea=cx.subjectArea and d.courseNbr=cx.courseNbr) or "
                            + " (cx.permId!=null and cx.permId=d.coursePermId)) "
                            + "order by s.uniqueId, d.priority, d.uniqueId")
                    .setLong("sessionId", session.getUniqueId().longValue()).list().iterator(); i.hasNext();) {
                Object[] o = (Object[]) i.next();
                LastLikeCourseDemand d = (LastLikeCourseDemand) o[0];
                org.unitime.timetable.model.Student s = (org.unitime.timetable.model.Student) d.getStudent();
                Long courseOfferingId = (Long) o[1];
                if (s.getExternalUniqueId() != null && loadedStudentIds.contains(s.getExternalUniqueId()))
                    continue;
                loadLastLikeStudent(hibSession, d, s, courseOfferingId, lastLikeStudentTable, courseTable,
                        classTable, classAssignments);
            }
            for (Enumeration e = lastLikeStudentTable.elements(); e.hasMoreElements();) {
                Student student = (Student) e.nextElement();
                getModel().addStudent(student);
            }
            if (classAssignments != null && !classAssignments.isEmpty()) {
                for (Request request : getModel().variables()) {
                    if (request.getInitialAssignment() == null)
                        continue;
                    Set conflicts = getModel().conflictValues(getAssignment(), request.getInitialAssignment());
                    if (conflicts.isEmpty())
                        getAssignment().assign(0, request.getInitialAssignment());
                    else
                        sLog.debug("Unable to assign " + request.getInitialAssignment() + ", conflicts: "
                                + conflicts);
                }
            }
            fixWeights();
        }

        tx.commit();
    } catch (Exception e) {
        tx.rollback();
        throw new RuntimeException(e);
    } finally {
        hibSession.close();
    }
}

From source file:org.opencms.webdav.CmsWebdavServlet.java

/**
 * Process a DELETE WebDAV request for the specified resource.<p>
 * //from www . j a  v  a 2s  .co m
 * @param req the servlet request we are processing
 * @param resp the servlet response we are creating
 * 
 * @throws IOException if an input/output error occurs
 */
@Override
protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws IOException {

    // Get the path to delete
    String path = getRelativePath(req);

    // Check if webdav is set to read only
    if (m_readOnly) {

        resp.setStatus(CmsWebdavStatus.SC_FORBIDDEN);

        if (LOG.isDebugEnabled()) {
            LOG.debug(Messages.get().getBundle().key(Messages.LOG_WEBDAV_READ_ONLY_0));
        }

        return;
    }

    // Check if path exists
    boolean exists = m_session.exists(path);
    if (!exists) {

        resp.setStatus(CmsWebdavStatus.SC_NOT_FOUND);

        if (LOG.isDebugEnabled()) {
            LOG.debug(Messages.get().getBundle().key(Messages.LOG_ITEM_NOT_FOUND_1, path));
        }

        return;
    }

    // Check if resource is locked
    if (isLocked(req)) {

        resp.setStatus(CmsWebdavStatus.SC_LOCKED);

        if (LOG.isDebugEnabled()) {
            LOG.debug(Messages.get().getBundle().key(Messages.LOG_ITEM_LOCKED_1, path));
        }

        return;
    }

    // Check if resources found in the tree of the path are locked
    Hashtable<String, Integer> errorList = new Hashtable<String, Integer>();

    checkChildLocks(req, path, errorList);
    if (!errorList.isEmpty()) {
        sendReport(req, resp, errorList);

        if (LOG.isDebugEnabled()) {
            Iterator<String> iter = errorList.keySet().iterator();
            while (iter.hasNext()) {
                String errorPath = iter.next();
                LOG.debug(Messages.get().getBundle().key(Messages.LOG_CHILD_LOCKED_1, errorPath));
            }
        }

        return;
    }

    // Delete the resource
    try {

        if (LOG.isDebugEnabled()) {
            LOG.debug(Messages.get().getBundle().key(Messages.LOG_DELETE_ITEM_0));
        }

        m_session.delete(path);
    } catch (CmsVfsResourceNotFoundException rnfex) {

        // should never happen
        resp.setStatus(CmsWebdavStatus.SC_NOT_FOUND);
        return;
    } catch (CmsSecurityException sex) {
        resp.setStatus(CmsWebdavStatus.SC_FORBIDDEN);

        if (LOG.isDebugEnabled()) {
            LOG.debug(Messages.get().getBundle().key(Messages.LOG_NO_PERMISSION_0));
        }

        return;
    } catch (CmsException ex) {
        resp.setStatus(CmsWebdavStatus.SC_INTERNAL_SERVER_ERROR);

        if (LOG.isErrorEnabled()) {
            LOG.error(Messages.get().getBundle().key(Messages.LOG_REPOSITORY_ERROR_2, "DELETE", path), ex);
        }

        return;
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug(Messages.get().getBundle().key(Messages.LOG_DELETE_SUCCESS_0));
    }

    resp.setStatus(CmsWebdavStatus.SC_NO_CONTENT);
}

From source file:org.gss_project.gss.server.rest.Webdav.java

/**
 * Copy a resource./*from  w w  w  .  ja v  a  2 s  . co m*/
 *
 * @param req Servlet request
 * @param resp Servlet response
 * @return boolean true if the copy is successful
 * @throws IOException
 */
private boolean copyResource(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    // Parsing destination header
    String destinationPath = req.getHeader("Destination");
    if (destinationPath == null) {
        resp.sendError(WebdavStatus.SC_BAD_REQUEST);
        return false;
    }

    // Remove url encoding from destination
    destinationPath = RequestUtil.URLDecode(destinationPath, "UTF8");

    int protocolIndex = destinationPath.indexOf("://");
    if (protocolIndex >= 0) {
        // if the Destination URL contains the protocol, we can safely
        // trim everything upto the first "/" character after "://"
        int firstSeparator = destinationPath.indexOf("/", protocolIndex + 4);
        if (firstSeparator < 0)
            destinationPath = "/";
        else
            destinationPath = destinationPath.substring(firstSeparator);
    } else {
        String hostName = req.getServerName();
        if (hostName != null && destinationPath.startsWith(hostName))
            destinationPath = destinationPath.substring(hostName.length());

        int portIndex = destinationPath.indexOf(":");
        if (portIndex >= 0)
            destinationPath = destinationPath.substring(portIndex);

        if (destinationPath.startsWith(":")) {
            int firstSeparator = destinationPath.indexOf("/");
            if (firstSeparator < 0)
                destinationPath = "/";
            else
                destinationPath = destinationPath.substring(firstSeparator);
        }
    }

    // Normalize destination path (remove '.' and '..')
    destinationPath = RequestUtil.normalize(destinationPath);

    String contextPath = req.getContextPath();
    if (contextPath != null && destinationPath.startsWith(contextPath))
        destinationPath = destinationPath.substring(contextPath.length());

    String pathInfo = req.getPathInfo();
    if (pathInfo != null) {
        String servletPath = req.getServletPath();
        if (servletPath != null && destinationPath.startsWith(servletPath))
            destinationPath = destinationPath.substring(servletPath.length());
    }

    if (logger.isDebugEnabled())
        logger.debug("Dest path :" + destinationPath);

    if (destinationPath.toUpperCase().startsWith("/WEB-INF")
            || destinationPath.toUpperCase().startsWith("/META-INF")) {
        resp.sendError(WebdavStatus.SC_FORBIDDEN);
        return false;
    }

    String path = getRelativePath(req);

    if (path.toUpperCase().startsWith("/WEB-INF") || path.toUpperCase().startsWith("/META-INF")) {
        resp.sendError(WebdavStatus.SC_FORBIDDEN);
        return false;
    }

    if (destinationPath.equals(path)) {
        resp.sendError(WebdavStatus.SC_FORBIDDEN);
        return false;
    }

    // Parsing overwrite header
    boolean overwrite = true;
    String overwriteHeader = req.getHeader("Overwrite");

    if (overwriteHeader != null)
        if (overwriteHeader.equalsIgnoreCase("T"))
            overwrite = true;
        else
            overwrite = false;

    User user = getUser(req);
    // Overwriting the destination
    boolean exists = true;
    try {
        getService().getResourceAtPath(user.getId(), destinationPath, true);
    } catch (ObjectNotFoundException e) {
        exists = false;
    } catch (RpcException e) {
        resp.sendError(HttpStatus.SC_INTERNAL_SERVER_ERROR);
        return false;
    }

    if (overwrite) {
        // Delete destination resource, if it exists
        if (exists) {
            if (!deleteResource(destinationPath, req, resp, true))
                return false;
        } else
            resp.setStatus(WebdavStatus.SC_CREATED);
    } else // If the destination exists, then it's a conflict
    if (exists) {
        resp.sendError(WebdavStatus.SC_PRECONDITION_FAILED);
        return false;
    } else
        resp.setStatus(WebdavStatus.SC_CREATED);

    // Copying source to destination.
    Hashtable<String, Integer> errorList = new Hashtable<String, Integer>();
    boolean result;
    try {
        result = copyResource(errorList, path, destinationPath, req);
    } catch (RpcException e) {
        resp.sendError(HttpStatus.SC_INTERNAL_SERVER_ERROR);
        return false;
    }
    if (!result || !errorList.isEmpty()) {
        sendReport(req, resp, errorList);
        return false;
    }
    return true;
}

From source file:com.zeroio.webdav.WebdavServlet.java

/**
 * Copy a resource./*w  w  w  .j  a  va 2s .co m*/
 *
 * @param context Description of the Parameter
 * @param db      Description of the Parameter
 * @param method  Description of the Parameter
 * @return boolean true if the copy is successful
 * @throws ServletException Description of the Exception
 * @throws IOException      Description of the Exception
 * @throws SQLException     Description of the Exception
 */
//private boolean copyResource(ActionContext context, Connection db)
private boolean performAction(ActionContext context, Connection db, String method)
        throws SQLException, ServletException, IOException {

    // Parsing destination header
    String destinationPath = context.getRequest().getHeader("Destination");

    if (destinationPath == null) {
        context.getResponse().sendError(WebdavStatus.SC_BAD_REQUEST);
        return false;
    }

    // Remove url encoding from destination
    destinationPath = RequestUtil.URLDecode(destinationPath, "UTF8");

    int protocolIndex = destinationPath.indexOf("://");
    if (protocolIndex >= 0) {
        // if the Destination URL contains the protocol, we can safely
        // trim everything upto the first "/" character after "://"
        int firstSeparator = destinationPath.indexOf("/", protocolIndex + 4);
        if (firstSeparator < 0) {
            destinationPath = "/";
        } else {
            destinationPath = destinationPath.substring(firstSeparator);
        }
    } else {
        String hostName = context.getRequest().getServerName();
        if ((hostName != null) && (destinationPath.startsWith(hostName))) {
            destinationPath = destinationPath.substring(hostName.length());
        }

        int portIndex = destinationPath.indexOf(":");
        if (portIndex >= 0) {
            destinationPath = destinationPath.substring(portIndex);
        }

        if (destinationPath.startsWith(":")) {
            int firstSeparator = destinationPath.indexOf("/");
            if (firstSeparator < 0) {
                destinationPath = "/";
            } else {
                destinationPath = destinationPath.substring(firstSeparator);
            }
        }
    }

    // Normalise destination path (remove '.' and '..')
    destinationPath = normalize(destinationPath);

    String contextPath = context.getRequest().getContextPath();
    if ((contextPath != null) && (destinationPath.startsWith(contextPath))) {
        destinationPath = destinationPath.substring(contextPath.length());
    }

    String pathInfo = context.getRequest().getPathInfo();
    if (pathInfo != null) {
        String servletPath = context.getRequest().getServletPath();
        if ((servletPath != null) && (destinationPath.startsWith(servletPath))) {
            destinationPath = destinationPath.substring(servletPath.length());
        }
    }

    if (debug > 0) {
        System.out.println("Dest path :" + destinationPath);
    }

    if ((destinationPath.toUpperCase().startsWith("/WEB-INF"))
            || (destinationPath.toUpperCase().startsWith("/META-INF"))) {
        context.getResponse().sendError(WebdavStatus.SC_FORBIDDEN);
        return false;
    }

    String path = getRelativePath(context.getRequest());

    //Fix for MACOSX finder. Do not allow requests for files starting with a period
    if (path.indexOf("/.") > -1 || path.indexOf(".DS_Store") > -1) {
        return false;
    }

    if (path.endsWith("/")) {
        path = path.substring(0, path.lastIndexOf("/"));
    }

    if ((path.toUpperCase().startsWith("/WEB-INF")) || (path.toUpperCase().startsWith("/META-INF"))) {
        context.getResponse().sendError(WebdavStatus.SC_FORBIDDEN);
        return false;
    }

    if (destinationPath.equals(path)) {
        context.getResponse().sendError(WebdavStatus.SC_FORBIDDEN);
        return false;
    }

    // Parsing overwrite header

    boolean overwrite = true;
    String overwriteHeader = context.getRequest().getHeader("Overwrite");

    if (overwriteHeader != null) {
        if (overwriteHeader.equalsIgnoreCase("T")) {
            overwrite = true;
        } else {
            overwrite = false;
        }
    }

    // Overwriting the destination
    // Retrieve the resources
    ModuleContext resources = getCFSResources(db, context);
    SystemStatus thisSystem = this.getSystemStatus(context);

    if (resources == null) {
        context.getResponse().sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return false;
    }

    Object object = null;
    boolean exists = true;

    try {
        //lookup the object at path. If it is a top level folder fail otherwise proceed
        object = resources.lookup(thisSystem, db, path);

        if (getWebdavManager(context).isTopLevelModule(object)) {
            return false;
        }

        resources.lookup(thisSystem, db, destinationPath);
    } catch (NamingException ne) {
        exists = false;
    }

    if (overwrite) {
        // Delete destination resource, if it exists
        if (exists) {
            if (!deleteResource(context, db, destinationPath, true)) {
                context.getResponse().sendError(WebdavStatus.SC_FORBIDDEN);
                return false;
            }
        } else {
            context.getResponse().setStatus(WebdavStatus.SC_CREATED);
        }
    } else {
        // If the destination exists, then it's a conflict
        if (exists) {
            context.getResponse().sendError(WebdavStatus.SC_PRECONDITION_FAILED);
            return false;
        }
    }

    // Copying source to destination
    Hashtable errorList = new Hashtable();
    boolean result = false;
    try {
        if (method.equals(METHOD_COPY)) {
            result = copyResource(context, thisSystem, db, resources, errorList, path, destinationPath);
        } else if (method.equals(METHOD_MOVE)) {
            result = moveResource(thisSystem, db, resources, errorList, path, destinationPath);
        }
    } catch (FileNotFoundException fnfe) {
    }

    if ((!result) || (!errorList.isEmpty())) {
        //sendReport(context.getRequest(), context.getResponse(), errorList);
        context.getResponse().sendError(WebdavStatus.SC_FORBIDDEN);
        return false;
    }

    // Removing any lock-null resource which would be present at
    // the destination path
    lockNullResources.remove(destinationPath);
    return true;
}

From source file:com.zeroio.webdav.WebdavServlet.java

/**
 * Delete a resource./*  ww w  .j  a va  2 s .c  om*/
 *
 * @param path      Path of the resource which is to be deleted
 * @param setStatus Should the response status be set on
 *                  successful completion
 * @param context   Description of the Parameter
 * @param db        Description of the Parameter
 * @return Description of the Return Value
 * @throws ServletException Description of the Exception
 * @throws IOException      Description of the Exception
 * @throws SQLException     Description of the Exception
 */
private boolean deleteResource(ActionContext context, Connection db, String path, boolean setStatus)
        throws SQLException, ServletException, IOException {

    if ((path.toUpperCase().startsWith("/WEB-INF")) || (path.toUpperCase().startsWith("/META-INF"))) {
        context.getResponse().sendError(WebdavStatus.SC_FORBIDDEN);
        return false;
    }

    String ifHeader = context.getRequest().getHeader("If");
    if (ifHeader == null) {
        ifHeader = "";
    }

    String lockTokenHeader = context.getRequest().getHeader("Lock-Token");
    if (lockTokenHeader == null) {
        lockTokenHeader = "";
    }

    if (isLocked(path, ifHeader + lockTokenHeader)) {
        context.getResponse().sendError(WebdavStatus.SC_LOCKED);
        return false;
    }

    //Check to see if the delete is being issued due to a copy or a move action
    String destinationPath = context.getRequest().getHeader("Destination");
    if (destinationPath != null) {
        System.out.println("DELETION DUE TO COPY OR MOVE ACTION....");
    }

    // Retrieve the resources
    ModuleContext resources = getCFSResources(db, context);
    SystemStatus thisSystem = this.getSystemStatus(context);

    if (resources == null) {
        context.getResponse().sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return false;
    }

    Object object = null;
    boolean exists = true;

    try {
        //lookup the object at path. If it is a top level folder fail otherwise proceed
        object = resources.lookup(thisSystem, db, path);

        if (getWebdavManager(context).isTopLevelModule(object)) {
            //context.getResponse().sendError(WebdavStatus.SC_FORBIDDEN);
            return false;
        }
    } catch (NamingException e) {
        exists = false;
    }

    if (!exists) {
        context.getResponse().sendError(WebdavStatus.SC_NOT_FOUND);
        return false;
    }

    boolean collection = (object instanceof ModuleContext);

    if (!collection) {
        try {
            resources.unbind(thisSystem, db, path);
        } catch (NamingException e) {
            //e.printStackTrace(System.out);
            context.getResponse().sendError(WebdavStatus.SC_INTERNAL_SERVER_ERROR);
            return false;
        }
    } else {
        Hashtable errorList = new Hashtable();
        //System.out.println("Calling deleteCollection(.....) .......");
        deleteCollection(thisSystem, db, context.getRequest(), resources, path, errorList);
        try {
            resources.unbind(thisSystem, db, path);
        } catch (NamingException e) {
            e.printStackTrace(System.out);
            errorList.put(path, new Integer(WebdavStatus.SC_INTERNAL_SERVER_ERROR));
        } catch (SQLException sql) {
            sql.printStackTrace(System.out);
            throw new SQLException(sql.getMessage());
        }
        if (!errorList.isEmpty()) {
            sendReport(context.getRequest(), context.getResponse(), errorList);
            return false;
        }
    }
    if (setStatus) {
        context.getResponse().setStatus(WebdavStatus.SC_NO_CONTENT);
    }
    return true;
}

From source file:org.LexGrid.LexBIG.Impl.dataAccess.SQLImplementedMethods.java

public static Entity buildCodedEntry(String internalCodingSchemeName, String internalVersionString, String code,
        String namespace, LocalNameList restrictToProperties, PropertyType[] restrictToPropertyTypes)
        throws UnexpectedInternalError, MissingResourceException {

    try {// w w  w. j a v  a  2 s. c  o m
        Entity concept = new Entity();
        concept.setEntityCode(code);

        SQLInterface si = ResourceManager.instance().getSQLInterface(internalCodingSchemeName,
                internalVersionString);

        //if the namespace is null (and its 2009 model), set it to the default (which is
        //equal to the codingSchemeName.
        //This shouldn't ever happen -- all classes that call this method should provide
        //a namespace.
        if (si.supports2009Model() && StringUtils.isBlank(namespace)) {
            namespace = internalCodingSchemeName;
        }

        ArrayList<Definition> definitions = new ArrayList<Definition>();
        ArrayList<Presentation> presentations = new ArrayList<Presentation>();
        ArrayList<Property> properties = new ArrayList<Property>();
        ArrayList<Comment> comments = new ArrayList<Comment>();

        ArrayList<PropertyLink> links = new ArrayList<PropertyLink>();

        PreparedStatement getEntityCode = null;
        PreparedStatement getEntityType = null;
        PreparedStatement getEntityProperties = null;
        PreparedStatement getPropertyLinks = null;

        try {
            StringBuffer buildEntity = new StringBuffer();

            buildEntity
                    .append("Select * " + " from " + si.getTableName(SQLTableConstants.ENTITY) + " {AS} t1 ");

            if (si.supports2009Model()) {
                buildEntity.append("left join " + si.getTableName(SQLTableConstants.ENTRY_STATE) + " {AS} t2 "
                        + "on t1." + SQLTableConstants.TBLCOL_ENTRYSTATEID + " = t2."
                        + SQLTableConstants.TBLCOL_ENTRYSTATEID);
            }

            buildEntity.append(" where " + si.getSQLTableConstants().codingSchemeNameOrId + " = ? AND "
                    + si.getSQLTableConstants().entityCodeOrId + " = ?");

            if (si.supports2009Model()) {
                buildEntity.append(" AND " + SQLTableConstants.TBLCOL_ENTITYCODENAMESPACE + " = ?");
            }

            getEntityCode = si.modifyAndCheckOutPreparedStatement(buildEntity.toString());

            getEntityCode.setString(1, internalCodingSchemeName);
            getEntityCode.setString(2, code);
            if (si.supports2009Model()) {
                getEntityCode.setString(3, namespace);
            }

            ResultSet results = getEntityCode.executeQuery();

            // one and only one result
            if (results.next()) {
                concept.setIsDefined(
                        DBUtility.getBooleanFromResultSet(results, SQLTableConstants.TBLCOL_ISDEFINED));
                concept.setIsAnonymous(
                        DBUtility.getBooleanFromResultSet(results, SQLTableConstants.TBLCOL_ISANONYMOUS));
                concept.setIsActive(
                        DBUtility.getBooleanFromResultSet(results, SQLTableConstants.TBLCOL_ISACTIVE));

                if (!si.supports2009Model()) {
                    concept.setStatus(results.getString(SQLTableConstants.TBLCOL_CONCEPTSTATUS));
                } else {
                    concept.setEntityCodeNamespace(namespace);
                }

                EntityDescription ed = new EntityDescription();
                ed.setContent(results.getString(SQLTableConstants.TBLCOL_ENTITYDESCRIPTION));
                concept.setEntityDescription(ed);

                if (si.supports2009Model()) {
                    String owner = results.getString(SQLTableConstants.TBLCOL_OWNER);
                    String status = results.getString(SQLTableConstants.TBLCOL_STATUS);
                    Timestamp effectiveDate = results.getTimestamp(SQLTableConstants.TBLCOL_EFFECTIVEDATE);
                    Timestamp expirationDate = results.getTimestamp(SQLTableConstants.TBLCOL_EXPIRATIONDATE);
                    String revisionId = results.getString(SQLTableConstants.TBLCOL_REVISIONID);
                    String prevRevisionId = results.getString(SQLTableConstants.TBLCOL_PREVREVISIONID);
                    String changeType = results.getString(SQLTableConstants.TBLCOL_CHANGETYPE);
                    String relativeOrder = results.getString(SQLTableConstants.TBLCOL_RELATIVEORDER);

                    EntryState es = new EntryState();

                    if (!StringUtils.isBlank(changeType)) {
                        es.setChangeType(org.LexGrid.versions.types.ChangeType.valueOf(changeType));
                    }
                    es.setContainingRevision(revisionId);
                    es.setPrevRevision(prevRevisionId);

                    es.setRelativeOrder(computeRelativeOrder(relativeOrder));

                    concept.setEntryState(es);

                    if (owner != null) {
                        concept.setOwner(owner);
                    }
                    concept.setStatus(status);
                    concept.setEffectiveDate(effectiveDate);
                    concept.setExpirationDate(expirationDate);
                }
            }

            results.close();
            si.checkInPreparedStatement(getEntityCode);

            if (si.supports2009Model()) {
                getEntityType = si.checkOutPreparedStatement(
                        "Select * " + " from " + si.getTableName(SQLTableConstants.ENTITY_TYPE) + " where "
                                + si.getSQLTableConstants().codingSchemeNameOrId + " = ? AND "
                                + si.getSQLTableConstants().entityCodeOrId + " = ? AND "
                                + SQLTableConstants.TBLCOL_ENTITYCODENAMESPACE + " = ?");

                getEntityType.setString(1, internalCodingSchemeName);
                getEntityType.setString(2, code);
                getEntityType.setString(3, namespace);

                results = getEntityType.executeQuery();
                while (results.next()) {
                    concept.addEntityType(results.getString(SQLTableConstants.TBLCOL_ENTITYTYPE));
                }

                results.close();
                si.checkInPreparedStatement(getEntityType);
            } else {
                concept.addEntityType(SQLTableConstants.ENTITYTYPE_CONCEPT);
            }

            // populate the property links
            String addWhereSegment = (!si.supports2009Model()
                    ? (si.getSQLTableConstants().entityType + " = '" + SQLTableConstants.ENTITYTYPE_CONCEPT
                            + "' and ")
                    : "");

            getPropertyLinks = si
                    .checkOutPreparedStatement("Select " + SQLTableConstants.TBLCOL_SOURCEPROPERTYID + ", "
                            + SQLTableConstants.TBLCOL_LINK + ", " + SQLTableConstants.TBLCOL_TARGETPROPERTYID
                            + " from " + si.getTableName(SQLTableConstants.ENTITY_PROPERTY_LINKS) + " where "
                            + addWhereSegment + si.getSQLTableConstants().entityCodeOrEntityId + " = ? and "
                            + si.getSQLTableConstants().codingSchemeNameOrId + " = ?");
            getPropertyLinks.setString(1, code);
            getPropertyLinks.setString(2, internalCodingSchemeName);

            results = getPropertyLinks.executeQuery();

            while (results.next()) {
                String sourcePropertyId = results.getString(SQLTableConstants.TBLCOL_SOURCEPROPERTYID);
                String link = results.getString(SQLTableConstants.TBLCOL_LINK);
                String targetPropertyId = results.getString(SQLTableConstants.TBLCOL_TARGETPROPERTYID);

                PropertyLink pl = new PropertyLink();
                pl.setPropertyLink(link);
                pl.setSourceProperty(sourcePropertyId);
                pl.setTargetProperty(targetPropertyId);
                links.add(pl);
            }
            results.close();
            si.checkInPreparedStatement(getPropertyLinks);

            // codedEntry.setModVersion(null);

            StringBuffer propertyQuery = new StringBuffer();

            // I'm constructing a left join query to get the property
            // results I need from 3 (or 2 in 1.5 table version) different
            // tables at once, rather than doing a query on each.

            propertyQuery.append("SELECT a." + SQLTableConstants.TBLCOL_PROPERTYID + ", a."
                    + SQLTableConstants.TBLCOL_PROPERTYNAME + ", a." + SQLTableConstants.TBLCOL_LANGUAGE
                    + ", a." + SQLTableConstants.TBLCOL_FORMAT + ", a." + SQLTableConstants.TBLCOL_ISPREFERRED
                    + ", a." + SQLTableConstants.TBLCOL_DEGREEOFFIDELITY + ", a."
                    + SQLTableConstants.TBLCOL_MATCHIFNOCONTEXT + ", a."
                    + SQLTableConstants.TBLCOL_REPRESENTATIONALFORM + ", a."
                    + SQLTableConstants.TBLCOL_PROPERTYVALUE + ", a." + SQLTableConstants.TBLCOL_PROPERTYTYPE
                    + (si.supports2009Model() ? (", a." + SQLTableConstants.TBLCOL_ENTRYSTATEID) : "")
                    + (si.supports2009Model() ? ", es.*" : "") + ", b." + SQLTableConstants.TBLCOL_TYPENAME
                    + ", b." + SQLTableConstants.TBLCOL_ATTRIBUTEVALUE + ", b." + SQLTableConstants.TBLCOL_VAL1
                    + ", b." + SQLTableConstants.TBLCOL_VAL2);

            propertyQuery.append(" FROM ");

            String codingSchemeName = si.getSQLTableConstants().codingSchemeNameOrId;
            String concptCode = si.getSQLTableConstants().entityCodeOrEntityId;

            propertyQuery.append(si.getTableName(SQLTableConstants.ENTITY_PROPERTY) + " {AS} a ");
            propertyQuery.append(
                    " left join " + si.getTableName(SQLTableConstants.ENTITY_PROPERTY_MULTI_ATTRIBUTES));
            propertyQuery.append(" {AS} b on a." + codingSchemeName + " = b." + codingSchemeName + " and a."
                    + concptCode + " = b." + concptCode + " and a." + SQLTableConstants.TBLCOL_PROPERTYID
                    + " = b." + SQLTableConstants.TBLCOL_PROPERTYID);

            if (si.supports2009Model()) {
                propertyQuery
                        .append(" left join " + si.getTableName(SQLTableConstants.ENTRY_STATE) + " {AS} es ");
                propertyQuery.append("on a." + SQLTableConstants.TBLCOL_ENTRYSTATEID);
                propertyQuery.append(" = es." + SQLTableConstants.TBLCOL_ENTRYSTATEID);
            }

            propertyQuery.append(" where a." + concptCode + " = ? " + "and a." + codingSchemeName + " = ?");
            if (si.supports2009Model()) {
                propertyQuery.append(" and a." + SQLTableConstants.TBLCOL_ENTITYCODENAMESPACE + " = ?");
            }

            if (restrictToProperties != null && restrictToProperties.getEntryCount() > 0) {
                propertyQuery.append(" AND (");
                for (int i = 0; i < restrictToProperties.getEntryCount(); i++) {
                    propertyQuery.append("  " + si.getSQLTableConstants().propertyOrPropertyName + " = ? ");
                    if (i + 1 < restrictToProperties.getEntryCount()) {
                        propertyQuery.append(" OR ");
                    }
                }
                propertyQuery.append(")");

            }

            if (restrictToPropertyTypes != null && restrictToPropertyTypes.length > 0) {
                propertyQuery.append(" AND (");

                for (int i = 0; i < restrictToPropertyTypes.length; i++) {
                    propertyQuery.append(" " + SQLTableConstants.TBLCOL_PROPERTYTYPE + " = ? ");
                    if (i + 1 < restrictToPropertyTypes.length) {
                        propertyQuery.append(" OR ");
                    }
                }
                propertyQuery.append(")");

            }

            getEntityProperties = si.modifyAndCheckOutPreparedStatement(propertyQuery.toString());

            int i = 1;
            getEntityProperties.setString(i++, code);
            getEntityProperties.setString(i++, internalCodingSchemeName);
            if (si.supports2009Model()) {
                getEntityProperties.setString(i++, namespace);
            }

            if (restrictToProperties != null && restrictToProperties.getEntryCount() > 0) {
                for (int j = 0; j < restrictToProperties.getEntryCount(); j++) {
                    getEntityProperties.setString(i++, restrictToProperties.getEntry(j));
                }
            }
            if (restrictToPropertyTypes != null && restrictToPropertyTypes.length > 0) {
                for (int j = 0; j < restrictToPropertyTypes.length; j++) {
                    String pts = RestrictionImplementations.mapPropertyType(restrictToPropertyTypes[j]);
                    getEntityProperties.setString(i++, pts);
                }
            }

            results = getEntityProperties.executeQuery();

            // store the property from the last row
            org.LexGrid.commonTypes.Property newProperty = null;

            // all of the fields that come from the Property table
            String propertyType, property, propertyValue, language, presentationFormat, degreeOfFidelity,
                    propertyId, representationalForm;
            Boolean matchIfNoContext, isPreferred;

            // holders for attributes, qualifiers
            Hashtable<String, Source> sources = null;
            HashSet<String> usageContexts = null;
            Hashtable<String, PropertyQualifier> propertyQualifiers = null;

            // As I process the result rows, I will get back duplicates of
            // the property information
            // if the property has more than one qualifer and/or source ,
            // etc.

            while (results.next()) {
                propertyId = results.getString(SQLTableConstants.TBLCOL_PROPERTYID);

                if (newProperty == null || !propertyId.equals(newProperty.getPropertyId())) {
                    // not equal means we have started a new property
                    property = results.getString(si.getSQLTableConstants().propertyOrPropertyName);
                    propertyType = results.getString(SQLTableConstants.TBLCOL_PROPERTYTYPE);
                    propertyValue = results.getString(SQLTableConstants.TBLCOL_PROPERTYVALUE);
                    language = results.getString(SQLTableConstants.TBLCOL_LANGUAGE);
                    presentationFormat = results
                            .getString(si.getSQLTableConstants().formatOrPresentationFormat);
                    degreeOfFidelity = results.getString(SQLTableConstants.TBLCOL_DEGREEOFFIDELITY);
                    representationalForm = results.getString(SQLTableConstants.TBLCOL_REPRESENTATIONALFORM);
                    matchIfNoContext = DBUtility.getBooleanFromResultSet(results,
                            SQLTableConstants.TBLCOL_MATCHIFNOCONTEXT);
                    isPreferred = DBUtility.getBooleanFromResultSet(results,
                            SQLTableConstants.TBLCOL_ISPREFERRED);

                    // add all of the collected sources, usage contexts, and
                    // qualifiers to
                    // the previous property
                    if (newProperty != null) {
                        newProperty.setSource(sources.values().toArray(new Source[sources.size()]));
                        newProperty.setUsageContext(usageContexts.toArray(new String[usageContexts.size()]));
                        if (!propertyQualifiers.isEmpty())
                            newProperty.setPropertyQualifier(propertyQualifiers.values()
                                    .toArray(new PropertyQualifier[propertyQualifiers.size()]));
                    }

                    // we are starting a new property, so clear out the old
                    // holders.
                    sources = new Hashtable<String, Source>();
                    usageContexts = new HashSet<String>();
                    propertyQualifiers = new Hashtable<String, PropertyQualifier>();

                    // process the property portion of the result
                    if (propertyType.equals(SQLTableConstants.TBLCOLVAL_DEFINITION)) {
                        Definition def = new Definition();
                        def.setIsPreferred(isPreferred);
                        def.setLanguage(language);
                        def.setPropertyName(property);
                        def.setPropertyId(propertyId);
                        Text text = new Text();
                        text.setContent(propertyValue);
                        text.setDataType(presentationFormat);
                        def.setValue(text);
                        definitions.add(def);
                        newProperty = def;
                    } else if (propertyType.equals(SQLTableConstants.TBLCOLVAL_PRESENTATION)) {
                        Presentation presentation = new Presentation();
                        presentation.setIsPreferred(isPreferred);
                        presentation.setLanguage(language);
                        presentation.setPropertyName(property);
                        presentation.setPropertyId(propertyId);
                        Text text = new Text();
                        text.setContent(propertyValue);
                        text.setDataType(presentationFormat);
                        presentation.setValue(text);
                        presentation.setDegreeOfFidelity(degreeOfFidelity);
                        presentation.setMatchIfNoContext(matchIfNoContext);
                        presentation.setRepresentationalForm(representationalForm);

                        presentations.add(presentation);
                        newProperty = presentation;
                    } else if (propertyType.equals(SQLTableConstants.TBLCOLVAL_COMMENT)) {
                        Comment comment = new Comment();
                        comment.setLanguage(language);
                        comment.setPropertyName(property);
                        comment.setPropertyId(propertyId);
                        Text text = new Text();
                        text.setContent(propertyValue);
                        text.setDataType(presentationFormat);
                        comment.setValue(text);
                        comments.add(comment);
                        newProperty = comment;
                    } else {
                        Property theProperty = new Property();
                        theProperty.setLanguage(language);
                        theProperty.setPropertyName(property);
                        theProperty.setPropertyId(propertyId);
                        Text text = new Text();
                        text.setContent(propertyValue);
                        text.setDataType(presentationFormat);
                        theProperty.setValue(text);
                        properties.add(theProperty);
                        newProperty = theProperty;
                    }

                    newProperty.setPropertyType(propertyType);

                    if (si.supports2009Model()) {

                        String owner = results.getString(SQLTableConstants.TBLCOL_OWNER);
                        String status = results.getString(SQLTableConstants.TBLCOL_STATUS);
                        Timestamp effectiveDate = results.getTimestamp(SQLTableConstants.TBLCOL_EFFECTIVEDATE);
                        Timestamp expirationDate = results
                                .getTimestamp(SQLTableConstants.TBLCOL_EXPIRATIONDATE);
                        String revisionId = results.getString(SQLTableConstants.TBLCOL_REVISIONID);
                        String prevRevisionId = results.getString(SQLTableConstants.TBLCOL_PREVREVISIONID);
                        String changeType = results.getString(SQLTableConstants.TBLCOL_CHANGETYPE);
                        String relativeOrder = results.getString(SQLTableConstants.TBLCOL_RELATIVEORDER);

                        if (revisionId != null) {
                            EntryState es = new EntryState();
                            if (!StringUtils.isBlank(changeType)) {
                                es.setChangeType(org.LexGrid.versions.types.ChangeType.valueOf(changeType));
                            }
                            es.setContainingRevision(revisionId);
                            es.setPrevRevision(prevRevisionId);
                            es.setRelativeOrder(computeRelativeOrder(relativeOrder));

                            newProperty.setEntryState(es);
                        }

                        if (owner != null) {
                            newProperty.setOwner(owner);
                        }

                        if (status != null)
                            newProperty.setStatus(status);
                        if (effectiveDate != null)
                            newProperty.setEffectiveDate(effectiveDate);
                        if (expirationDate != null)
                            newProperty.setExpirationDate(expirationDate);
                    }
                }

                String type = null;
                String value = null;
                String val1 = null;
                String val2 = null;

                // collect values from the multiAttributes table
                type = results.getString(SQLTableConstants.TBLCOL_TYPENAME);
                value = results.getString(SQLTableConstants.TBLCOL_ATTRIBUTEVALUE);
                val1 = results.getString(SQLTableConstants.TBLCOL_VAL1);
                if (StringUtils.isBlank(val1))
                    val1 = null;
                val2 = results.getString(SQLTableConstants.TBLCOL_VAL2);
                if (StringUtils.isBlank(val2))
                    val2 = null;

                // hashsets to remove dupes (table doesn't allow dupes, but
                // left join will create some)
                if (type != null) {
                    if (type.equalsIgnoreCase(SQLTableConstants.TBLCOLVAL_SOURCE)) {
                        if (!sources.containsKey(createUniqueKeyForSource(value, val1))) {
                            Source s = new Source();
                            s.setContent(value);
                            s.setRole(val2);
                            s.setSubRef(val1);
                            sources.put(createUniqueKeyForSource(value, val1), s);
                        }
                    } else if (type.equalsIgnoreCase(SQLTableConstants.TBLCOLVAL_USAGECONTEXT)) {
                        usageContexts.add(value);
                    } else if (type.equalsIgnoreCase(SQLTableConstants.TBLCOLVAL_QUALIFIER)) {
                        // nulls are a side affect of left join
                        if (!propertyQualifiers.containsKey(val1 + ":" + value)) {
                            PropertyQualifier pq = new PropertyQualifier();
                            Text txt = new Text();
                            txt.setContent(val1);
                            pq.setValue(txt);
                            pq.setPropertyQualifierName(value);
                            propertyQualifiers.put(val1 + ":" + value, pq);
                        }
                    } else {
                        getLogger().warn("There is invalid data in the 'typeName' column in the table "
                                + si.getTableName(SQLTableConstants.ENTITY_PROPERTY_MULTI_ATTRIBUTES)
                                + " for the concept code: " + code + " propertyId: " + propertyId
                                + " codingSchemeName: " + internalCodingSchemeName);
                    }
                }
            }

            // add all of the collected sources, usage contexts, and
            // qualifiers to
            // the previous property before exiting ...
            if (newProperty != null) {
                newProperty.setSource(sources.values().toArray(new Source[sources.size()]));
                newProperty.setUsageContext(usageContexts.toArray(new String[usageContexts.size()]));
                if (!propertyQualifiers.isEmpty())
                    newProperty.setPropertyQualifier(propertyQualifiers.values()
                            .toArray(new PropertyQualifier[propertyQualifiers.size()]));
            }
            results.close();
        } finally {
            si.checkInPreparedStatement(getEntityCode);
            si.checkInPreparedStatement(getEntityProperties);
            si.checkInPreparedStatement(getPropertyLinks);
        }

        concept.setComment(comments.toArray(new Comment[comments.size()]));
        concept.setDefinition(definitions.toArray(new Definition[definitions.size()]));
        concept.setPropertyLink(links.toArray(new PropertyLink[links.size()]));
        concept.setPresentation(presentations.toArray(new Presentation[presentations.size()]));
        concept.setProperty(properties.toArray(new Property[properties.size()]));
        return concept;
    } catch (MissingResourceException e) {
        throw e;
    } catch (Exception e) {
        throw new UnexpectedInternalError("There was an unexpected internal error.", e);
    }
}

From source file:org.gss_project.gss.server.rest.Webdav.java

/**
 * Delete a resource.//w w w. j av  a  2  s. com
 *
 * @param path Path of the resource which is to be deleted
 * @param req Servlet request
 * @param resp Servlet response
 * @param setStatus Should the response status be set on successful
 *            completion
 * @return boolean true if the deletion is successful
 * @throws IOException
 */
private boolean deleteResource(String path, HttpServletRequest req, HttpServletResponse resp, boolean setStatus)
        throws IOException {
    if (path.toUpperCase().startsWith("/WEB-INF") || path.toUpperCase().startsWith("/META-INF")) {
        resp.sendError(WebdavStatus.SC_FORBIDDEN);
        return false;
    }
    String ifHeader = req.getHeader("If");
    if (ifHeader == null)
        ifHeader = "";

    String lockTokenHeader = req.getHeader("Lock-Token");
    if (lockTokenHeader == null)
        lockTokenHeader = "";

    if (isLocked(path, ifHeader + lockTokenHeader)) {
        resp.sendError(WebdavStatus.SC_LOCKED);
        return false;
    }

    final User user = getUser(req);
    boolean exists = true;
    Object object = null;
    try {
        object = getService().getResourceAtPath(user.getId(), path, true);
    } catch (ObjectNotFoundException e) {
        exists = false;
    } catch (RpcException e) {
        resp.sendError(WebdavStatus.SC_INTERNAL_SERVER_ERROR);
        return false;
    }

    if (!exists) {
        resp.sendError(WebdavStatus.SC_NOT_FOUND);
        return false;
    }

    Folder folderLocal = null;
    FileHeader fileLocal = null;
    if (object instanceof Folder)
        folderLocal = (Folder) object;
    else
        fileLocal = (FileHeader) object;

    if (fileLocal != null)
        try {
            final FileHeader f = fileLocal;
            new TransactionHelper<Void>().tryExecute(new Callable<Void>() {
                @Override
                public Void call() throws Exception {
                    getService().deleteFile(user.getId(), f.getId());
                    return null;
                }
            });
        } catch (InsufficientPermissionsException e) {
            resp.sendError(WebdavStatus.SC_METHOD_NOT_ALLOWED);
            return false;
        } catch (ObjectNotFoundException e) {
            // Although we had already found the object, it was
            // probably deleted from another thread.
            resp.sendError(WebdavStatus.SC_NOT_FOUND);
            return false;
        } catch (RpcException e) {
            resp.sendError(WebdavStatus.SC_INTERNAL_SERVER_ERROR);
            return false;
        } catch (Exception e) {
            resp.sendError(WebdavStatus.SC_INTERNAL_SERVER_ERROR);
            return false;
        }
    else if (folderLocal != null) {
        Hashtable<String, Integer> errorList = new Hashtable<String, Integer>();
        deleteCollection(req, folderLocal, path, errorList);
        try {
            final Folder f = folderLocal;
            new TransactionHelper<Void>().tryExecute(new Callable<Void>() {
                @Override
                public Void call() throws Exception {
                    getService().deleteFolder(user.getId(), f.getId());
                    return null;
                }
            });
        } catch (InsufficientPermissionsException e) {
            errorList.put(path, new Integer(WebdavStatus.SC_METHOD_NOT_ALLOWED));
        } catch (ObjectNotFoundException e) {
            errorList.put(path, new Integer(WebdavStatus.SC_NOT_FOUND));
        } catch (RpcException e) {
            errorList.put(path, new Integer(WebdavStatus.SC_INTERNAL_SERVER_ERROR));
        } catch (Exception e) {
            errorList.put(path, new Integer(WebdavStatus.SC_INTERNAL_SERVER_ERROR));
        }

        if (!errorList.isEmpty()) {
            sendReport(req, resp, errorList);
            return false;
        }
    }
    if (setStatus)
        resp.setStatus(WebdavStatus.SC_NO_CONTENT);
    return true;
}