    001package org.cpsolver.studentsct;
    002
    003import java.io.File;
    004import java.io.FileOutputStream;
    005import java.io.IOException;
    006import java.math.RoundingMode;
    007import java.text.DecimalFormat;
    008import java.text.DecimalFormatSymbols;
    009import java.util.BitSet;
    010import java.util.Date;
    011import java.util.Locale;
    012import java.util.Map;
    013import java.util.Set;
    014import java.util.TreeSet;
    015
    016import org.cpsolver.coursett.IdConvertor;
    017import org.cpsolver.coursett.model.RoomLocation;
    018import org.cpsolver.coursett.model.TimeLocation;
    019import org.cpsolver.ifs.solver.Solver;
    020import org.cpsolver.ifs.util.Progress;
    021import org.cpsolver.studentsct.constraint.LinkedSections;
    022import org.cpsolver.studentsct.model.AreaClassificationMajor;
    023import org.cpsolver.studentsct.model.Choice;
    024import org.cpsolver.studentsct.model.Config;
    025import org.cpsolver.studentsct.model.Course;
    026import org.cpsolver.studentsct.model.CourseRequest;
    027import org.cpsolver.studentsct.model.Enrollment;
    028import org.cpsolver.studentsct.model.FreeTimeRequest;
    029import org.cpsolver.studentsct.model.Instructor;
    030import org.cpsolver.studentsct.model.Offering;
    031import org.cpsolver.studentsct.model.Request;
    032import org.cpsolver.studentsct.model.Request.RequestPriority;
    033import org.cpsolver.studentsct.model.RequestGroup;
    034import org.cpsolver.studentsct.model.Section;
    035import org.cpsolver.studentsct.model.Student;
    036import org.cpsolver.studentsct.model.Student.BackToBackPreference;
    037import org.cpsolver.studentsct.model.Student.ModalityPreference;
    038import org.cpsolver.studentsct.model.Student.StudentPriority;
    039import org.cpsolver.studentsct.model.StudentGroup;
    040import org.cpsolver.studentsct.model.Subpart;
    041import org.cpsolver.studentsct.model.Unavailability;
    042import org.cpsolver.studentsct.reservation.CourseReservation;
    043import org.cpsolver.studentsct.reservation.CourseRestriction;
    044import org.cpsolver.studentsct.reservation.CurriculumOverride;
    045import org.cpsolver.studentsct.reservation.CurriculumReservation;
    046import org.cpsolver.studentsct.reservation.CurriculumRestriction;
    047import org.cpsolver.studentsct.reservation.DummyReservation;
    048import org.cpsolver.studentsct.reservation.GroupReservation;
    049import org.cpsolver.studentsct.reservation.IndividualReservation;
    050import org.cpsolver.studentsct.reservation.IndividualRestriction;
    051import org.cpsolver.studentsct.reservation.LearningCommunityReservation;
    052import org.cpsolver.studentsct.reservation.Reservation;
    053import org.cpsolver.studentsct.reservation.ReservationOverride;
    054import org.cpsolver.studentsct.reservation.Restriction;
    055import org.cpsolver.studentsct.reservation.UniversalOverride;
    056import org.dom4j.Document;
    057import org.dom4j.DocumentHelper;
    058import org.dom4j.Element;
    059import org.dom4j.io.OutputFormat;
    060import org.dom4j.io.XMLWriter;
    061
    062
    063/**
    064 * Save student sectioning solution into an XML file.
    065 *
    066 * <br>
    067 * <br>
    068 * Parameters:
    069 * <table border='1'><caption>Related Solver Parameters</caption>
    070 * <tr>
    071 * <th>Parameter</th>
    072 * <th>Type</th>
    073 * <th>Comment</th>
    074 * </tr>
    075 * <tr>
    076 * <td>General.Output</td>
    077 * <td>{@link String}</td>
    078 * <td>Folder with the output solution in XML format (solution.xml)</td>
    079 * </tr>
    080 * <tr>
    081 * <td>Xml.ConvertIds</td>
    082 * <td>{@link Boolean}</td>
    083 * <td>If true, ids are converted (to be able to make input data public)</td>
    084 * </tr>
    085 * <tr>
    086 * <td>Xml.ShowNames</td>
    087 * <td>{@link Boolean}</td>
    088 * <td>If false, names are not exported (to be able to make input data public)</td>
    089 * </tr>
    090 * <tr>
    091 * <td>Xml.SaveBest</td>
    092 * <td>{@link Boolean}</td>
    093 * <td>If true, best solution is saved.</td>
    094 * </tr>
    095 * <tr>
    096 * <td>Xml.SaveInitial</td>
    097 * <td>{@link Boolean}</td>
    098 * <td>If true, initial solution is saved.</td>
    099 * </tr>
    100 * <tr>
    101 * <td>Xml.SaveCurrent</td>
    102 * <td>{@link Boolean}</td>
    103 * <td>If true, current solution is saved.</td>
    104 * </tr>
    105 * <tr>
    106 * <td>Xml.SaveOnlineSectioningInfo</td>
    107 * <td>{@link Boolean}</td>
    108 * <td>If true, save online sectioning info (i.e., expected and held space of
    109 * each section)</td>
    110 * </tr>
    111 * <tr>
    112 * <td>Xml.SaveStudentInfo</td>
    113 * <td>{@link Boolean}</td>
    114 * <td>If true, save student information (i.e., academic area classification,
    115 * major, minor)</td>
    116 * </tr>
    117 * </table>
    118 * <br>
    119 * <br>
    120 * Usage:
    121 * <pre><code>
    122 * new StudentSectioningXMLSaver(solver).save(new File("solution.xml"));
    123 * </code></pre>
    124 *
    125 * @author  Tomáš Müller
    126 * @version StudentSct 1.3 (Student Sectioning)<br>
    127 *          Copyright (C) 2007 - 2014 Tomáš Müller<br>
    128 *          <a href="mailto:muller@unitime.org">muller@unitime.org</a><br>
    129 *          <a href="http://muller.unitime.org">http://muller.unitime.org</a><br>
    130 * <br>
    131 *          This library is free software; you can redistribute it and/or modify
    132 *          it under the terms of the GNU Lesser General Public License as
    133 *          published by the Free Software Foundation; either version 3 of the
    134 *          License, or (at your option) any later version. <br>
    135 * <br>
    136 *          This library is distributed in the hope that it will be useful, but
    137 *          WITHOUT ANY WARRANTY; without even the implied warranty of
    138 *          MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
    139 *          Lesser General Public License for more details. <br>
    140 * <br>
    141 *          You should have received a copy of the GNU Lesser General Public
    142 *          License along with this library; if not see
    143 *          <a href='http://www.gnu.org/licenses/'>http://www.gnu.org/licenses/</a>.
    144 */
    145
    146public class StudentSectioningXMLSaver extends StudentSectioningSaver {
    147    private static org.apache.logging.log4j.Logger sLogger = org.apache.logging.log4j.LogManager.getLogger(StudentSectioningXMLSaver.class);
    148    private static DecimalFormat[] sDF = { new DecimalFormat(""), new DecimalFormat("0"), new DecimalFormat("00"),
    149            new DecimalFormat("000"), new DecimalFormat("0000"), new DecimalFormat("00000"),
    150            new DecimalFormat("000000"), new DecimalFormat("0000000") };
    151    private static DecimalFormat sStudentWeightFormat = new DecimalFormat("0.0000", new DecimalFormatSymbols(Locale.US));
    152    private File iOutputFolder = null;
    153
    154    private boolean iSaveBest = false;
    155    private boolean iSaveInitial = false;
    156    private boolean iSaveCurrent = false;
    157    private boolean iSaveOnlineSectioningInfo = false;
    158    private boolean iSaveStudentInfo = true;
    159
    160    private boolean iConvertIds = false;
    161    private boolean iShowNames = false;
    162
    163    static {
    164        sStudentWeightFormat.setRoundingMode(RoundingMode.DOWN);
    165    }
    166
    167    /**
    168     * Constructor
    169     *
    170     * @param solver
    171     *            student sectioning solver
    172     */
    173    public StudentSectioningXMLSaver(Solver<Request, Enrollment> solver) {
    174        super(solver);
    175        iOutputFolder = new File(getModel().getProperties().getProperty("General.Output",
    176                "." + File.separator + "output"));
    177        iSaveBest = getModel().getProperties().getPropertyBoolean("Xml.SaveBest", true);
    178        iSaveInitial = getModel().getProperties().getPropertyBoolean("Xml.SaveInitial", true);
    179        iSaveCurrent = getModel().getProperties().getPropertyBoolean("Xml.SaveCurrent", false);
    180        iSaveOnlineSectioningInfo = getModel().getProperties().getPropertyBoolean("Xml.SaveOnlineSectioningInfo", true);
    181        iSaveStudentInfo = getModel().getProperties().getPropertyBoolean("Xml.SaveStudentInfo", true);
    182        iShowNames = getModel().getProperties().getPropertyBoolean("Xml.ShowNames", true);
    183        iConvertIds = getModel().getProperties().getPropertyBoolean("Xml.ConvertIds", false);
    184    }
    185
    186    /** Convert bitset to a bit string */
    187    private static String bitset2string(BitSet b) {
    188        StringBuffer sb = new StringBuffer();
    189        for (int i = 0; i < b.length(); i++)
    190            sb.append(b.get(i) ? "1" : "0");
    191        return sb.toString();
    192    }
    193
    194    /** Generate id for given object with the given id */
    195    private String getId(String type, String id) {
    196        if (!iConvertIds)
    197            return id.toString();
    198        return IdConvertor.getInstance().convert(type, id);
    199    }
    200
    201    /** Generate id for given object with the given id */
    202    private String getId(String type, Number id) {
    203        return getId(type, id.toString());
    204    }
    205
    206    /** Generate id for given object with the given id */
    207    private String getId(String type, long id) {
    208        return getId(type, String.valueOf(id));
    209    }
    210
    211    /** Save an XML file */
    212    @Override
    213    public void save() throws Exception {
    214        save(null);
    215    }
    216
    217    /**
    218     * Save an XML file
    219     *
    220     * @param outFile
    221     *            output file
    222     * @throws Exception thrown when the save fails
    223     */
    224    public void save(File outFile) throws Exception {
    225        if (outFile == null) {
    226            outFile = new File(iOutputFolder, "solution.xml");
    227        } else if (outFile.getParentFile() != null) {
    228            outFile.getParentFile().mkdirs();
    229        }
    230        sLogger.debug("Writting XML data to:" + outFile);
    231
    232        Document document = DocumentHelper.createDocument();
    233        document.addComment("Student Sectioning");
    234
    235        populate(document);
    236
    237        FileOutputStream fos = null;
    238        try {
    239            fos = new FileOutputStream(outFile);
    240            (new XMLWriter(fos, OutputFormat.createPrettyPrint())).write(document);
    241            fos.flush();
    242            fos.close();
    243            fos = null;
    244        } finally {
    245            try {
    246                if (fos != null)
    247                    fos.close();
    248            } catch (IOException e) {
    249            }
    250        }
    251
    252        if (iConvertIds)
    253            IdConvertor.getInstance().save();
    254    }
    255
    256    public Document saveDocument() {
    257        Document document = DocumentHelper.createDocument();
    258        document.addComment("Student Sectioning");
    259
    260        populate(document);
    261
    262        return document;
    263    }
    264
    265    /**
    266     * Fill in all the data into the given document
    267     * @param document document to be populated
    268     */
    269    protected void populate(Document document) {
    270        if (iSaveCurrent || iSaveBest) {
    271            StringBuffer comments = new StringBuffer("Solution Info:\n");
    272            Map<String, String> solutionInfo = (getSolution() == null ? getModel().getExtendedInfo(getAssignment()) : getSolution().getExtendedInfo());
    273            for (String key : new TreeSet<String>(solutionInfo.keySet())) {
    274                String value = solutionInfo.get(key);
    275                comments.append("    " + key + ": " + value + "\n");
    276            }
    277            document.addComment(comments.toString());
    278        }
    279
    280        Element root = document.addElement("sectioning");
    281        root.addAttribute("version", "1.0");
    282        root.addAttribute("initiative", getModel().getProperties().getProperty("Data.Initiative"));
    283        root.addAttribute("term", getModel().getProperties().getProperty("Data.Term"));
    284        root.addAttribute("year", getModel().getProperties().getProperty("Data.Year"));
    285        root.addAttribute("created", String.valueOf(new Date()));
    286
    287        saveOfferings(root);
    288
    289        saveStudents(root);
    290
    291        saveLinkedSections(root);
    292
    293        saveTravelTimes(root);
    294
    295        if (iShowNames) {
    296            Progress.getInstance(getModel()).save(root);
    297        }
    298    }
    299
    300    /**
    301     * Save offerings
    302     * @param root document root
    303     */
    304    protected void saveOfferings(Element root) {
    305        Element offeringsEl = root.addElement("offerings");
    306        for (Offering offering : getModel().getOfferings()) {
    307            Element offeringEl = offeringsEl.addElement("offering");
    308            saveOffering(offeringEl, offering);
    309            saveReservations(offeringEl, offering);
    310            saveRestrictions(offeringEl, offering);
    311        }
    312    }
    313
    314    /**
    315     * Save given offering
    316     * @param offeringEl offering element to be populated
    317     * @param offering offering to be saved
    318     */
    319    protected void saveOffering(Element offeringEl, Offering offering) {
    320        offeringEl.addAttribute("id", getId("offering", offering.getId()));
    321        if (iShowNames)
    322            offeringEl.addAttribute("name", offering.getName());
    323        if (offering.isDummy())
    324            offeringEl.addAttribute("dummy", "true");
    325        for (Course course : offering.getCourses()) {
    326            Element courseEl = offeringEl.addElement("course");
    327            saveCourse(courseEl, course);
    328        }
    329        for (Config config : offering.getConfigs()) {
    330            Element configEl = offeringEl.addElement("config");
    331            saveConfig(configEl, config);
    332        }
    333    }
    334
    335    /**
    336     * Save given course
    337     * @param courseEl course element to be populated
    338     * @param course course to be saved
    339     */
    340    protected void saveCourse(Element courseEl, Course course) {
    341        courseEl.addAttribute("id", getId("course", course.getId()));
    342        if (iShowNames)
    343            courseEl.addAttribute("subjectArea", course.getSubjectArea());
    344        if (iShowNames)
    345            courseEl.addAttribute("courseNbr", course.getCourseNumber());
    346        if (iShowNames && course.getLimit() >= 0)
    347            courseEl.addAttribute("limit", String.valueOf(course.getLimit()));
    348        if (iShowNames && course.getProjected() != 0)
    349            courseEl.addAttribute("projected", String.valueOf(course.getProjected()));
    350        if (iShowNames && course.getCredit() != null)
    351            courseEl.addAttribute("credit", course.getCredit());
    352        if (course.hasCreditValue())
    353            courseEl.addAttribute("credits", course.getCreditValue().toString());
    354        if (iShowNames && course.getType() != null)
    355            courseEl.addAttribute("type", course.getType());
    356        if (iShowNames && course.getTitle() != null)
    357            courseEl.addAttribute("title", course.getTitle());
    358        if (iShowNames && course.getNote() != null)
    359            courseEl.addAttribute("note", course.getNote());
    360
    361    }
    362
    363    /**
    364     * Save given config
    365     * @param configEl config element to be populated
    366     * @param config config to be saved
    367     */
    368    protected void saveConfig(Element configEl, Config config) {
    369        configEl.addAttribute("id", getId("config", config.getId()));
    370        if (config.getLimit() >= 0)
    371            configEl.addAttribute("limit", String.valueOf(config.getLimit()));
    372        if (iShowNames)
    373            configEl.addAttribute("name", config.getName());
    374        for (Subpart subpart : config.getSubparts()) {
    375            Element subpartEl = configEl.addElement("subpart");
    376            saveSubpart(subpartEl, subpart);
    377        }
    378        if (config.getInstructionalMethodId() != null) {
    379            Element imEl = configEl.addElement("instructional-method");
    380            imEl.addAttribute("id", getId("instructional-method", config.getInstructionalMethodId()));
    381            if (iShowNames && config.getInstructionalMethodName() != null)
    382                imEl.addAttribute("name", config.getInstructionalMethodName());
    383            if (iShowNames && config.getInstructionalMethodReference() != null)
    384                imEl.addAttribute("reference", config.getInstructionalMethodReference());
    385        }
    386    }
    387
    388    /**
    389     * Save scheduling subpart
    390     * @param subpartEl subpart element to be populated
    391     * @param subpart subpart to be saved
    392     */
    393    protected void saveSubpart(Element subpartEl, Subpart subpart) {
    394        subpartEl.addAttribute("id", getId("subpart", subpart.getId()));
    395        subpartEl.addAttribute("itype", subpart.getInstructionalType());
    396        if (subpart.getParent() != null)
    397            subpartEl.addAttribute("parent", getId("subpart", subpart.getParent().getId()));
    398        if (iShowNames) {
    399            subpartEl.addAttribute("name", subpart.getName());
    400            if (subpart.getCredit() != null)
    401                subpartEl.addAttribute("credit", subpart.getCredit());
    402            if (subpart.hasCreditValue())
    403                subpartEl.addAttribute("credits", subpart.getCreditValue().toString());
    404        }
    405        if (subpart.isAllowOverlap())
    406            subpartEl.addAttribute("allowOverlap", "true");
    407        for (Section section : subpart.getSections()) {
    408            Element sectionEl = subpartEl.addElement("section");
    409            saveSection(sectionEl, section);
    410        }
    411    }
    412
    413    /**
    414     * Save section
    415     * @param sectionEl section element to be populated
    416     * @param section section to be saved
    417     */
    418    protected void saveSection(Element sectionEl, Section section) {
    419        sectionEl.addAttribute("id", getId("section", section.getId()));
    420        sectionEl.addAttribute("limit", String.valueOf(section.getLimit()));
    421        if (section.isCancelled())
    422            sectionEl.addAttribute("cancelled", "true");
    423        if (!section.isEnabled())
    424            sectionEl.addAttribute("enabled", "false");
    425        if (section.isOnline())
    426            sectionEl.addAttribute("online", "true");
    427        if (section.isPast())
    428            sectionEl.addAttribute("past", "true");
    429        if (iShowNames && section.getNameByCourse() != null)
    430            for (Map.Entry<Long, String> entry: section.getNameByCourse().entrySet())
    431                sectionEl.addElement("cname").addAttribute("id", getId("course", entry.getKey())).setText(entry.getValue());
    432        if (section.getParent() != null)
    433            sectionEl.addAttribute("parent", getId("section", section.getParent().getId()));
    434        if (section.hasInstructors()) {
    435            for (Instructor instructor: section.getInstructors()) {
    436                Element instructorEl = sectionEl.addElement("instructor");
    437                instructorEl.addAttribute("id", getId("instructor", instructor.getId()));
    438                if (iShowNames && instructor.getName() != null)
    439                    instructorEl.addAttribute("name", instructor.getName());
    440                if (iShowNames && instructor.getExternalId() != null)
    441                    instructorEl.addAttribute("externalId", instructor.getExternalId());
    442                if (iShowNames && instructor.getEmail() != null)
    443                    instructorEl.addAttribute("email", instructor.getExternalId());
    444            }
    445        }
    446        if (iShowNames)
    447            sectionEl.addAttribute("name", section.getName());
    448        if (section.getPlacement() != null) {
    449            TimeLocation tl = section.getPlacement().getTimeLocation();
    450            if (tl != null) {
    451                Element timeLocationEl = sectionEl.addElement("time");
    452                timeLocationEl.addAttribute("days", sDF[7].format(Long.parseLong(Integer
    453                        .toBinaryString(tl.getDayCode()))));
    454                timeLocationEl.addAttribute("start", String.valueOf(tl.getStartSlot()));
    455                timeLocationEl.addAttribute("length", String.valueOf(tl.getLength()));
    456                if (tl.getBreakTime() != 0)
    457                    timeLocationEl.addAttribute("breakTime", String.valueOf(tl.getBreakTime()));
    458                if (iShowNames && tl.getTimePatternId() != null)
    459                    timeLocationEl.addAttribute("pattern", getId("timePattern", tl.getTimePatternId()));
    460                if (iShowNames && tl.getDatePatternId() != null)
    461                    timeLocationEl.addAttribute("datePattern", tl.getDatePatternId().toString());
    462                if (iShowNames && tl.getDatePatternName() != null
    463                        && tl.getDatePatternName().length() > 0)
    464                    timeLocationEl.addAttribute("datePatternName", tl.getDatePatternName());
    465                timeLocationEl.addAttribute("dates", bitset2string(tl.getWeekCode()));
    466                if (iShowNames)
    467                    timeLocationEl.setText(tl.getLongName(true));
    468            }
    469            for (RoomLocation rl : section.getRooms()) {
    470                Element roomLocationEl = sectionEl.addElement("room");
    471                roomLocationEl.addAttribute("id", getId("room", rl.getId()));
    472                if (iShowNames && rl.getBuildingId() != null)
    473                    roomLocationEl.addAttribute("building", getId("building", rl.getBuildingId()));
    474                if (iShowNames && rl.getName() != null)
    475                    roomLocationEl.addAttribute("name", rl.getName());
    476                roomLocationEl.addAttribute("capacity", String.valueOf(rl.getRoomSize()));
    477                if (rl.getPosX() != null && rl.getPosY() != null)
    478                    roomLocationEl.addAttribute("location", rl.getPosX() + "," + rl.getPosY());
    479                if (rl.getIgnoreTooFar())
    480                    roomLocationEl.addAttribute("ignoreTooFar", "true");
    481            }
    482        }
    483        if (iSaveOnlineSectioningInfo) {
    484            if (section.getSpaceHeld() != 0.0)
    485                sectionEl.addAttribute("hold", sStudentWeightFormat.format(section.getSpaceHeld()));
    486            if (section.getSpaceExpected() != 0.0)
    487                sectionEl.addAttribute("expect", sStudentWeightFormat
    488                        .format(section.getSpaceExpected()));
    489        }
    490        if (section.getIgnoreConflictWithSectionIds() != null && !section.getIgnoreConflictWithSectionIds().isEmpty()) {
    491            Element ignoreEl = sectionEl.addElement("no-conflicts");
    492            for (Long sectionId: section.getIgnoreConflictWithSectionIds())
    493                ignoreEl.addElement("section").addAttribute("id", getId("section", sectionId));
    494        }
    495    }
    496
    497    /**
    498     * Save reservations of the given offering
    499     * @param offeringEl offering element to be populated with reservations
    500     * @param offering offering which reservations are to be saved
    501     */
    502    protected void saveReservations(Element offeringEl, Offering offering) {
    503        if (!offering.getReservations().isEmpty()) {
    504            for (Reservation r: offering.getReservations()) {
    505                saveReservation(offeringEl.addElement("reservation"), r);
    506            }
    507        }
    508    }
    509
    510    /**
    511     * Save reservation
    512     * @param reservationEl reservation element to be populated
    513     * @param reservation reservation to be saved
    514     */
    515    protected void saveReservation(Element reservationEl, Reservation reservation) {
    516        reservationEl.addAttribute("id", getId("reservation", reservation.getId()));
    517        reservationEl.addAttribute("expired", reservation.isExpired() ? "true" : "false");
    518        if (reservation instanceof LearningCommunityReservation) {
    519            LearningCommunityReservation lc = (LearningCommunityReservation)reservation;
    520            reservationEl.addAttribute("type", "lc");
    521            for (Long studentId: lc.getStudentIds())
    522                reservationEl.addElement("student").addAttribute("id", getId("student", studentId));
    523            if (lc.getReservationLimit() >= 0.0)
    524                reservationEl.addAttribute("limit", String.valueOf(lc.getReservationLimit()));
    525            reservationEl.addAttribute("course", getId("course",lc.getCourse().getId()));
    526        } else if (reservation instanceof GroupReservation) {
    527            GroupReservation gr = (GroupReservation)reservation;
    528            reservationEl.addAttribute("type", "group");
    529            for (Long studentId: gr.getStudentIds())
    530                reservationEl.addElement("student").addAttribute("id", getId("student", studentId));
    531            if (gr.getReservationLimit() >= 0.0)
    532                reservationEl.addAttribute("limit", String.valueOf(gr.getReservationLimit()));
    533        } else if (reservation instanceof ReservationOverride) {
    534            reservationEl.addAttribute("type", "override");
    535            ReservationOverride o = (ReservationOverride)reservation;
    536            for (Long studentId: o.getStudentIds())
    537                reservationEl.addElement("student").addAttribute("id", getId("student", studentId));
    538        } else if (reservation instanceof IndividualReservation) {
    539            reservationEl.addAttribute("type", "individual");
    540            for (Long studentId: ((IndividualReservation)reservation).getStudentIds())
    541                reservationEl.addElement("student").addAttribute("id", getId("student", studentId));
    542        } else if (reservation instanceof CurriculumReservation) {
    543            reservationEl.addAttribute("type", (reservation instanceof CurriculumOverride ? "curriculum-override" : "curriculum"));
    544            CurriculumReservation cr = (CurriculumReservation)reservation;
    545            if (cr.getReservationLimit() >= 0.0)
    546                reservationEl.addAttribute("limit", String.valueOf(cr.getReservationLimit()));
    547            if (cr.getAcademicAreas().size() == 1)
    548                reservationEl.addAttribute("area", cr.getAcademicAreas().iterator().next());
    549            else {
    550                for (String area: cr.getAcademicAreas())
    551                    reservationEl.addElement("area").addAttribute("code", area);
    552            }
    553            for (String clasf: cr.getClassifications())
    554                reservationEl.addElement("classification").addAttribute("code", clasf);
    555            for (String major: cr.getMajors()) {
    556                Element majorEl = reservationEl.addElement("major").addAttribute("code", major);
    557                Set<String> concentrations = cr.getConcentrations(major);
    558                if (concentrations != null)
    559                    for (String conc: concentrations)
    560                        majorEl.addElement("concentration").addAttribute("code", conc);
    561            }
    562            for (String minor: cr.getMinors())
    563                reservationEl.addElement("minor").addAttribute("code", minor);
    564        } else if (reservation instanceof CourseReservation) {
    565            reservationEl.addAttribute("type", "course");
    566            CourseReservation cr = (CourseReservation)reservation;
    567            reservationEl.addAttribute("course", getId("course",cr.getCourse().getId()));
    568        } else if (reservation instanceof DummyReservation) {
    569            reservationEl.addAttribute("type", "dummy");
    570        } else if (reservation instanceof UniversalOverride) {
    571            reservationEl.addAttribute("type", "universal");
    572            UniversalOverride ur = (UniversalOverride)reservation;
    573            if (ur.getFilter() != null)
    574                reservationEl.addAttribute("filter", ur.getFilter());
    575            reservationEl.addAttribute("override", ur.isOverride() ? "true" : "false");
    576            if (ur.getReservationLimit() >= 0.0)
    577                reservationEl.addAttribute("limit", String.valueOf(ur.getReservationLimit()));
    578        }
    579        reservationEl.addAttribute("priority", String.valueOf(reservation.getPriority()));
    580        reservationEl.addAttribute("mustBeUsed", reservation.mustBeUsed() ? "true" : "false");
    581        reservationEl.addAttribute("allowOverlap", reservation.isAllowOverlap() ? "true" : "false");
    582        reservationEl.addAttribute("canAssignOverLimit", reservation.canAssignOverLimit() ? "true" : "false");
    583        reservationEl.addAttribute("allowDisabled", reservation.isAllowDisabled() ? "true" : "false");
    584        if (reservation.neverIncluded()) reservationEl.addAttribute("neverIncluded", "true");
    585        if (reservation.canBreakLinkedSections()) reservationEl.addAttribute("breakLinkedSections", "true");
    586        for (Config config: reservation.getConfigs())
    587            reservationEl.addElement("config").addAttribute("id", getId("config", config.getId()));
    588        for (Map.Entry<Subpart, Set<Section>> entry: reservation.getSections().entrySet()) {
    589            for (Section section: entry.getValue()) {
    590                reservationEl.addElement("section").addAttribute("id", getId("section", section.getId()));
    591            }
    592        }
    593    }
    594
    595    /**
    596     * Save restrictions of the given offering
    597     * @param offeringEl offering element to be populated with restrictions
    598     * @param offering offering which restrictions are to be saved
    599     */
    600    protected void saveRestrictions(Element offeringEl, Offering offering) {
    601        if (!offering.getRestrictions().isEmpty()) {
    602            for (Restriction r: offering.getRestrictions()) {
    603                saveRestriction(offeringEl.addElement("restriction"), r);
    604            }
    605        }
    606    }
    607
    608    /**
    609     * Save restriction
    610     * @param restrictionEl restriction element to be populated
    611     * @param restriction restriction to be saved
    612     */
    613    protected void saveRestriction(Element restrictionEl, Restriction restriction) {
    614        restrictionEl.addAttribute("id", getId("restriction", restriction.getId()));
    615        if (restriction instanceof IndividualRestriction) {
    616            restrictionEl.addAttribute("type", "individual");
    617            for (Long studentId: ((IndividualRestriction)restriction).getStudentIds())
    618                restrictionEl.addElement("student").addAttribute("id", getId("student", studentId));
    619        } else if (restriction instanceof CurriculumRestriction) {
    620            restrictionEl.addAttribute("type", "curriculum");
    621            CurriculumRestriction cr = (CurriculumRestriction)restriction;
    622            if (cr.getAcademicAreas().size() == 1)
    623                restrictionEl.addAttribute("area", cr.getAcademicAreas().iterator().next());
    624            else {
    625                for (String area: cr.getAcademicAreas())
    626                    restrictionEl.addElement("area").addAttribute("code", area);
    627            }
    628            for (String clasf: cr.getClassifications())
    629                restrictionEl.addElement("classification").addAttribute("code", clasf);
    630            for (String major: cr.getMajors()) {
    631                Element majorEl = restrictionEl.addElement("major").addAttribute("code", major);
    632                Set<String> concentrations = cr.getConcentrations(major);
    633                if (concentrations != null)
    634                    for (String conc: concentrations)
    635                        majorEl.addElement("concentration").addAttribute("code", conc);
    636            }
    637            for (String minor: cr.getMinors())
    638                restrictionEl.addElement("minor").addAttribute("code", minor);
    639        } else if (restriction instanceof CourseRestriction) {
    640            restrictionEl.addAttribute("type", "course");
    641            CourseRestriction cr = (CourseRestriction)restriction;
    642            restrictionEl.addAttribute("course", getId("course",cr.getCourse().getId()));
    643        }
    644        for (Config config: restriction.getConfigs())
    645            restrictionEl.addElement("config").addAttribute("id", getId("config", config.getId()));
    646        for (Map.Entry<Subpart, Set<Section>> entry: restriction.getSections().entrySet()) {
    647            for (Section section: entry.getValue()) {
    648                restrictionEl.addElement("section").addAttribute("id", getId("section", section.getId()));
    649            }
    650        }
    651    }
    652
    653    /**
    654     * Save students
    655     * @param root document root
    656     */
    657    protected void saveStudents(Element root) {
    658        Element studentsEl = root.addElement("students");
    659        for (Student student : getModel().getStudents()) {
    660            Element studentEl = studentsEl.addElement("student");
    661            saveStudent(studentEl, student);
    662            for (Request request : student.getRequests()) {
    663                saveRequest(studentEl, request);
    664            }
    665        }
    666    }
    667
    668    /**
    669     * Save student
    670     * @param studentEl student element to be populated
    671     * @param student student to be saved
    672     */
    673    protected void saveStudent(Element studentEl, Student student) {
    674        studentEl.addAttribute("id", getId("student", student.getId()));
    675        if (iShowNames) {
    676            if (student.getExternalId() != null && !student.getExternalId().isEmpty())
    677                studentEl.addAttribute("externalId", student.getExternalId());
    678            if (student.getName() != null && !student.getName().isEmpty())
    679                studentEl.addAttribute("name", student.getName());
    680            if (student.getStatus() != null && !student.getStatus().isEmpty())
    681                studentEl.addAttribute("status", student.getStatus());
    682        }
    683        if (student.isDummy())
    684            studentEl.addAttribute("dummy", "true");
    685        if (student.getPriority().ordinal() < StudentPriority.Normal.ordinal())
    686            studentEl.addAttribute("priority", student.getPriority().name());
    687        if (student.isNeedShortDistances())
    688            studentEl.addAttribute("shortDistances", "true");
    689        if (student.isAllowDisabled())
    690            studentEl.addAttribute("allowDisabled", "true");
    691        if (student.hasMinCredit())
    692            studentEl.addAttribute("minCredit", String.valueOf(student.getMinCredit()));
    693        if (student.hasMaxCredit())
    694            studentEl.addAttribute("maxCredit", String.valueOf(student.getMaxCredit()));
    695        if (student.getClassFirstDate() != null)
    696            studentEl.addAttribute("classFirstDate", String.valueOf(student.getClassFirstDate()));
    697        if (student.getClassLastDate() != null)
    698            studentEl.addAttribute("classLastDate", String.valueOf(student.getClassLastDate()));
    699        if (student.getModalityPreference() != null && student.getModalityPreference() != ModalityPreference.NO_PREFERENCE)
    700            studentEl.addAttribute("modality", student.getModalityPreference().name());
    701        if (student.getBackToBackPreference() != null && student.getBackToBackPreference() != BackToBackPreference.NO_PREFERENCE)
    702            studentEl.addAttribute("btb", student.getBackToBackPreference().name());
    703        if (iSaveStudentInfo) {
    704            for (AreaClassificationMajor acm : student.getAreaClassificationMajors()) {
    705                Element acmEl = studentEl.addElement("acm");
    706                if (acm.getArea() != null)
    707                    acmEl.addAttribute("area", acm.getArea());
    708                if (acm.getClassification() != null)
    709                    acmEl.addAttribute("classification", acm.getClassification());
    710                if (acm.getMajor() != null)
    711                    acmEl.addAttribute("major", acm.getMajor());
    712                if (acm.getConcentration() != null)
    713                    acmEl.addAttribute("concentration", acm.getConcentration());
    714                if (acm.getDegree() != null)
    715                    acmEl.addAttribute("degree", acm.getDegree());
    716                if (acm.getProgram() != null)
    717                    acmEl.addAttribute("program", acm.getProgram());
    718                if (acm.getAreaName() != null && iShowNames)
    719                    acmEl.addAttribute("areaName", acm.getAreaName());
    720                if (acm.getClassificationName() != null && iShowNames)
    721                    acmEl.addAttribute("classificationName", acm.getClassificationName());
    722                if (acm.getMajorName() != null && iShowNames)
    723                    acmEl.addAttribute("majorName", acm.getMajorName());
    724                if (acm.getConcentrationName() != null && iShowNames)
    725                    acmEl.addAttribute("concentrationName", acm.getConcentrationName());
    726                if (acm.getDegreeName() != null && iShowNames)
    727                    acmEl.addAttribute("degreeName", acm.getDegreeName());
    728                if (acm.getProgramName() != null && iShowNames)
    729                    acmEl.addAttribute("programName", acm.getProgramName());
    730                if (acm.getWeight() != 1.0)
    731                    acmEl.addAttribute("weight", String.valueOf(acm.getWeight()));
    732                if (acm.getCampus() != null)
    733                    acmEl.addAttribute("campus", acm.getCampus());
    734                if (acm.getCampusName() != null && iShowNames)
    735                    acmEl.addAttribute("campusName", acm.getCampusName());
    736            }
    737            for (AreaClassificationMajor acm : student.getAreaClassificationMinors()) {
    738                Element acmEl = studentEl.addElement("acm");
    739                if (acm.getArea() != null)
    740                    acmEl.addAttribute("area", acm.getArea());
    741                if (acm.getClassification() != null)
    742                    acmEl.addAttribute("classification", acm.getClassification());
    743                if (acm.getMajor() != null)
    744                    acmEl.addAttribute("minor", acm.getMajor());
    745                if (acm.getConcentration() != null)
    746                    acmEl.addAttribute("concentration", acm.getConcentration());
    747                if (acm.getDegree() != null)
    748                    acmEl.addAttribute("degree", acm.getDegree());
    749                if (acm.getProgram() != null)
    750                    acmEl.addAttribute("program", acm.getProgram());
    751                if (acm.getAreaName() != null && iShowNames)
    752                    acmEl.addAttribute("areaName", acm.getAreaName());
    753                if (acm.getClassificationName() != null && iShowNames)
    754                    acmEl.addAttribute("classificationName", acm.getClassificationName());
    755                if (acm.getMajorName() != null && iShowNames)
    756                    acmEl.addAttribute("minorName", acm.getMajorName());
    757                if (acm.getConcentrationName() != null && iShowNames)
    758                    acmEl.addAttribute("concentrationName", acm.getConcentrationName());
    759                if (acm.getDegreeName() != null && iShowNames)
    760                    acmEl.addAttribute("degreeName", acm.getDegreeName());
    761                if (acm.getProgramName() != null && iShowNames)
    762                    acmEl.addAttribute("programName", acm.getProgramName());
    763                if (acm.getWeight() != 1.0)
    764                    acmEl.addAttribute("weight", String.valueOf(acm.getWeight()));
    765                if (acm.getCampus() != null)
    766                    acmEl.addAttribute("campus", acm.getCampus());
    767                if (acm.getCampusName() != null && iShowNames)
    768                    acmEl.addAttribute("campusName", acm.getCampusName());
    769            }
    770            for (StudentGroup g : student.getGroups()) {
    771                Element grEl = studentEl.addElement("group");
    772                if (g.getType() != null && !g.getType().isEmpty())
    773                    grEl.addAttribute("type", g.getType());
    774                if (g.getReference() != null)
    775                    grEl.addAttribute("reference", g.getReference());
    776                if (g.getName() != null)
    777                    grEl.addAttribute("name", g.getName());
    778            }
    779            for (String acc: student.getAccommodations())
    780                studentEl.addElement("accommodation").addAttribute("reference", acc);
    781        }
    782        if (iShowNames && iSaveStudentInfo) {
    783            for (Instructor adv: student.getAdvisors()) {
    784                Element advEl = studentEl.addElement("advisor");
    785                if (adv.getExternalId() != null)
    786                    advEl.addAttribute("externalId", adv.getExternalId());
    787                if (adv.getName() != null)
    788                    advEl.addAttribute("name", adv.getName());
    789                if (adv.getEmail() != null)
    790                    advEl.addAttribute("email", adv.getEmail());
    791            }
    792        }
    793        for (Unavailability unavailability: student.getUnavailabilities()) {
    794            Element unavEl = studentEl.addElement("unavailability");
    795            unavEl.addAttribute("offering", getId("offering", unavailability.getSection().getSubpart().getConfig().getOffering().getId()));
    796            unavEl.addAttribute("section", getId("section", unavailability.getSection().getId()));
    797            unavEl.addAttribute("ta", unavailability.isTeachingAssignment() ? "true" : "false");
    798            if (unavailability.getCourseId() != null)
    799                unavEl.addAttribute("course", getId("course", unavailability.getCourseId()));
    800            if (unavailability.isAllowOverlap()) unavEl.addAttribute("allowOverlap", "true");
    801        }
    802    }
    803
    804    /**
    805     * Save request
    806     * @param studentEl student element to be populated
    807     * @param request request to be saved
    808     */
    809    protected void saveRequest(Element studentEl, Request request) {
    810        if (request instanceof FreeTimeRequest) {
    811            saveFreeTimeRequest(studentEl.addElement("freeTime"), (FreeTimeRequest) request);
    812        } else if (request instanceof CourseRequest) {
    813            saveCourseRequest(studentEl.addElement("course"), (CourseRequest) request);
    814        }
    815    }
    816
    817    /**
    818     * Save free time request
    819     * @param requestEl request element to be populated
    820     * @param request free time request to be saved
    821     */
    822    protected void saveFreeTimeRequest(Element requestEl, FreeTimeRequest request) {
    823        requestEl.addAttribute("id", getId("request", request.getId()));
    824        requestEl.addAttribute("priority", String.valueOf(request.getPriority()));
    825        if (request.isAlternative())
    826            requestEl.addAttribute("alternative", "true");
    827        if (request.getWeight() != 1.0)
    828            requestEl.addAttribute("weight", sStudentWeightFormat.format(request.getWeight()));
    829        TimeLocation tl = request.getTime();
    830        if (tl != null) {
    831            requestEl.addAttribute("days", sDF[7].format(Long.parseLong(Integer.toBinaryString(tl
    832                    .getDayCode()))));
    833            requestEl.addAttribute("start", String.valueOf(tl.getStartSlot()));
    834            requestEl.addAttribute("length", String.valueOf(tl.getLength()));
    835            if (iShowNames && tl.getDatePatternId() != null)
    836                requestEl.addAttribute("datePattern", tl.getDatePatternId().toString());
    837            requestEl.addAttribute("dates", bitset2string(tl.getWeekCode()));
    838            if (iShowNames)
    839                requestEl.setText(tl.getLongName(true));
    840        }
    841        if (iSaveInitial && request.getInitialAssignment() != null) {
    842            requestEl.addElement("initial");
    843        }
    844        if (iSaveCurrent && getAssignment().getValue(request) != null) {
    845            requestEl.addElement("current");
    846        }
    847        if (iSaveBest && request.getBestAssignment() != null) {
    848            requestEl.addElement("best");
    849        }
    850    }
    851
    852    /**
    853     * Save course request
    854     * @param requestEl request element to be populated
    855     * @param request course request to be saved
    856     */
    857    protected void saveCourseRequest(Element requestEl, CourseRequest request) {
    858        requestEl.addAttribute("id", getId("request", request.getId()));
    859        requestEl.addAttribute("priority", String.valueOf(request.getPriority()));
    860        if (request.isAlternative())
    861            requestEl.addAttribute("alternative", "true");
    862        if (request.getWeight() != 1.0)
    863            requestEl.addAttribute("weight", sStudentWeightFormat.format(request.getWeight()));
    864        requestEl.addAttribute("waitlist", request.isWaitlist() ? "true" : "false");
    865        if (request.getRequestPriority() != RequestPriority.Normal)
    866            requestEl.addAttribute("importance", request.getRequestPriority().name());
    867        if (request.getRequestPriority() == RequestPriority.Critical)
    868            requestEl.addAttribute("critical", "true");
    869        if (request.getTimeStamp() != null)
    870            requestEl.addAttribute("timeStamp", request.getTimeStamp().toString());
    871        boolean first = true;
    872        for (Course course : request.getCourses()) {
    873            if (first)
    874                requestEl.addAttribute("course", getId("course", course.getId()));
    875            else
    876                requestEl.addElement("alternative").addAttribute("course", getId("course", course.getId()));
    877            first = false;
    878        }
    879        for (Choice choice : request.getWaitlistedChoices()) {
    880            Element choiceEl = requestEl.addElement("waitlisted");
    881            choiceEl.addAttribute("offering", getId("offering", choice.getOffering().getId()));
    882            choiceEl.setText(choice.getId());
    883        }
    884        for (Choice choice : request.getSelectedChoices()) {
    885            Element choiceEl = requestEl.addElement("selected");
    886            choiceEl.addAttribute("offering", getId("offering", choice.getOffering().getId()));
    887            choiceEl.setText(choice.getId());
    888        }
    889        for (Choice choice : request.getRequiredChoices()) {
    890            Element choiceEl = requestEl.addElement("required");
    891            choiceEl.addAttribute("offering", getId("offering", choice.getOffering().getId()));
    892            choiceEl.setText(choice.getId());
    893        }
    894        if (iSaveInitial && request.getInitialAssignment() != null) {
    895            saveEnrollment(requestEl.addElement("initial"), request.getInitialAssignment());
    896        }
    897        if (iSaveCurrent && getAssignment().getValue(request) != null) {
    898            saveEnrollment(requestEl.addElement("current"), getAssignment().getValue(request));
    899        }
    900        if (iSaveBest && request.getBestAssignment() != null) {
    901            saveEnrollment(requestEl.addElement("best"), request.getBestAssignment());
    902        }
    903        if (request.isFixed())
    904            saveEnrollment(requestEl.addElement("fixed"), request.getFixedValue());
    905        for (RequestGroup g: request.getRequestGroups()) {
    906            Element groupEl = requestEl.addElement("group").addAttribute("id", getId("group", g.getId())).addAttribute("course", getId("course", g.getCourse().getId()));
    907            if (iShowNames)
    908                groupEl.addAttribute("name", g.getName());
    909        }
    910    }
    911
    912    /**
    913     * Save enrollment
    914     * @param assignmentEl assignment element to be populated
    915     * @param enrollment enrollment to be saved
    916     */
    917    protected void saveEnrollment(Element assignmentEl, Enrollment enrollment) {
    918        if (enrollment.getReservation() != null)
    919            assignmentEl.addAttribute("reservation", getId("reservation", enrollment.getReservation().getId()));
    920        if (enrollment.getCourse() != null)
    921            assignmentEl.addAttribute("course", getId("course", enrollment.getCourse().getId()));
    922        for (Section section : enrollment.getSections()) {
    923            Element sectionEl = assignmentEl.addElement("section").addAttribute("id",
    924                    getId("section", section.getId()));
    925            if (iShowNames)
    926                sectionEl.setText(section.getName() + " " +
    927                        (section.getTime() == null ? " Arr Hrs" : " " + section.getTime().getLongName(true)) +
    928                        (section.getNrRooms() == 0 ? "" : " " + section.getPlacement().getRoomName(",")) +
    929                        (section.hasInstructors() ? " " + section.getInstructorNames(",") : ""));
    930        }
    931    }
    932
    933    /**
    934     * Save linked sections
    935     * @param root document root
    936     */
    937    protected void saveLinkedSections(Element root) {
    938        Element constrainstEl = root.addElement("constraints");
    939        for (LinkedSections linkedSections: getModel().getLinkedSections()) {
    940            Element linkEl = constrainstEl.addElement("linked-sections");
    941            linkEl.addAttribute("mustBeUsed", linkedSections.isMustBeUsed() ? "true" : "false");
    942            for (Offering offering: linkedSections.getOfferings())
    943                for (Subpart subpart: linkedSections.getSubparts(offering))
    944                    for (Section section: linkedSections.getSections(subpart))
    945                        linkEl.addElement("section")
    946                            .addAttribute("offering", getId("offering", offering.getId()))
    947                            .addAttribute("id", getId("section", section.getId()));
    948        }
    949    }
    950
    951    /**
    952     * Save travel times
    953     * @param root document root
    954     */
    955    protected void saveTravelTimes(Element root) {
    956        if (getModel().getDistanceMetric() != null) {
    957            Map<Long, Map<Long, Integer>> travelTimes = getModel().getDistanceMetric().getTravelTimes();
    958            if (travelTimes != null) {
    959                Element travelTimesEl = root.addElement("travel-times");
    960                for (Map.Entry<Long, Map<Long, Integer>> e1: travelTimes.entrySet())
    961                    for (Map.Entry<Long, Integer> e2: e1.getValue().entrySet())
    962                        travelTimesEl.addElement("travel-time")
    963                            .addAttribute("id1", getId("room", e1.getKey().toString()))
    964                            .addAttribute("id2", getId("room", e2.getKey().toString()))
    965                            .addAttribute("minutes", e2.getValue().toString());
    966            }
    967        }
    968    }
    969}