Example usage for org.dom4j Document addComment

List of usage examples for org.dom4j Document addComment

Introduction

In this page you can find the example usage for org.dom4j Document addComment.

Prototype

Document addComment(String comment);

Source Link

Document

Adds a new Comment node with the given text to this branch.

Usage

From source file:org.cpsolver.instructor.model.InstructorSchedulingModel.java

License:Open Source License

/**
 * Store the problem (together with its solution) in an XML format
 * @param assignment current assignment//from  w  ww. j a va2s .  co m
 * @return XML document with the problem
 */
public Document save(Assignment<TeachingRequest.Variable, TeachingAssignment> assignment) {
    DecimalFormat sDF7 = new DecimalFormat("0000000");
    boolean saveInitial = getProperties().getPropertyBoolean("Xml.SaveInitial", false);
    boolean saveBest = getProperties().getPropertyBoolean("Xml.SaveBest", false);
    boolean saveSolution = getProperties().getPropertyBoolean("Xml.SaveSolution", true);
    Document document = DocumentHelper.createDocument();
    if (assignment != null && assignment.nrAssignedVariables() > 0) {
        StringBuffer comments = new StringBuffer("Solution Info:\n");
        Map<String, String> solutionInfo = (getProperties().getPropertyBoolean("Xml.ExtendedInfo", true)
                ? getExtendedInfo(assignment)
                : getInfo(assignment));
        for (String key : new TreeSet<String>(solutionInfo.keySet())) {
            String value = solutionInfo.get(key);
            comments.append("    " + key + ": " + value + "\n");
        }
        document.addComment(comments.toString());
    }
    Element root = document.addElement("instructor-schedule");
    root.addAttribute("version", "1.0");
    root.addAttribute("created", String.valueOf(new Date()));
    Element typesEl = root.addElement("attributes");
    for (Attribute.Type type : getAttributeTypes()) {
        Element typeEl = typesEl.addElement("type");
        if (type.getTypeId() != null)
            typeEl.addAttribute("id", String.valueOf(type.getTypeId()));
        typeEl.addAttribute("name", type.getTypeName());
        typeEl.addAttribute("conjunctive", type.isConjunctive() ? "true" : "false");
        typeEl.addAttribute("required", type.isRequired() ? "true" : "false");
        Set<Attribute> attributes = new HashSet<Attribute>();
        for (TeachingRequest request : getRequests()) {
            for (Preference<Attribute> pref : request.getAttributePreferences()) {
                Attribute attribute = pref.getTarget();
                if (type.equals(attribute.getType()) && attributes.add(attribute)) {
                    Element attributeEl = typeEl.addElement("attribute");
                    if (attribute.getAttributeId() != null)
                        attributeEl.addAttribute("id", String.valueOf(attribute.getAttributeId()));
                    attributeEl.addAttribute("name", attribute.getAttributeName());
                }
            }
            for (Instructor instructor : getInstructors()) {
                for (Attribute attribute : instructor.getAttributes()) {
                    if (type.equals(attribute.getType()) && attributes.add(attribute)) {
                        Element attributeEl = typeEl.addElement("attribute");
                        if (attribute.getAttributeId() != null)
                            attributeEl.addAttribute("id", String.valueOf(attribute.getAttributeId()));
                        attributeEl.addAttribute("name", attribute.getAttributeName());
                    }
                }
            }
        }
    }
    Element requestsEl = root.addElement("teaching-requests");
    for (TeachingRequest request : getRequests()) {
        Element requestEl = requestsEl.addElement("request");
        requestEl.addAttribute("id", String.valueOf(request.getRequestId()));
        if (request.getNrInstructors() != 1)
            requestEl.addAttribute("nrInstructors", String.valueOf(request.getNrInstructors()));
        Course course = request.getCourse();
        Element courseEl = requestEl.addElement("course");
        if (course.getCourseId() != null)
            courseEl.addAttribute("id", String.valueOf(course.getCourseId()));
        if (course.getCourseName() != null)
            courseEl.addAttribute("name", String.valueOf(course.getCourseName()));
        for (Section section : request.getSections()) {
            Element sectionEl = requestEl.addElement("section");
            sectionEl.addAttribute("id", String.valueOf(section.getSectionId()));
            if (section.getExternalId() != null && !section.getExternalId().isEmpty())
                sectionEl.addAttribute("externalId", section.getExternalId());
            if (section.getSectionType() != null && !section.getSectionType().isEmpty())
                sectionEl.addAttribute("type", section.getSectionType());
            if (section.getSectionName() != null && !section.getSectionName().isEmpty())
                sectionEl.addAttribute("name", section.getSectionName());
            if (section.hasTime()) {
                TimeLocation tl = section.getTime();
                Element timeEl = sectionEl.addElement("time");
                timeEl.addAttribute("days",
                        sDF7.format(Long.parseLong(Integer.toBinaryString(tl.getDayCode()))));
                timeEl.addAttribute("start", String.valueOf(tl.getStartSlot()));
                timeEl.addAttribute("length", String.valueOf(tl.getLength()));
                if (tl.getBreakTime() != 0)
                    timeEl.addAttribute("breakTime", String.valueOf(tl.getBreakTime()));
                if (tl.getTimePatternId() != null)
                    timeEl.addAttribute("pattern", tl.getTimePatternId().toString());
                if (tl.getDatePatternId() != null)
                    timeEl.addAttribute("datePattern", tl.getDatePatternId().toString());
                if (tl.getDatePatternName() != null && !tl.getDatePatternName().isEmpty())
                    timeEl.addAttribute("datePatternName", tl.getDatePatternName());
                if (tl.getWeekCode() != null)
                    timeEl.addAttribute("dates", bitset2string(tl.getWeekCode()));
                timeEl.setText(tl.getLongName(false));
            }
            if (section.hasRoom())
                sectionEl.addAttribute("room", section.getRoom());
            if (section.isAllowOverlap())
                sectionEl.addAttribute("canOverlap", "true");
            if (section.isCommon())
                sectionEl.addAttribute("common", "true");
        }
        requestEl.addAttribute("load", sDoubleFormat.format(request.getLoad()));
        requestEl.addAttribute("sameCourse",
                Constants.preferenceLevel2preference(request.getSameCoursePreference()));
        requestEl.addAttribute("sameCommon",
                Constants.preferenceLevel2preference(request.getSameCommonPreference()));
        for (Preference<Attribute> pref : request.getAttributePreferences()) {
            Element attributeEl = requestEl.addElement("attribute");
            if (pref.getTarget().getAttributeId() != null)
                attributeEl.addAttribute("id", String.valueOf(pref.getTarget().getAttributeId()));
            attributeEl.addAttribute("name", pref.getTarget().getAttributeName());
            attributeEl.addAttribute("type", pref.getTarget().getType().getTypeName());
            attributeEl.addAttribute("preference", (pref.isRequired() ? "R"
                    : pref.isProhibited() ? "P" : String.valueOf(pref.getPreference())));
        }
        for (Preference<Instructor> pref : request.getInstructorPreferences()) {
            Element instructorEl = requestEl.addElement("instructor");
            instructorEl.addAttribute("id", String.valueOf(pref.getTarget().getInstructorId()));
            if (pref.getTarget().hasExternalId())
                instructorEl.addAttribute("externalId", pref.getTarget().getExternalId());
            if (pref.getTarget().hasName())
                instructorEl.addAttribute("name", pref.getTarget().getName());
            instructorEl.addAttribute("preference", (pref.isRequired() ? "R"
                    : pref.isProhibited() ? "P" : String.valueOf(pref.getPreference())));
        }
        if (saveBest)
            for (TeachingRequest.Variable variable : request.getVariables()) {
                if (variable.getBestAssignment() != null) {
                    Instructor instructor = variable.getBestAssignment().getInstructor();
                    Element instructorEl = requestEl.addElement("best-instructor");
                    instructorEl.addAttribute("id", String.valueOf(instructor.getInstructorId()));
                    if (request.getNrInstructors() != 1)
                        instructorEl.addAttribute("index", String.valueOf(variable.getInstructorIndex()));
                    if (instructor.hasExternalId())
                        instructorEl.addAttribute("externalId", instructor.getExternalId());
                    if (instructor.hasName())
                        instructorEl.addAttribute("name", instructor.getName());
                }
            }
        if (saveInitial)
            for (TeachingRequest.Variable variable : request.getVariables()) {
                if (variable.getInitialAssignment() != null) {
                    Instructor instructor = variable.getInitialAssignment().getInstructor();
                    Element instructorEl = requestEl.addElement("initial-instructor");
                    instructorEl.addAttribute("id", String.valueOf(instructor.getInstructorId()));
                    if (request.getNrInstructors() != 1)
                        instructorEl.addAttribute("index", String.valueOf(variable.getInstructorIndex()));
                    if (instructor.hasExternalId())
                        instructorEl.addAttribute("externalId", instructor.getExternalId());
                    if (instructor.hasName())
                        instructorEl.addAttribute("name", instructor.getName());
                }
            }
        if (saveSolution)
            for (TeachingRequest.Variable variable : request.getVariables()) {
                TeachingAssignment ta = assignment.getValue(variable);
                if (ta != null) {
                    Instructor instructor = ta.getInstructor();
                    Element instructorEl = requestEl.addElement("assigned-instructor");
                    instructorEl.addAttribute("id", String.valueOf(instructor.getInstructorId()));
                    if (request.getNrInstructors() != 1)
                        instructorEl.addAttribute("index", String.valueOf(variable.getInstructorIndex()));
                    if (instructor.hasExternalId())
                        instructorEl.addAttribute("externalId", instructor.getExternalId());
                    if (instructor.hasName())
                        instructorEl.addAttribute("name", instructor.getName());
                }
            }
    }
    Element instructorsEl = root.addElement("instructors");
    for (Instructor instructor : getInstructors()) {
        Element instructorEl = instructorsEl.addElement("instructor");
        instructorEl.addAttribute("id", String.valueOf(instructor.getInstructorId()));
        if (instructor.hasExternalId())
            instructorEl.addAttribute("externalId", instructor.getExternalId());
        if (instructor.hasName())
            instructorEl.addAttribute("name", instructor.getName());
        if (instructor.getPreference() != 0)
            instructorEl.addAttribute("preference", String.valueOf(instructor.getPreference()));
        if (instructor.getBackToBackPreference() != 0)
            instructorEl.addAttribute("btb", String.valueOf(instructor.getBackToBackPreference()));
        if (instructor.getSameDaysPreference() != 0)
            instructorEl.addAttribute("same-days", String.valueOf(instructor.getSameDaysPreference()));
        if (instructor.getSameRoomPreference() != 0)
            instructorEl.addAttribute("same-room", String.valueOf(instructor.getSameRoomPreference()));
        for (Attribute attribute : instructor.getAttributes()) {
            Element attributeEl = instructorEl.addElement("attribute");
            if (attribute.getAttributeId() != null)
                attributeEl.addAttribute("id", String.valueOf(attribute.getAttributeId()));
            attributeEl.addAttribute("name", attribute.getAttributeName());
            attributeEl.addAttribute("type", attribute.getType().getTypeName());
        }
        instructorEl.addAttribute("maxLoad", sDoubleFormat.format(instructor.getMaxLoad()));
        for (Preference<TimeLocation> tp : instructor.getTimePreferences()) {

            Element timeEl = instructorEl.addElement("time");
            TimeLocation tl = tp.getTarget();
            timeEl.addAttribute("days", sDF7.format(Long.parseLong(Integer.toBinaryString(tl.getDayCode()))));
            timeEl.addAttribute("start", String.valueOf(tl.getStartSlot()));
            timeEl.addAttribute("length", String.valueOf(tl.getLength()));
            if (tl.getBreakTime() != 0)
                timeEl.addAttribute("breakTime", String.valueOf(tl.getBreakTime()));
            if (tl.getTimePatternId() != null)
                timeEl.addAttribute("pattern", tl.getTimePatternId().toString());
            if (tl.getDatePatternId() != null)
                timeEl.addAttribute("datePattern", tl.getDatePatternId().toString());
            if (tl.getDatePatternName() != null && !tl.getDatePatternName().isEmpty())
                timeEl.addAttribute("datePatternName", tl.getDatePatternName());
            if (tl.getWeekCode() != null)
                timeEl.addAttribute("dates", bitset2string(tl.getWeekCode()));
            timeEl.addAttribute("preference",
                    tp.isProhibited() ? "P" : tp.isRequired() ? "R" : String.valueOf(tp.getPreference()));
            if (tp.getTarget() instanceof EnrolledClass) {
                Element classEl = timeEl.addElement("section");
                Element courseEl = null;
                EnrolledClass ec = (EnrolledClass) tp.getTarget();
                if (ec.getCourseId() != null || ec.getCourse() != null) {
                    courseEl = timeEl.addElement("course");
                    if (ec.getCourseId() != null)
                        courseEl.addAttribute("id", String.valueOf(ec.getCourseId()));
                    if (ec.getCourse() != null)
                        courseEl.addAttribute("name", ec.getCourse());
                }
                if (ec.getClassId() != null)
                    classEl.addAttribute("id", String.valueOf(ec.getClassId()));
                if (ec.getType() != null)
                    classEl.addAttribute("type", ec.getType());
                if (ec.getSection() != null)
                    classEl.addAttribute("name", ec.getSection());
                if (ec.getExternalId() != null)
                    classEl.addAttribute("externalId", ec.getExternalId());
                if (ec.getRoom() != null)
                    classEl.addAttribute("room", ec.getRoom());
                classEl.addAttribute("role", ec.isInstructor() ? "instructor" : "student");
            } else {
                timeEl.setText(tl.getLongName(false));
            }
        }
        for (Preference<Course> cp : instructor.getCoursePreferences()) {
            Element courseEl = instructorEl.addElement("course");
            Course course = cp.getTarget();
            if (course.getCourseId() != null)
                courseEl.addAttribute("id", String.valueOf(course.getCourseId()));
            if (course.getCourseName() != null)
                courseEl.addAttribute("name", String.valueOf(course.getCourseName()));
            courseEl.addAttribute("preference",
                    cp.isProhibited() ? "P" : cp.isRequired() ? "R" : String.valueOf(cp.getPreference()));
        }
    }
    Element constraintsEl = root.addElement("constraints");
    for (Constraint<TeachingRequest.Variable, TeachingAssignment> c : constraints()) {
        if (c instanceof SameInstructorConstraint) {
            SameInstructorConstraint si = (SameInstructorConstraint) c;
            Element sameInstEl = constraintsEl.addElement("same-instructor");
            if (si.getConstraintId() != null)
                sameInstEl.addAttribute("id", String.valueOf(si.getConstraintId()));
            if (si.getName() != null)
                sameInstEl.addAttribute("name", si.getName());
            sameInstEl.addAttribute("preference", Constants.preferenceLevel2preference(si.getPreference()));
            for (TeachingRequest.Variable request : c.variables()) {
                Element assignmentEl = sameInstEl.addElement("request");
                assignmentEl.addAttribute("id", String.valueOf(request.getRequest().getRequestId()));
                if (request.getRequest().getNrInstructors() != 1)
                    assignmentEl.addAttribute("index", String.valueOf(request.getInstructorIndex()));
            }
        } else if (c instanceof SameLinkConstraint) {
            SameLinkConstraint si = (SameLinkConstraint) c;
            Element sameInstEl = constraintsEl.addElement("same-link");
            if (si.getConstraintId() != null)
                sameInstEl.addAttribute("id", String.valueOf(si.getConstraintId()));
            if (si.getName() != null)
                sameInstEl.addAttribute("name", si.getName());
            sameInstEl.addAttribute("preference", Constants.preferenceLevel2preference(si.getPreference()));
            for (TeachingRequest.Variable request : c.variables()) {
                Element assignmentEl = sameInstEl.addElement("request");
                assignmentEl.addAttribute("id", String.valueOf(request.getRequest().getRequestId()));
                if (request.getRequest().getNrInstructors() != 1)
                    assignmentEl.addAttribute("index", String.valueOf(request.getInstructorIndex()));
            }
        }
    }
    return document;
}

From source file:org.cpsolver.studentsct.StudentSectioningXMLSaver.java

License:Open Source License

/**
 * Save an XML file/*from w ww  .  j av a2s .c om*/
 * 
 * @param outFile
 *            output file
 * @throws Exception thrown when the save fails
 */
public void save(File outFile) throws Exception {
    if (outFile == null) {
        outFile = new File(iOutputFolder, "solution.xml");
    } else if (outFile.getParentFile() != null) {
        outFile.getParentFile().mkdirs();
    }
    sLogger.debug("Writting XML data to:" + outFile);

    Document document = DocumentHelper.createDocument();
    document.addComment("Student Sectioning");

    populate(document);

    FileOutputStream fos = null;
    try {
        fos = new FileOutputStream(outFile);
        (new XMLWriter(fos, OutputFormat.createPrettyPrint())).write(document);
        fos.flush();
        fos.close();
        fos = null;
    } finally {
        try {
            if (fos != null)
                fos.close();
        } catch (IOException e) {
        }
    }

    if (iConvertIds)
        IdConvertor.getInstance().save();
}

From source file:org.cpsolver.studentsct.StudentSectioningXMLSaver.java

License:Open Source License

public Document saveDocument() {
    Document document = DocumentHelper.createDocument();
    document.addComment("Student Sectioning");

    populate(document);//from  w  w  w . ja  v a 2  s.  c om

    return document;
}

From source file:org.cpsolver.studentsct.StudentSectioningXMLSaver.java

License:Open Source License

/**
 * Fill in all the data into the given document
 * @param document document to be populated
 *//* w w w  . ja va2 s . c  om*/
protected void populate(Document document) {
    if (iSaveCurrent || iSaveBest) {
        StringBuffer comments = new StringBuffer("Solution Info:\n");
        Map<String, String> solutionInfo = (getSolution() == null ? getModel().getExtendedInfo(getAssignment())
                : getSolution().getExtendedInfo());
        for (String key : new TreeSet<String>(solutionInfo.keySet())) {
            String value = solutionInfo.get(key);
            comments.append("    " + key + ": " + value + "\n");
        }
        document.addComment(comments.toString());
    }

    Element root = document.addElement("sectioning");
    root.addAttribute("version", "1.0");
    root.addAttribute("initiative", getModel().getProperties().getProperty("Data.Initiative"));
    root.addAttribute("term", getModel().getProperties().getProperty("Data.Term"));
    root.addAttribute("year", getModel().getProperties().getProperty("Data.Year"));
    root.addAttribute("created", String.valueOf(new Date()));

    saveOfferings(root);

    saveStudents(root);

    saveLinkedSections(root);

    saveTravelTimes(root);

    if (iShowNames) {
        Progress.getInstance(getModel()).save(root);
    }
}

From source file:org.openbravo.dal.xml.ModelXMLConverter.java

License:Open Source License

/**
 * Generates the XML Schema representation of the in-memory model. This XML Schema represents the
 * in- and output of the REST web-services.
 * /*w ww.j a v a  2s  .co m*/
 * @return the Dom4j document containing the XML Schema.
 */
public Document getSchema() {
    final Document doc = XMLUtil.getInstance().createDomDocument();
    doc.addComment("\n* ***********************************************************************************\n"
            + "* The contents of this file are subject to the Openbravo  Public  License"
            + "* Version  1.1  (the  \"License\"),  being   the  Mozilla   Public  License"
            + "* Version 1.1  with a permitted attribution clause; you may not  use this"
            + "* file except in compliance with the License. You  may  obtain  a copy of"
            + "* the License at http://www.openbravo.com/legal/license.html "
            + "* Software distributed under the License  is  distributed  on  an \"AS IS\""
            + "* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the"
            + "* License for the specific  language  governing  rights  and  limitations"
            + "* under the License. " + "* The Original Code is Openbravo ERP. "
            + "* The Initial Developer of the Original Code is Openbravo SLU"
            + "* All portions are Copyright (C) 2008-2011 Openbravo SLU" + "* All Rights Reserved. "
            + "* Contributor(s):  ______________________________________."
            + "* ***********************************************************************************\n");
    final Element root = doc.addElement("xs:schema");
    root.addNamespace("xs", "http://www.w3.org/2001/XMLSchema");
    root.addNamespace("ob", "http://www.openbravo.com");
    root.addAttribute("targetNamespace", "http://www.openbravo.com");

    final List<String> entityNames = new ArrayList<String>();
    for (final Entity e : ModelProvider.getInstance().getModel()) {
        entityNames.add(e.getName());
    }
    Collections.sort(entityNames);

    final Element rootElement = root.addElement("xs:element");
    rootElement.addAttribute("name", XMLConstants.OB_ROOT_ELEMENT);
    final Element complexType = rootElement.addElement("xs:complexType");
    final Element choiceElement = complexType.addElement("xs:choice");
    choiceElement.addAttribute("minOccurs", "0");
    choiceElement.addAttribute("maxOccurs", "unbounded");

    complexType.addElement("xs:attribute").addAttribute("name", XMLConstants.DATE_TIME_ATTRIBUTE)
            .addAttribute("type", "xs:string").addAttribute("use", "optional");
    complexType.addElement("xs:attribute").addAttribute("name", XMLConstants.OB_VERSION_ATTRIBUTE)
            .addAttribute("type", "xs:string").addAttribute("use", "optional");
    complexType.addElement("xs:attribute").addAttribute("name", XMLConstants.OB_REVISION_ATTRIBUTE)
            .addAttribute("type", "xs:string").addAttribute("use", "optional");

    for (final String entityName : entityNames) {
        final Element entityElement = choiceElement.addElement("xs:element");
        entityElement.addAttribute("name", entityName);
        entityElement.addAttribute("type", "ob:" + entityName + "Type");
    }

    for (final String entityName : entityNames) {
        final Element typeElement = root.addElement("xs:complexType");
        typeElement.addAttribute("name", entityName + "Type");

        final Element typeSequenceElement = typeElement.addElement("xs:sequence");
        typeSequenceElement.addAttribute("minOccurs", "0");

        addPropertyElements(typeSequenceElement, ModelProvider.getInstance().getEntity(entityName));

        typeElement.addElement("xs:attribute").addAttribute("name", XMLConstants.ID_ATTRIBUTE)
                .addAttribute("type", "xs:string").addAttribute("use", "optional");
        typeElement.addElement("xs:attribute").addAttribute("name", XMLConstants.IDENTIFIER_ATTRIBUTE)
                .addAttribute("type", "xs:string").addAttribute("use", "optional");
        typeElement.addElement("xs:attribute").addAttribute("name", XMLConstants.REFERENCE_ATTRIBUTE)
                .addAttribute("type", "xs:boolean").addAttribute("use", "optional");
        typeElement.addElement("xs:anyAttribute");
    }

    addSimpleTypeDeclarations(root);
    addReferenceType(root);
    addErrorSchema(root);
    addResultSchema(root);

    return doc;
}

From source file:org.suren.autotest.web.framework.code.DefaultXmlDataSourceGenerator.java

License:Apache License

/**
 * ?xmldocument//from   w w  w.  j av  a 2s  .com
 * @param resPath
 * @return
 */
private Document prepareDoc(final String resPath) {
    ClassLoader clsLoader = this.getClass().getClassLoader();
    URL url = clsLoader.getResource(resPath);
    InputStream dsInput = null;
    try {
        if (url != null) {
            dsInput = url.openStream();
        }
    } catch (IOException e1) {
        e1.printStackTrace();
    }

    Document doc = null;
    if (dsInput != null) {
        try {
            doc = new SAXReader().read(dsInput);
        } catch (DocumentException e) {
            e.printStackTrace();
        }
    } else {
        doc = DocumentHelper.createDocument();
    }

    SimpleDateFormat dateFormat = new SimpleDateFormat();
    doc.addComment("Auto created by AutoTest, " + dateFormat.format(new Date()));

    SimpleNamespaceContext simpleNamespaceContext = new SimpleNamespaceContext();
    simpleNamespaceContext.addNamespace("ns", "http://datasource.surenpi.com");

    XPath xpath = new DefaultXPath("/ns:dataSources");
    xpath.setNamespaceContext(simpleNamespaceContext);

    //?
    Element dataSourcesEle = (Element) xpath.selectSingleNode(doc);
    if (dataSourcesEle == null) {
        String prefix = "suren";
        dataSourcesEle = doc.addElement(prefix + ":dataSources");

        dataSourcesEle.addNamespace(prefix, "http://datasource.surenpi.com");
        dataSourcesEle.addAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
        dataSourcesEle.addAttribute("xsi:schemaLocation", "http://datasource.surenpi.com "
                + "http://surenpi.com/schema/datasource/autotest.web.framework.datasource.xsd ");
    }

    return doc;
}

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

License:Open Source License

public static void main(String[] args) {
    try {// w ww  . j a v a 2 s. c om
        Properties props = new Properties();
        props.setProperty("log4j.rootLogger", "DEBUG, A1");
        props.setProperty("log4j.appender.A1", "org.apache.log4j.ConsoleAppender");
        props.setProperty("log4j.appender.A1.layout", "org.apache.log4j.PatternLayout");
        props.setProperty("log4j.appender.A1.layout.ConversionPattern", "%-5p %c{2}: %m%n");
        props.setProperty("log4j.logger.org.hibernate", "INFO");
        props.setProperty("log4j.logger.org.hibernate.cfg", "WARN");
        props.setProperty("log4j.logger.org.hibernate.cache.EhCacheProvider", "ERROR");
        props.setProperty("log4j.logger.org.unitime.commons.hibernate", "INFO");
        props.setProperty("log4j.logger.net", "INFO");
        PropertyConfigurator.configure(props);

        HibernateUtil.configureHibernate(ApplicationProperties.getProperties());

        org.hibernate.Session hibSession = new _RootDAO().getSession();

        Session session = Session.getSessionUsingInitiativeYearTerm(
                ApplicationProperties.getProperty("initiative", "PWL"),
                ApplicationProperties.getProperty("year", "2011"),
                ApplicationProperties.getProperty("term", "Fall"));

        if (session == null) {
            sLog.error(
                    "Academic session not found, use properties initiative, year, and term to set academic session.");
            System.exit(0);
        } else {
            sLog.info("Session: " + session);
        }

        DistributionType linkedSections = (DistributionType) hibSession
                .createQuery("select d from DistributionType d where d.reference = :type")
                .setString("type", "LINKED_SECTIONS").uniqueResult();

        BufferedReader r = new BufferedReader(new FileReader(ApplicationProperties.getProperty("file",
                "/Users/muller/Downloads/Fall 2011 LC Course Matrix.csv")));
        Document document = DocumentHelper.createDocument();
        document.addComment("Learning comunities for " + session);
        Element root = document.addElement("constraints");
        Element group = null;
        String line = null;
        DistributionPref dpLinkedSections = null;

        List<DistributionPref> distPrefs = new ArrayList<DistributionPref>();
        StudentGroupReservation reservation = null;
        List<StudentGroupReservation> reservations = new ArrayList<StudentGroupReservation>();
        StudentGroup studentGroup = null;
        List<StudentGroup> groups = new ArrayList<StudentGroup>();
        Map<SchedulingSubpart, Set<Class_>> classes = new HashMap<SchedulingSubpart, Set<Class_>>();

        while ((line = r.readLine()) != null) {
            if (line.trim().isEmpty()) {
                if (group != null) {
                    Set<Student> students = null;
                    for (Map.Entry<SchedulingSubpart, Set<Class_>> entry : classes.entrySet()) {
                        Set<Student> studentsThisSubpart = new HashSet<Student>();
                        for (Class_ c : entry.getValue())
                            for (StudentClassEnrollment e : c.getStudentEnrollments())
                                studentsThisSubpart.add(e.getStudent());
                        if (students == null) {
                            students = studentsThisSubpart;
                        } else {
                            for (Iterator<Student> i = students.iterator(); i.hasNext();) {
                                if (!studentsThisSubpart.contains(i.next()))
                                    i.remove();
                            }
                        }
                    }
                    studentGroup.setStudents(students);
                }
                group = null;
                continue;
            }
            String[] cols = line.split(",");
            if (cols.length <= 9) {
                sLog.info("Skipping " + line);
                continue;
            }
            if (group == null) {
                group = root.addElement("linked-sections");
                if (!cols[0].trim().isEmpty())
                    group.addAttribute("name", cols[0].trim());
                dpLinkedSections = new DistributionPref();
                dpLinkedSections.setDistributionType(linkedSections);
                dpLinkedSections.setPrefLevel(PreferenceLevel.getPreferenceLevel(PreferenceLevel.sRequired));
                dpLinkedSections.setGrouping(DistributionPref.sGroupingNone);
                dpLinkedSections.setDistributionObjects(new HashSet<DistributionObject>());
                distPrefs.add(dpLinkedSections);
                studentGroup = new StudentGroup();
                studentGroup.setGroupName(cols[0].trim());
                studentGroup.setGroupAbbreviation(abbv(cols[0].trim()));
                studentGroup.setSession(session);
                // studentGroup.setStudents(new HashSet<Student>());
                groups.add(studentGroup);
                reservation = new StudentGroupReservation();
                reservation.setClasses(new HashSet<Class_>());
                reservation.setGroup(studentGroup);
                reservations.add(reservation);
                classes.clear();
            }
            String crn = cols[2].trim();
            Class_ clazz = (Class_) hibSession.createQuery("from Class_ c where c.classSuffix like :crn and "
                    + "c.schedulingSubpart.instrOfferingConfig.instructionalOffering.session.uniqueId = :sessionId")
                    .setString("crn", crn + "%").setLong("sessionId", session.getUniqueId()).setMaxResults(1)
                    .uniqueResult();
            if (clazz != null) {
                group.addElement("section")
                        .addAttribute("offering",
                                clazz.getSchedulingSubpart().getInstrOfferingConfig().getInstructionalOffering()
                                        .getUniqueId().toString())
                        .addAttribute("id", clazz.getUniqueId().toString())
                        .addAttribute("name", clazz.getClassLabel());

                if (dpLinkedSections.getOwner() == null)
                    dpLinkedSections.setOwner(clazz.getManagingDept());
                else if (!dpLinkedSections.getOwner().equals(clazz.getManagingDept())
                        && ((Department) dpLinkedSections.getOwner()).getDistributionPrefPriority() < clazz
                                .getManagingDept().getDistributionPrefPriority())
                    dpLinkedSections.setOwner(clazz.getManagingDept());

                /*
                if (dpLinkedSections.getDistributionObjects().isEmpty()) {
                   for (StudentClassEnrollment enrl: clazz.getStudentEnrollments()) {
                studentGroup.getStudents().add(enrl.getStudent());
                   }
                } else {
                   students: for (Iterator<Student> i = studentGroup.getStudents().iterator(); i.hasNext(); ) {
                Student student = i.next();
                for (StudentClassEnrollment enrl: clazz.getStudentEnrollments()) {
                   if (student.equals(enrl.getStudent())) continue students;
                }
                i.remove();
                   }
                }
                */
                reservation.getClasses().add(clazz);
                Set<Class_> c = classes.get(clazz.getSchedulingSubpart());
                if (c == null) {
                    c = new HashSet<Class_>();
                    classes.put(clazz.getSchedulingSubpart(), c);
                }
                c.add(clazz);

                DistributionObject o = new DistributionObject();
                o.setDistributionPref(dpLinkedSections);
                o.setPrefGroup(clazz);
                o.setSequenceNumber(dpLinkedSections.getDistributionObjects().size());
                dpLinkedSections.getDistributionObjects().add(o);
            } else {
                sLog.warn("Unable to find class " + crn + " (" + cols[3] + " " + cols[4] + " " + cols[7] + " "
                        + cols[8] + " " + cols[9] + ")");
            }
        }
        r.close();

        (new XMLWriter(System.out, OutputFormat.createPrettyPrint())).write(document);

        for (StudentGroup g : groups) {
            sLog.info(g.getGroupAbbreviation() + ": " + g.getGroupName() + " has " + g.getStudents().size()
                    + " students.");
        }

        for (DistributionPref distPref : distPrefs) {
            for (DistributionObject obj : new ArrayList<DistributionObject>(
                    distPref.getDistributionObjects())) {
                Class_ p = ((Class_) obj.getPrefGroup()).getParentClass();
                while (p != null) {
                    for (DistributionObject x : distPref.getDistributionObjects()) {
                        if (x.getPrefGroup().equals(p)) {
                            distPref.getDistributionObjects().remove(x);
                            break;
                        }
                    }
                    p = p.getParentClass();
                }

            }
            if (distPref.getDistributionObjects().size() <= 1)
                continue;
            int idx = 0;
            for (DistributionObject obj : new TreeSet<DistributionObject>(distPref.getDistributionObjects()))
                obj.setSequenceNumber(idx++);
            hibSession.saveOrUpdate(distPref);
        }
        for (StudentGroup g : groups) {
            // if (g.getStudents().isEmpty()) continue;
            hibSession.saveOrUpdate(g);
        }

        for (StudentGroupReservation res : reservations) {
            // if (res.getGroup().getStudents().isEmpty()) continue;
            Map<InstructionalOffering, StudentGroupReservation> of2res = new HashMap<InstructionalOffering, StudentGroupReservation>();
            for (Class_ clazz : res.getClasses()) {
                InstructionalOffering offering = clazz.getSchedulingSubpart().getInstrOfferingConfig()
                        .getInstructionalOffering();
                StudentGroupReservation x = of2res.get(offering);
                if (x == null) {
                    x = new StudentGroupReservation();
                    x.setClasses(new HashSet<Class_>());
                    x.setGroup(res.getGroup());
                    x.setConfigurations(new HashSet<InstrOfferingConfig>());
                    x.setInstructionalOffering(offering);
                    x.setLimit(res.getGroup().getStudents().size());
                    of2res.put(offering, x);
                }
                x.getClasses().add(clazz);
                // x.getConfigurations().add(clazz.getSchedulingSubpart().getInstrOfferingConfig());
            }
            for (StudentGroupReservation x : of2res.values()) {
                for (Class_ c : new ArrayList<Class_>(x.getClasses())) {
                    Class_ p = c.getParentClass();
                    while (p != null) {
                        if (x.getClasses().contains(p))
                            x.getClasses().remove(p);
                        p = p.getParentClass();
                    }
                }
                hibSession.saveOrUpdate(x);
            }
        }

        hibSession.flush();

        sLog.info("All done.");
    } catch (Exception e) {
        e.printStackTrace();
    }
}