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:net.sf.cpsolver.studentsct.StudentSectioningXMLSaver.java

License:Open Source License

/**
 * Save an XML file//from   w  w  w  .  j a v a2  s.  co  m
 * 
 * @param outFile
 *            output file
 */
public void save(File outFile) throws Exception {
    if (outFile == null)
        outFile = new File(iOutputFolder, "solution.xml");
    outFile.getParentFile().mkdirs();
    sLogger.debug("Writting XML data to:" + outFile);

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

    if ((iSaveCurrent || iSaveBest)) { // &&
                                       // !getModel().assignedVariables().isEmpty()
        StringBuffer comments = new StringBuffer("Solution Info:\n");
        Map<String, String> solutionInfo = (getSolution() == null ? getModel().getExtendedInfo()
                : 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()));

    Element offeringsEl = root.addElement("offerings");
    for (Offering offering : getModel().getOfferings()) {
        Element offeringEl = offeringsEl.addElement("offering");
        offeringEl.addAttribute("id", getId("offering", offering.getId()));
        if (iShowNames)
            offeringEl.addAttribute("name", offering.getName());
        for (Course course : offering.getCourses()) {
            Element courseEl = offeringEl.addElement("course");
            courseEl.addAttribute("id", getId("course", course.getId()));
            if (iShowNames)
                courseEl.addAttribute("subjectArea", course.getSubjectArea());
            if (iShowNames)
                courseEl.addAttribute("courseNbr", course.getCourseNumber());
            if (iShowNames && course.getLimit() >= 0)
                courseEl.addAttribute("limit", String.valueOf(course.getLimit()));
            if (iShowNames && course.getProjected() != 0)
                courseEl.addAttribute("projected", String.valueOf(course.getProjected()));
        }
        for (Config config : offering.getConfigs()) {
            Element configEl = offeringEl.addElement("config");
            configEl.addAttribute("id", getId("config", config.getId()));
            if (config.getLimit() >= 0)
                configEl.addAttribute("limit", String.valueOf(config.getLimit()));
            if (iShowNames)
                configEl.addAttribute("name", config.getName());
            for (Subpart subpart : config.getSubparts()) {
                Element subpartEl = configEl.addElement("subpart");
                subpartEl.addAttribute("id", getId("subpart", subpart.getId()));
                subpartEl.addAttribute("itype", subpart.getInstructionalType());
                if (subpart.getParent() != null)
                    subpartEl.addAttribute("parent", getId("subpart", subpart.getParent().getId()));
                if (iShowNames)
                    subpartEl.addAttribute("name", subpart.getName());
                if (subpart.isAllowOverlap())
                    subpartEl.addAttribute("allowOverlap", "true");
                for (Section section : subpart.getSections()) {
                    Element sectionEl = subpartEl.addElement("section");
                    sectionEl.addAttribute("id", getId("section", section.getId()));
                    sectionEl.addAttribute("limit", String.valueOf(section.getLimit()));
                    if (section.getNameByCourse() != null)
                        for (Map.Entry<Long, String> entry : section.getNameByCourse().entrySet())
                            sectionEl.addElement("cname").addAttribute("id", entry.getKey().toString())
                                    .setText(entry.getValue());
                    if (section.getParent() != null)
                        sectionEl.addAttribute("parent", getId("section", section.getParent().getId()));
                    if (iShowNames && section.getChoice().getInstructorIds() != null)
                        sectionEl.addAttribute("instructorIds", section.getChoice().getInstructorIds());
                    if (iShowNames && section.getChoice().getInstructorNames() != null)
                        sectionEl.addAttribute("instructorNames", section.getChoice().getInstructorNames());
                    if (iShowNames)
                        sectionEl.addAttribute("name", section.getName());
                    if (section.getPlacement() != null) {
                        TimeLocation tl = section.getPlacement().getTimeLocation();
                        if (tl != null) {
                            Element timeLocationEl = sectionEl.addElement("time");
                            timeLocationEl.addAttribute("days",
                                    sDF[7].format(Long.parseLong(Integer.toBinaryString(tl.getDayCode()))));
                            timeLocationEl.addAttribute("start", String.valueOf(tl.getStartSlot()));
                            timeLocationEl.addAttribute("length", String.valueOf(tl.getLength()));
                            if (tl.getBreakTime() != 0)
                                timeLocationEl.addAttribute("breakTime", String.valueOf(tl.getBreakTime()));
                            if (iShowNames && tl.getTimePatternId() != null)
                                timeLocationEl.addAttribute("pattern",
                                        getId("timePattern", tl.getTimePatternId()));
                            if (iShowNames && tl.getDatePatternId() != null)
                                timeLocationEl.addAttribute("datePattern", tl.getDatePatternId().toString());
                            if (iShowNames && tl.getDatePatternName() != null
                                    && tl.getDatePatternName().length() > 0)
                                timeLocationEl.addAttribute("datePatternName", tl.getDatePatternName());
                            timeLocationEl.addAttribute("dates", bitset2string(tl.getWeekCode()));
                            if (iShowNames)
                                timeLocationEl.setText(tl.getLongName());
                        }
                        for (RoomLocation rl : section.getRooms()) {
                            Element roomLocationEl = sectionEl.addElement("room");
                            roomLocationEl.addAttribute("id", getId("room", rl.getId()));
                            if (iShowNames && rl.getBuildingId() != null)
                                roomLocationEl.addAttribute("building", getId("building", rl.getBuildingId()));
                            if (iShowNames && rl.getName() != null)
                                roomLocationEl.addAttribute("name", rl.getName());
                            roomLocationEl.addAttribute("capacity", String.valueOf(rl.getRoomSize()));
                            if (rl.getPosX() != null && rl.getPosY() != null)
                                roomLocationEl.addAttribute("location", rl.getPosX() + "," + rl.getPosY());
                            if (rl.getIgnoreTooFar())
                                roomLocationEl.addAttribute("ignoreTooFar", "true");
                        }
                    }
                    if (iSaveOnlineSectioningInfo) {
                        if (section.getSpaceHeld() != 0.0)
                            sectionEl.addAttribute("hold", sStudentWeightFormat.format(section.getSpaceHeld()));
                        if (section.getSpaceExpected() != 0.0)
                            sectionEl.addAttribute("expect",
                                    sStudentWeightFormat.format(section.getSpaceExpected()));
                    }
                }
            }
        }
        if (!offering.getReservations().isEmpty()) {
            for (Reservation r : offering.getReservations()) {
                Element reservationEl = offeringEl.addElement("reservation");
                reservationEl.addAttribute("id", getId("reservation", r.getId()));
                if (r instanceof GroupReservation) {
                    GroupReservation gr = (GroupReservation) r;
                    reservationEl.addAttribute("type", "group");
                    for (Long studentId : gr.getStudentIds())
                        reservationEl.addElement("student").addAttribute("id", getId("student", studentId));
                    if (gr.getLimit() >= 0.0)
                        reservationEl.addAttribute("limit", String.valueOf(gr.getLimit()));
                } else if (r instanceof IndividualReservation) {
                    reservationEl.addAttribute("type", "individual");
                    for (Long studentId : ((IndividualReservation) r).getStudentIds())
                        reservationEl.addElement("student").addAttribute("id", getId("student", studentId));
                } else if (r instanceof CurriculumReservation) {
                    reservationEl.addAttribute("type", "curriculum");
                    CurriculumReservation cr = (CurriculumReservation) r;
                    if (cr.getLimit() >= 0.0)
                        reservationEl.addAttribute("limit", String.valueOf(cr.getLimit()));
                    reservationEl.addAttribute("area", cr.getAcademicArea());
                    for (String clasf : cr.getClassifications())
                        reservationEl.addElement("classification").addAttribute("code", clasf);
                    for (String major : cr.getMajors())
                        reservationEl.addElement("major").addAttribute("code", major);
                } else if (r instanceof CourseReservation) {
                    reservationEl.addAttribute("type", "course");
                    CourseReservation cr = (CourseReservation) r;
                    reservationEl.addAttribute("course", getId("course", cr.getCourse().getId()));
                }
                for (Config config : r.getConfigs())
                    reservationEl.addElement("config").addAttribute("id", getId("config", config.getId()));
                for (Map.Entry<Subpart, Set<Section>> entry : r.getSections().entrySet()) {
                    for (Section section : entry.getValue()) {
                        reservationEl.addElement("section").addAttribute("id",
                                getId("section", section.getId()));
                    }
                }
            }
        }
    }

    Element studentsEl = root.addElement("students");
    for (Student student : getModel().getStudents()) {
        Element studentEl = studentsEl.addElement("student");
        studentEl.addAttribute("id", getId("student", student.getId()));
        if (student.isDummy())
            studentEl.addAttribute("dummy", "true");
        if (iSaveStudentInfo) {
            for (AcademicAreaCode aac : student.getAcademicAreaClasiffications()) {
                Element aacEl = studentEl.addElement("classification");
                if (aac.getArea() != null)
                    aacEl.addAttribute("area", aac.getArea());
                if (aac.getCode() != null)
                    aacEl.addAttribute("code", aac.getCode());
            }
            for (AcademicAreaCode aac : student.getMajors()) {
                Element aacEl = studentEl.addElement("major");
                if (aac.getArea() != null)
                    aacEl.addAttribute("area", aac.getArea());
                if (aac.getCode() != null)
                    aacEl.addAttribute("code", aac.getCode());
            }
            for (AcademicAreaCode aac : student.getMinors()) {
                Element aacEl = studentEl.addElement("minor");
                if (aac.getArea() != null)
                    aacEl.addAttribute("area", aac.getArea());
                if (aac.getCode() != null)
                    aacEl.addAttribute("code", aac.getCode());
            }
        }
        for (Request request : student.getRequests()) {
            if (request instanceof FreeTimeRequest) {
                Element requestEl = studentEl.addElement("freeTime");
                FreeTimeRequest ft = (FreeTimeRequest) request;
                requestEl.addAttribute("id", getId("request", request.getId()));
                requestEl.addAttribute("priority", String.valueOf(request.getPriority()));
                if (request.isAlternative())
                    requestEl.addAttribute("alternative", "true");
                if (request.getWeight() != 1.0)
                    requestEl.addAttribute("weight", sStudentWeightFormat.format(request.getWeight()));
                TimeLocation tl = ft.getTime();
                if (tl != null) {
                    requestEl.addAttribute("days",
                            sDF[7].format(Long.parseLong(Integer.toBinaryString(tl.getDayCode()))));
                    requestEl.addAttribute("start", String.valueOf(tl.getStartSlot()));
                    requestEl.addAttribute("length", String.valueOf(tl.getLength()));
                    if (iShowNames && tl.getDatePatternId() != null)
                        requestEl.addAttribute("datePattern", tl.getDatePatternId().toString());
                    requestEl.addAttribute("dates", bitset2string(tl.getWeekCode()));
                    if (iShowNames)
                        requestEl.setText(tl.getLongName());
                }
                if (iSaveInitial && request.getInitialAssignment() != null) {
                    requestEl.addElement("initial");
                }
                if (iSaveCurrent && request.getAssignment() != null) {
                    requestEl.addElement("current");
                }
                if (iSaveBest && request.getBestAssignment() != null) {
                    requestEl.addElement("best");
                }
            } else if (request instanceof CourseRequest) {
                CourseRequest cr = (CourseRequest) request;
                Element requestEl = studentEl.addElement("course");
                requestEl.addAttribute("id", getId("request", request.getId()));
                requestEl.addAttribute("priority", String.valueOf(request.getPriority()));
                if (request.isAlternative())
                    requestEl.addAttribute("alternative", "true");
                if (request.getWeight() != 1.0)
                    requestEl.addAttribute("weight", sStudentWeightFormat.format(request.getWeight()));
                requestEl.addAttribute("waitlist", cr.isWaitlist() ? "true" : "false");
                if (cr.getTimeStamp() != null)
                    requestEl.addAttribute("timeStamp", cr.getTimeStamp().toString());
                boolean first = true;
                for (Course course : cr.getCourses()) {
                    if (first)
                        requestEl.addAttribute("course", getId("course", course.getId()));
                    else
                        requestEl.addElement("alternative").addAttribute("course",
                                getId("course", course.getId()));
                    first = false;
                }
                for (Choice choice : cr.getWaitlistedChoices()) {
                    Element choiceEl = requestEl.addElement("waitlisted");
                    choiceEl.addAttribute("offering", getId("offering", choice.getOffering().getId()));
                    choiceEl.setText(choice.getId());
                }
                for (Choice choice : cr.getSelectedChoices()) {
                    Element choiceEl = requestEl.addElement("selected");
                    choiceEl.addAttribute("offering", getId("offering", choice.getOffering().getId()));
                    choiceEl.setText(choice.getId());
                }
                if (iSaveInitial && request.getInitialAssignment() != null) {
                    Element assignmentEl = requestEl.addElement("initial");
                    Enrollment enrollment = request.getInitialAssignment();
                    if (enrollment.getReservation() != null)
                        assignmentEl.addAttribute("reservation",
                                getId("reservation", enrollment.getReservation().getId()));
                    for (Section section : enrollment.getSections()) {
                        Element sectionEl = assignmentEl.addElement("section").addAttribute("id",
                                getId("section", section.getId()));
                        if (iShowNames)
                            sectionEl.setText(section.getName() + " "
                                    + (section.getTime() == null ? " Arr Hrs"
                                            : " " + section.getTime().getLongName())
                                    + (section.getNrRooms() == 0 ? ""
                                            : " " + section.getPlacement().getRoomName(","))
                                    + (section.getChoice().getInstructorNames() == null ? ""
                                            : " " + section.getChoice().getInstructorNames()));
                    }
                }
                if (iSaveCurrent && request.getAssignment() != null) {
                    Element assignmentEl = requestEl.addElement("current");
                    Enrollment enrollment = request.getAssignment();
                    if (enrollment.getReservation() != null)
                        assignmentEl.addAttribute("reservation",
                                getId("reservation", enrollment.getReservation().getId()));
                    for (Section section : enrollment.getSections()) {
                        Element sectionEl = assignmentEl.addElement("section").addAttribute("id",
                                getId("section", section.getId()));
                        if (iShowNames)
                            sectionEl.setText(section.getName() + " "
                                    + (section.getTime() == null ? " Arr Hrs"
                                            : " " + section.getTime().getLongName())
                                    + (section.getNrRooms() == 0 ? ""
                                            : " " + section.getPlacement().getRoomName(","))
                                    + (section.getChoice().getInstructorNames() == null ? ""
                                            : " " + section.getChoice().getInstructorNames()));
                    }
                }
                if (iSaveBest && request.getBestAssignment() != null) {
                    Element assignmentEl = requestEl.addElement("best");
                    Enrollment enrollment = request.getBestAssignment();
                    if (enrollment.getReservation() != null)
                        assignmentEl.addAttribute("reservation",
                                getId("reservation", enrollment.getReservation().getId()));
                    for (Section section : enrollment.getSections()) {
                        Element sectionEl = assignmentEl.addElement("section").addAttribute("id",
                                getId("section", section.getId()));
                        if (iShowNames)
                            sectionEl.setText(section.getName() + " "
                                    + (section.getTime() == null ? " Arr Hrs"
                                            : " " + section.getTime().getLongName())
                                    + (section.getNrRooms() == 0 ? ""
                                            : " " + section.getPlacement().getRoomName(","))
                                    + (section.getChoice().getInstructorNames() == null ? ""
                                            : " " + section.getChoice().getInstructorNames()));
                    }
                }
            }
        }
    }

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

    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:net.sf.eclipsecs.core.config.ConfigurationWriter.java

License:Open Source License

/**
 * Writes the modules of the configuration to the output stream.
 *
 * @param out//from w  w  w.  j  a v  a  2  s . co  m
 *            the ouput stream.
 * @param modules
 *            the modules
 * @param checkConfig
 *            the Check configuration object
 * @throws CheckstylePluginException
 *             error writing the checkstyle configuration
 */
public static void write(OutputStream out, List<Module> modules, ICheckConfiguration checkConfig)
        throws CheckstylePluginException {

    try {
        // pass the configured modules through the save filters
        SaveFilters.process(modules);

        Document doc = DocumentHelper.createDocument();
        doc.addDocType(XMLTags.MODULE_TAG, "-//Puppy Crawl//DTD Check Configuration 1.3//EN",
                "http://www.puppycrawl.com/dtds/configuration_1_3.dtd");

        String lineSeperator = System.getProperty("line.separator"); //$NON-NLS-1$

        String comment = lineSeperator
                + "    This configuration file was written by the eclipse-cs plugin configuration editor" //$NON-NLS-1$
                + lineSeperator;
        doc.addComment(comment);

        // write out name and description as comment
        String description = lineSeperator + "    Checkstyle-Configuration: " //$NON-NLS-1$
                + checkConfig.getName() + lineSeperator + "    Description: " //$NON-NLS-1$
                + (StringUtils.trimToNull(checkConfig.getDescription()) != null
                        ? lineSeperator + checkConfig.getDescription() + lineSeperator
                        : "none" + lineSeperator); //$NON-NLS-1$
        doc.addComment(description);

        // find the root module (Checker)
        // the root module is the only module that has no parent
        List<Module> rootModules = getChildModules(null, modules);
        if (rootModules.size() < 1) {
            throw new CheckstylePluginException(Messages.errorNoRootModule);
        }

        if (rootModules.size() > 1) {
            throw new CheckstylePluginException(Messages.errorMoreThanOneRootModule);
        }

        writeModule(rootModules.get(0), doc, null, modules);

        out.write(XMLUtil.toByteArray(doc));
    } catch (IOException e) {
        CheckstylePluginException.rethrow(e);
    }
}

From source file:nl.tue.gale.common.XPPEntityReader.java

License:Open Source License

protected Document parseDocument() throws DocumentException, IOException, XmlPullParserException {
    DocumentFactory df = getDocumentFactory();
    Document document = df.createDocument();
    Element parent = null;//from  w  w w  .j av a  2  s  . c  om
    XmlPullParser pp = getXPPParser();
    pp.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true);
    pp.setFeature(XmlPullParser.FEATURE_PROCESS_DOCDECL, false);
    defineEntities(pp);

    while (true) {
        int type = pp.nextToken();

        switch (type) {
        case XmlPullParser.PROCESSING_INSTRUCTION: {
            String text = pp.getText();
            int loc = text.indexOf(" ");

            if (loc >= 0) {
                String target = text.substring(0, loc);
                String txt = text.substring(loc + 1);
                document.addProcessingInstruction(target, txt);
            } else {
                document.addProcessingInstruction(text, "");
            }

            break;
        }

        case XmlPullParser.COMMENT: {
            if (parent != null) {
                parent.addComment(pp.getText());
            } else {
                document.addComment(pp.getText());
            }

            break;
        }

        case XmlPullParser.CDSECT: {
            if (parent != null) {
                parent.addCDATA(pp.getText());
            } else {
                String msg = "Cannot have text content outside of the " + "root document";
                throw new DocumentException(msg);
            }

            break;
        }

        case XmlPullParser.ENTITY_REF:
            if (parent != null) {
                if (pp.getName().equals("gt")) {
                    parent.addText(">");
                } else if (pp.getName().equals("lt")) {
                    parent.addText("<");
                } else if (pp.getName().equals("amp")) {
                    parent.addText("&");
                } else if (pp.getName().equals("quot")) {
                    parent.addText("\"");
                } else
                    parent.addEntity(pp.getName(), "&" + pp.getName() + ";");
            }
            break;

        case XmlPullParser.END_DOCUMENT:
            return document;

        case XmlPullParser.START_TAG: {
            QName qname = (pp.getPrefix() == null) ? df.createQName(pp.getName(), pp.getNamespace())
                    : df.createQName(pp.getName(), pp.getPrefix(), pp.getNamespace());
            Element newElement = df.createElement(qname);
            int nsStart = pp.getNamespaceCount(pp.getDepth() - 1);
            int nsEnd = pp.getNamespaceCount(pp.getDepth());

            for (int i = nsStart; i < nsEnd; i++) {
                if (pp.getNamespacePrefix(i) != null) {
                    newElement.addNamespace(pp.getNamespacePrefix(i), pp.getNamespaceUri(i));
                }
            }

            for (int i = 0; i < pp.getAttributeCount(); i++) {
                QName qa = (pp.getAttributePrefix(i) == null) ? df.createQName(pp.getAttributeName(i))
                        : df.createQName(pp.getAttributeName(i), pp.getAttributePrefix(i),
                                pp.getAttributeNamespace(i));
                newElement.addAttribute(qa, pp.getAttributeValue(i));
            }

            if (parent != null) {
                parent.add(newElement);
            } else {
                document.add(newElement);
            }

            parent = newElement;

            break;
        }

        case XmlPullParser.END_TAG: {
            if (parent != null) {
                parent = parent.getParent();
            }

            break;
        }

        case XmlPullParser.TEXT: {
            String text = pp.getText();

            if (parent != null) {
                parent.addText(text);
            } else {
                String msg = "Cannot have text content outside of the " + "root document";
                throw new DocumentException(msg);
            }

            break;
        }

        default:
            break;
        }
    }
}

From source file:org.apache.openmeetings.servlet.outputhandler.CalendarServlet.java

License:Apache License

@Override
protected void service(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
        throws ServletException, IOException {

    try {/*  ww w.j a  v  a 2s  . c  o m*/
        String sid = httpServletRequest.getParameter("sid");

        if (sid == null) {
            sid = "default";
        }
        log.debug("sid: " + sid);

        Long users_id = getBean(SessiondataDao.class).checkSession(sid);
        Long user_level = getBean(UserManager.class).getUserLevelByID(users_id);

        if (user_level != null && user_level > 0) {

            String timeZoneIdAsStr = httpServletRequest.getParameter("timeZoneId");

            if (timeZoneIdAsStr == null) {
                log.error("No timeZoneIdAsStr given, using default");
                timeZoneIdAsStr = "";
            }

            TimeZone timezone = getBean(TimezoneUtil.class)
                    .getTimezoneByOmTimeZoneId(Long.valueOf(timeZoneIdAsStr).longValue());

            String yearStr = httpServletRequest.getParameter("year");
            String monthStr = httpServletRequest.getParameter("month");
            String userStr = httpServletRequest.getParameter("user");
            String contactUser = httpServletRequest.getParameter("contactUser");

            Calendar starttime = GregorianCalendar.getInstance(timezone);
            starttime.set(Calendar.DATE, 1);
            starttime.set(Calendar.MONTH, Integer.parseInt(monthStr) - 1);
            starttime.set(Calendar.MINUTE, 0);
            starttime.set(Calendar.SECOND, 0);
            starttime.set(Calendar.YEAR, Integer.parseInt(yearStr));

            Calendar endtime = GregorianCalendar.getInstance(timezone);
            endtime.set(Calendar.DATE, 1);
            endtime.set(Calendar.MONTH, Integer.parseInt(monthStr));
            endtime.set(Calendar.MINUTE, 0);
            endtime.set(Calendar.SECOND, 0);
            endtime.set(Calendar.YEAR, Integer.parseInt(yearStr));

            Long userToShowId = Long.parseLong(contactUser);
            if (userToShowId == 0) {
                userToShowId = Long.parseLong(userStr);
            }

            List<Appointment> appointements = getBean(AppointmentLogic.class).getAppointmentByRange(
                    userToShowId, new Date(starttime.getTimeInMillis()), new Date(endtime.getTimeInMillis()));

            Document document = DocumentHelper.createDocument();
            document.setXMLEncoding("UTF-8");
            document.addComment("###############################################\n"
                    + getServletContext().getServletContextName() + " Calendar \n"
                    + "###############################################");

            Element vcalendar = document.addElement("vcalendar");

            Element year = vcalendar.addElement("year" + yearStr);
            Element month = year.addElement("month" + monthStr);

            int previousDay = 0;
            Element day = null;

            for (Appointment appointment : appointements) {

                Calendar appStart = Calendar.getInstance(timezone);
                appStart.setTime(appointment.getAppointmentStarttime());

                int dayAsInt = appStart.get(Calendar.DATE);

                if (previousDay != dayAsInt) {

                    day = month.addElement("day" + dayAsInt);

                    previousDay = dayAsInt;

                }

                if (appStart.get(Calendar.MONTH) + 1 == Integer.parseInt(monthStr)) {

                    Element event = day.addElement("event");

                    Element appointementId = event.addElement("appointementId");
                    appointementId.addAttribute("value", "" + appointment.getAppointmentId());

                    Element isConnectedEvent = event.addElement("isConnectedEvent");
                    isConnectedEvent.addAttribute("value", "" + appointment.getIsConnectedEvent());

                    Element rooms_id = event.addElement("rooms_id");
                    Element roomtype = event.addElement("roomtype");
                    if (appointment.getRoom() != null) {
                        rooms_id.addAttribute("value", "" + appointment.getRoom().getRooms_id());
                        roomtype.addAttribute("value",
                                "" + appointment.getRoom().getRoomtype().getRoomtypes_id());
                    } else {
                        rooms_id.addAttribute("value", "0");
                        roomtype.addAttribute("value", "1");
                    }
                    Element remindType = event.addElement("remindtype");
                    remindType.addAttribute("value",
                            appointment.getRemind() != null ? "" + appointment.getRemind().getTypId() : "0");

                    Element summary = event.addElement("summary");
                    summary.addAttribute("value", appointment.getAppointmentName());

                    Element comment = event.addElement("comment");
                    comment.addAttribute("value", appointment.getAppointmentDescription());

                    Element start = event.addElement("start");

                    start.addAttribute("year", "" + appStart.get(Calendar.YEAR));
                    start.addAttribute("month", "" + (appStart.get(Calendar.MONTH) + 1));
                    start.addAttribute("day", "" + appStart.get(Calendar.DATE));
                    start.addAttribute("hour", "" + appStart.get(Calendar.HOUR_OF_DAY));
                    start.addAttribute("minute", "" + appStart.get(Calendar.MINUTE));

                    Calendar appEnd = Calendar.getInstance(timezone);
                    appEnd.setTime(appointment.getAppointmentEndtime());
                    Element end = event.addElement("end");
                    end.addAttribute("year", "" + appEnd.get(Calendar.YEAR));
                    end.addAttribute("month", "" + (appEnd.get(Calendar.MONTH) + 1));
                    end.addAttribute("day", "" + appEnd.get(Calendar.DATE));
                    end.addAttribute("hour", "" + appEnd.get(Calendar.HOUR_OF_DAY));
                    end.addAttribute("minute", "" + appEnd.get(Calendar.MINUTE));

                    Element category = event.addElement("category");
                    category.addAttribute("value", "" + appointment.getAppointmentCategory().getCategoryId());

                    Element uid = event.addElement("uid");
                    uid.addAttribute("value", "" + appointment.getAppointmentId());

                    Element attendees = event.addElement("attendees");

                    for (MeetingMember meetingMember : appointment.getMeetingMember()) {

                        Element attendee = attendees.addElement("attendee");

                        Element email = attendee.addElement("email");
                        email.addAttribute("value", meetingMember.getEmail());

                        Element userId = attendee.addElement("userId");
                        if (meetingMember.getUserid() != null) {
                            userId.addAttribute("value", "" + meetingMember.getUserid().getUser_id());
                        } else {
                            userId.addAttribute("value", "");
                        }

                        Element memberId = attendee.addElement("memberId");
                        memberId.addAttribute("value", "" + meetingMember.getMeetingMemberId());

                        Element firstname = attendee.addElement("firstname");
                        memberId.addAttribute("value", "" + meetingMember.getMeetingMemberId());
                        firstname.addAttribute("value", meetingMember.getFirstname());

                        Element lastname = attendee.addElement("lastname");
                        lastname.addAttribute("value", meetingMember.getLastname());

                        Element jNameTimeZoneMember = attendee.addElement("jNameTimeZone");
                        if (meetingMember.getOmTimeZone() != null) {
                            jNameTimeZoneMember.addAttribute("value", meetingMember.getOmTimeZone().getJname());
                        } else {
                            jNameTimeZoneMember.addAttribute("value", "");
                        }

                    }

                }

            }

            httpServletResponse.reset();
            httpServletResponse.resetBuffer();
            OutputStream out = httpServletResponse.getOutputStream();
            httpServletResponse.setContentType("text/xml");

            // httpServletResponse.setHeader("Content-Length", ""+
            // rf.length());

            OutputFormat outformat = OutputFormat.createPrettyPrint();
            outformat.setEncoding("UTF-8");
            XMLWriter writer = new XMLWriter(out, outformat);
            writer.write(document);
            writer.flush();

            out.flush();
            out.close();

        }
    } catch (ServerNotInitializedException e) {
        return;
    } catch (Exception er) {
        log.error("[Calendar :: service]", er);
    }
}

From source file:org.apache.openmeetings.servlet.outputhandler.LangExport.java

License:Apache License

public static Document createDocument() {
    Document document = DocumentHelper.createDocument();
    document.setXMLEncoding("UTF-8");
    document.addComment(LangExport.FILE_COMMENT);
    return document;
}

From source file:org.apache.openmeetings.util.XmlExport.java

License:Apache License

public static Document createDocument() {
    Document document = DocumentHelper.createDocument();
    document.setXMLEncoding(StandardCharsets.UTF_8.name());
    document.addComment(XmlExport.FILE_COMMENT);
    return document;
}

From source file:org.cpsolver.coursett.TimetableXMLSaver.java

License:Open Source License

public Document saveDocument() {
    Document document = DocumentHelper.createDocument();
    document.addComment("University Course Timetabling");

    if (iSaveCurrent && getAssignment().nrAssignedVariables() != 0) {
        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");
        }//  www.j a  va 2 s.  c  o  m
        document.addComment(comments.toString());
    }

    Element root = document.addElement("timetable");

    doSave(root);

    return document;
}

From source file:org.cpsolver.coursett.TimetableXMLSaver.java

License:Open Source License

public void save(File outFile) throws Exception {
    if (outFile == null)
        outFile = new File(iOutputFolder, "solution.xml");
    outFile.getParentFile().mkdirs();/*w w  w.j a  v  a 2s .co  m*/
    sLogger.debug("Writting XML data to:" + outFile);

    Document document = DocumentHelper.createDocument();
    document.addComment("University Course Timetabling");

    if (iSaveCurrent && getAssignment().nrAssignedVariables() != 0) {
        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("timetable");

    doSave(root);

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

        try {
            getSolver().getClass().getMethod("save", new Class[] { Element.class }).invoke(getSolver(),
                    new Object[] { root });
        } catch (Exception e) {
        }
    }

    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)
        iIdConvertor.save();
}

From source file:org.cpsolver.exam.model.ExamModel.java

License:Open Source License

/**
 * Save model (including its solution) into XML.
 * @param assignment current assignment//w  ww .  j a  v a 2 s. c  om
 * @return created XML document
 */
public Document save(Assignment<Exam, ExamPlacement> assignment) {
    boolean saveInitial = getProperties().getPropertyBoolean("Xml.SaveInitial", true);
    boolean saveBest = getProperties().getPropertyBoolean("Xml.SaveBest", true);
    boolean saveSolution = getProperties().getPropertyBoolean("Xml.SaveSolution", true);
    boolean saveConflictTable = getProperties().getPropertyBoolean("Xml.SaveConflictTable", false);
    boolean saveParams = getProperties().getPropertyBoolean("Xml.SaveParameters", true);
    boolean anonymize = getProperties().getPropertyBoolean("Xml.Anonymize", false);
    boolean idconv = getProperties().getPropertyBoolean("Xml.ConvertIds", anonymize);
    Document document = DocumentHelper.createDocument();
    document.addComment("Examination Timetable");
    if (assignment != null && assignment.nrAssignedVariables() > 0) {
        StringBuffer comments = new StringBuffer("Solution Info:\n");
        Map<String, String> solutionInfo = (getProperties().getPropertyBoolean("Xml.ExtendedInfo", false)
                ? 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("examtt");
    root.addAttribute("version", "1.0");
    root.addAttribute("campus", getProperties().getProperty("Data.Initiative"));
    root.addAttribute("term", getProperties().getProperty("Data.Term"));
    root.addAttribute("year", getProperties().getProperty("Data.Year"));
    root.addAttribute("created", String.valueOf(new Date()));
    if (saveParams) {
        Map<String, String> params = new HashMap<String, String>();
        for (Criterion<Exam, ExamPlacement> criterion : getCriteria()) {
            if (criterion instanceof ExamCriterion)
                ((ExamCriterion) criterion).getXmlParameters(params);
        }
        params.put("maxRooms", String.valueOf(getMaxRooms()));
        Element parameters = root.addElement("parameters");
        for (String key : new TreeSet<String>(params.keySet())) {
            parameters.addElement("property").addAttribute("name", key).addAttribute("value", params.get(key));
        }
    }
    Element periods = root.addElement("periods");
    for (ExamPeriod period : getPeriods()) {
        periods.addElement("period").addAttribute("id", getId(idconv, "period", String.valueOf(period.getId())))
                .addAttribute("length", String.valueOf(period.getLength()))
                .addAttribute("day", period.getDayStr()).addAttribute("time", period.getTimeStr())
                .addAttribute("penalty", String.valueOf(period.getPenalty()));
    }
    Element rooms = root.addElement("rooms");
    for (ExamRoom room : getRooms()) {
        Element r = rooms.addElement("room");
        r.addAttribute("id", getId(idconv, "room", String.valueOf(room.getId())));
        if (!anonymize && room.hasName())
            r.addAttribute("name", room.getName());
        r.addAttribute("size", String.valueOf(room.getSize()));
        r.addAttribute("alt", String.valueOf(room.getAltSize()));
        if (room.getCoordX() != null && room.getCoordY() != null)
            r.addAttribute("coordinates", room.getCoordX() + "," + room.getCoordY());
        for (ExamPeriod period : getPeriods()) {
            if (!room.isAvailable(period))
                r.addElement("period")
                        .addAttribute("id", getId(idconv, "period", String.valueOf(period.getId())))
                        .addAttribute("available", "false");
            else if (room.getPenalty(period) != 0)
                r.addElement("period")
                        .addAttribute("id", getId(idconv, "period", String.valueOf(period.getId())))
                        .addAttribute("penalty", String.valueOf(room.getPenalty(period)));
        }
        Map<Long, Integer> travelTimes = getDistanceMetric().getTravelTimes().get(room.getId());
        if (travelTimes != null)
            for (Map.Entry<Long, Integer> time : travelTimes.entrySet())
                r.addElement("travel-time").addAttribute("id", getId(idconv, "room", time.getKey().toString()))
                        .addAttribute("minutes", time.getValue().toString());
    }
    Element exams = root.addElement("exams");
    for (Exam exam : variables()) {
        Element ex = exams.addElement("exam");
        ex.addAttribute("id", getId(idconv, "exam", String.valueOf(exam.getId())));
        if (!anonymize && exam.hasName())
            ex.addAttribute("name", exam.getName());
        ex.addAttribute("length", String.valueOf(exam.getLength()));
        if (exam.getSizeOverride() != null)
            ex.addAttribute("size", exam.getSizeOverride().toString());
        if (exam.getMinSize() != 0)
            ex.addAttribute("minSize", String.valueOf(exam.getMinSize()));
        ex.addAttribute("alt", (exam.hasAltSeating() ? "true" : "false"));
        if (exam.getMaxRooms() != getMaxRooms())
            ex.addAttribute("maxRooms", String.valueOf(exam.getMaxRooms()));
        if (exam.getPrintOffset() != null && !anonymize)
            ex.addAttribute("printOffset", exam.getPrintOffset().toString());
        if (!anonymize)
            ex.addAttribute("enrl", String.valueOf(exam.getStudents().size()));
        if (!anonymize)
            for (ExamOwner owner : exam.getOwners()) {
                Element o = ex.addElement("owner");
                o.addAttribute("id", getId(idconv, "owner", String.valueOf(owner.getId())));
                o.addAttribute("name", owner.getName());
            }
        for (ExamPeriodPlacement period : exam.getPeriodPlacements()) {
            Element pe = ex.addElement("period").addAttribute("id",
                    getId(idconv, "period", String.valueOf(period.getId())));
            int penalty = period.getPenalty() - period.getPeriod().getPenalty();
            if (penalty != 0)
                pe.addAttribute("penalty", String.valueOf(penalty));
        }
        for (ExamRoomPlacement room : exam.getRoomPlacements()) {
            Element re = ex.addElement("room").addAttribute("id",
                    getId(idconv, "room", String.valueOf(room.getId())));
            if (room.getPenalty() != 0)
                re.addAttribute("penalty", String.valueOf(room.getPenalty()));
            if (room.getMaxPenalty() != 100)
                re.addAttribute("maxPenalty", String.valueOf(room.getMaxPenalty()));
        }
        if (exam.hasAveragePeriod())
            ex.addAttribute("average", String.valueOf(exam.getAveragePeriod()));
        ExamPlacement p = (assignment == null ? null : assignment.getValue(exam));
        if (p != null && saveSolution) {
            Element asg = ex.addElement("assignment");
            asg.addElement("period").addAttribute("id",
                    getId(idconv, "period", String.valueOf(p.getPeriod().getId())));
            for (ExamRoomPlacement r : p.getRoomPlacements()) {
                asg.addElement("room").addAttribute("id", getId(idconv, "room", String.valueOf(r.getId())));
            }
        }
        p = exam.getInitialAssignment();
        if (p != null && saveInitial) {
            Element ini = ex.addElement("initial");
            ini.addElement("period").addAttribute("id",
                    getId(idconv, "period", String.valueOf(p.getPeriod().getId())));
            for (ExamRoomPlacement r : p.getRoomPlacements()) {
                ini.addElement("room").addAttribute("id", getId(idconv, "room", String.valueOf(r.getId())));
            }
        }
        p = exam.getBestAssignment();
        if (p != null && saveBest) {
            Element ini = ex.addElement("best");
            ini.addElement("period").addAttribute("id",
                    getId(idconv, "period", String.valueOf(p.getPeriod().getId())));
            for (ExamRoomPlacement r : p.getRoomPlacements()) {
                ini.addElement("room").addAttribute("id", getId(idconv, "room", String.valueOf(r.getId())));
            }
        }
        if (iRoomSharing != null)
            iRoomSharing.save(exam, ex, anonymize ? IdConvertor.getInstance() : null);
    }
    Element students = root.addElement("students");
    for (ExamStudent student : getStudents()) {
        Element s = students.addElement("student");
        s.addAttribute("id", getId(idconv, "student", String.valueOf(student.getId())));
        for (Exam ex : student.variables()) {
            Element x = s.addElement("exam").addAttribute("id",
                    getId(idconv, "exam", String.valueOf(ex.getId())));
            if (!anonymize)
                for (ExamOwner owner : ex.getOwners(student)) {
                    x.addElement("owner").addAttribute("id",
                            getId(idconv, "owner", String.valueOf(owner.getId())));
                }
        }
        for (ExamPeriod period : getPeriods()) {
            if (!student.isAvailable(period))
                s.addElement("period")
                        .addAttribute("id", getId(idconv, "period", String.valueOf(period.getId())))
                        .addAttribute("available", "false");
        }
    }
    Element instructors = root.addElement("instructors");
    for (ExamInstructor instructor : getInstructors()) {
        Element i = instructors.addElement("instructor");
        i.addAttribute("id", getId(idconv, "instructor", String.valueOf(instructor.getId())));
        if (!anonymize && instructor.hasName())
            i.addAttribute("name", instructor.getName());
        for (Exam ex : instructor.variables()) {
            Element x = i.addElement("exam").addAttribute("id",
                    getId(idconv, "exam", String.valueOf(ex.getId())));
            if (!anonymize)
                for (ExamOwner owner : ex.getOwners(instructor)) {
                    x.addElement("owner").addAttribute("id",
                            getId(idconv, "owner", String.valueOf(owner.getId())));
                }
        }
        for (ExamPeriod period : getPeriods()) {
            if (!instructor.isAvailable(period))
                i.addElement("period")
                        .addAttribute("id", getId(idconv, "period", String.valueOf(period.getId())))
                        .addAttribute("available", "false");
        }
    }
    Element distConstraints = root.addElement("constraints");
    for (ExamDistributionConstraint distConstraint : getDistributionConstraints()) {
        Element dc = distConstraints.addElement(distConstraint.getTypeString());
        dc.addAttribute("id", getId(idconv, "constraint", String.valueOf(distConstraint.getId())));
        if (!distConstraint.isHard()) {
            dc.addAttribute("hard", "false");
            dc.addAttribute("weight", String.valueOf(distConstraint.getWeight()));
        }
        for (Exam exam : distConstraint.variables()) {
            dc.addElement("exam").addAttribute("id", getId(idconv, "exam", String.valueOf(exam.getId())));
        }
    }
    if (saveConflictTable && assignment != null) {
        Element conflicts = root.addElement("conflicts");
        Map<ExamStudent, Set<Exam>> studentsOfPreviousPeriod = null;
        for (ExamPeriod period : getPeriods()) {
            Map<ExamStudent, Set<Exam>> studentsOfPeriod = getStudentsOfPeriod(assignment, period);
            for (Map.Entry<ExamStudent, Set<Exam>> entry : studentsOfPeriod.entrySet()) {
                ExamStudent student = entry.getKey();
                Set<Exam> examsOfStudent = entry.getValue();
                if (examsOfStudent.size() > 1) {
                    Element dir = conflicts.addElement("direct").addAttribute("student",
                            getId(idconv, "student", String.valueOf(student.getId())));
                    for (Exam exam : examsOfStudent) {
                        dir.addElement("exam").addAttribute("id",
                                getId(idconv, "exam", String.valueOf(exam.getId())));
                    }
                }
                if (examsOfStudent.size() > 0 && studentsOfPreviousPeriod != null
                        && (isDayBreakBackToBack() || period.prev().getDay() == period.getDay())) {
                    Set<Exam> previousExamsOfStudent = studentsOfPreviousPeriod.get(student);
                    if (previousExamsOfStudent != null) {
                        for (Exam ex1 : previousExamsOfStudent)
                            for (Exam ex2 : examsOfStudent) {
                                Element btb = conflicts.addElement("back-to-back").addAttribute("student",
                                        getId(idconv, "student", String.valueOf(student.getId())));
                                btb.addElement("exam").addAttribute("id",
                                        getId(idconv, "exam", String.valueOf(ex1.getId())));
                                btb.addElement("exam").addAttribute("id",
                                        getId(idconv, "exam", String.valueOf(ex2.getId())));
                                if (getBackToBackDistance() >= 0 && period.prev().getDay() == period.getDay()) {
                                    double dist = (assignment.getValue(ex1))
                                            .getDistanceInMeters(assignment.getValue(ex2));
                                    if (dist > 0)
                                        btb.addAttribute("distance", String.valueOf(dist));
                                }
                            }
                    }
                }
            }
            if (period.next() == null || period.next().getDay() != period.getDay()) {
                Map<ExamStudent, Set<Exam>> studentsOfDay = getStudentsOfDay(assignment, period);
                for (Map.Entry<ExamStudent, Set<Exam>> entry : studentsOfDay.entrySet()) {
                    ExamStudent student = entry.getKey();
                    Set<Exam> examsOfStudent = entry.getValue();
                    if (examsOfStudent.size() > 2) {
                        Element mt2 = conflicts.addElement("more-2-day").addAttribute("student",
                                getId(idconv, "student", String.valueOf(student.getId())));
                        for (Exam exam : examsOfStudent) {
                            mt2.addElement("exam").addAttribute("id",
                                    getId(idconv, "exam", String.valueOf(exam.getId())));
                        }
                    }
                }
            }
            studentsOfPreviousPeriod = studentsOfPeriod;
        }
        /*
        Element conflicts = root.addElement("conflicts");
        for (ExamStudent student : getStudents()) {
        for (ExamPeriod period : getPeriods()) {
            int nrExams = student.getExams(assignment, period).size();
            if (nrExams > 1) {
                Element dir = conflicts.addElement("direct").addAttribute("student", getId(idconv, "student", String.valueOf(student.getId())));
                for (Exam exam : student.getExams(assignment, period)) {
                    dir.addElement("exam").addAttribute("id", getId(idconv, "exam", String.valueOf(exam.getId())));
                }
            }
            if (nrExams > 0) {
                if (period.next() != null && !student.getExams(assignment, period.next()).isEmpty()
                        && (!isDayBreakBackToBack() || period.next().getDay() == period.getDay())) {
                    for (Exam ex1 : student.getExams(assignment, period)) {
                        for (Exam ex2 : student.getExams(assignment, period.next())) {
                            Element btb = conflicts.addElement("back-to-back").addAttribute("student", getId(idconv, "student", String.valueOf(student.getId())));
                            btb.addElement("exam").addAttribute("id", getId(idconv, "exam", String.valueOf(ex1.getId())));
                            btb.addElement("exam").addAttribute("id", getId(idconv, "exam", String.valueOf(ex2.getId())));
                            if (getBackToBackDistance() >= 0) {
                                double dist = (assignment.getValue(ex1)).getDistanceInMeters(assignment.getValue(ex2));
                                if (dist > 0)
                                    btb.addAttribute("distance", String.valueOf(dist));
                            }
                        }
                    }
                }
            }
            if (period.next() == null || period.next().getDay() != period.getDay()) {
                int nrExamsADay = student.getExamsADay(assignment, period.getDay()).size();
                if (nrExamsADay > 2) {
                    Element mt2 = conflicts.addElement("more-2-day").addAttribute("student", getId(idconv, "student", String.valueOf(student.getId())));
                    for (Exam exam : student.getExamsADay(assignment, period.getDay())) {
                        mt2.addElement("exam").addAttribute("id", getId(idconv, "exam", String.valueOf(exam.getId())));
                    }
                }
            }
        }
        }
        */
    }
    return document;
}

From source file:org.cpsolver.ifs.example.tt.TimetableModel.java

License:Open Source License

public void saveAsXML(DataProperties cfg, boolean gen, Solution<Activity, Location> solution,
        Assignment<Activity, Location> assignment, File outFile) throws IOException {
    outFile.getParentFile().mkdirs();//from ww w .ja v a2 s  .  co m
    sLogger.debug("Writting XML data to:" + outFile);

    Document document = DocumentHelper.createDocument();
    document.addComment("Interactive Timetabling - University Timetable Generator (version 2.0)");
    if (assignment == null && solution != null)
        assignment = solution.getAssignment();
    if (assignment == null)
        assignment = new DefaultSingleAssignment<Activity, Location>();

    if (!assignedVariables(assignment).isEmpty()) {
        StringBuffer comments = new StringBuffer("Solution Info:\n");
        Map<String, String> solutionInfo = (solution == null ? getInfo(assignment) : solution.getInfo());
        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("Timetable");
    if (gen) {
        Element generator = root.addElement("Generator");
        generator.addAttribute("version", "2.0");
        generator.addElement("DaysPerWeek").setText(String.valueOf(iNrDays));
        generator.addElement("SlotsPerDay").setText(String.valueOf(iNrHours));
        generator.addElement("NrRooms").setText(cfg.getProperty("Generator.NrRooms", "20"));
        generator.addElement("NrInstructors").setText(cfg.getProperty("Generator.NrInstructors", "20"));
        generator.addElement("NrClasses").setText(cfg.getProperty("Generator.NrClasses", "20"));
        generator.addElement("FillFactor").setText(cfg.getProperty("Generator.FillFactor", "0.8"));
        generator.addElement("ActivityLengthMax").setText(cfg.getProperty("Generator.ActivityLengthMax", "5"));
        generator.addElement("NrGroupsOfRooms").setText(cfg.getProperty("Generator.NrGroupsOfRooms", "20"));
        generator.addElement("NrRoomsInGroupMin").setText(cfg.getProperty("Generator.NrRoomsInGroupMin", "1"));
        generator.addElement("NrRoomsInGroupMax").setText(cfg.getProperty("Generator.NrRoomsInGroupMax", "10"));
        generator.addElement("NrRoomInGroupMin").setText(cfg.getProperty("Generator.NrRoomInGroupMin", "1"));
        generator.addElement("HardFreeResource").setText(cfg.getProperty("Generator.HardFreeResource", "0.05"));
        generator.addElement("SoftFreeResource").setText(cfg.getProperty("Generator.SoftFreeResource", "0.3"));
        generator.addElement("SoftUsedResource").setText(cfg.getProperty("Generator.SoftUsedResource", "0.05"));
        generator.addElement("SoftUsedActivity").setText(cfg.getProperty("Generator.SoftUsedActivity", "0.05"));
        generator.addElement("SoftFreeActivity").setText(cfg.getProperty("Generator.SoftFreeActivity", "0.3"));
        generator.addElement("HardFreeActivity").setText(cfg.getProperty("Generator.HardFreeActivity", "0.05"));
        generator.addElement("NrDependencies").setText(cfg.getProperty("Generator.NrDependencies", "50"));
    }

    ArrayList<Resource> rooms = new ArrayList<Resource>();
    ArrayList<Resource> classes = new ArrayList<Resource>();
    ArrayList<Resource> instructors = new ArrayList<Resource>();
    ArrayList<Resource> specials = new ArrayList<Resource>();
    ArrayList<Dependence> dependencies = new ArrayList<Dependence>();

    for (Constraint<Activity, Location> c : constraints()) {
        if (c instanceof Resource) {
            Resource r = (Resource) c;
            switch (r.getType()) {
            case Resource.TYPE_ROOM:
                rooms.add(r);
                break;
            case Resource.TYPE_CLASS:
                classes.add(r);
                break;
            case Resource.TYPE_INSTRUCTOR:
                instructors.add(r);
                break;
            default:
                specials.add(r);
            }
        } else if (c instanceof Dependence) {
            dependencies.add((Dependence) c);
        }
    }

    Element problem = root.addElement("Problem");
    problem.addAttribute("version", "2.0");
    Element problemGen = problem.addElement("General");
    problemGen.addElement("DaysPerWeek").setText(String.valueOf(iNrDays));
    problemGen.addElement("SlotsPerDay").setText(String.valueOf(iNrHours));
    Element resourceGen = problemGen.addElement("Resources");
    resourceGen.addElement("Classrooms").setText(String.valueOf(rooms.size()));
    resourceGen.addElement("Teachers").setText(String.valueOf(instructors.size()));
    resourceGen.addElement("Classes").setText(String.valueOf(classes.size()));
    resourceGen.addElement("Special").setText(String.valueOf(specials.size()));
    problemGen.addElement("Activities").setText(String.valueOf(variables().size()));
    problemGen.addElement("Dependences").setText(String.valueOf(dependencies.size()));

    Element resources = problem.addElement("Resources");

    Element resEl = resources.addElement("Classrooms");
    for (Resource r : rooms) {
        Element el = resEl.addElement("Resource");
        el.addAttribute("id", r.getResourceId());
        el.addElement("Name").setText(r.getName());
        Element pref = el.addElement("TimePreferences");
        for (Integer slot : new TreeSet<Integer>(r.getDiscouragedSlots()))
            pref.addElement("Soft").setText(slot.toString());
        for (Integer slot : new TreeSet<Integer>(r.getProhibitedSlots()))
            pref.addElement("Hard").setText(slot.toString());
    }

    resEl = resources.addElement("Teachers");
    for (Resource r : instructors) {
        Element el = resEl.addElement("Resource");
        el.addAttribute("id", r.getResourceId());
        el.addElement("Name").setText(r.getName());
        Element pref = el.addElement("TimePreferences");
        for (Integer slot : new TreeSet<Integer>(r.getDiscouragedSlots()))
            pref.addElement("Soft").setText(slot.toString());
        for (Integer slot : new TreeSet<Integer>(r.getProhibitedSlots()))
            pref.addElement("Hard").setText(slot.toString());
    }

    resEl = resources.addElement("Classes");
    for (Resource r : classes) {
        Element el = resEl.addElement("Resource");
        el.addAttribute("id", r.getResourceId());
        el.addElement("Name").setText(r.getName());
        Element pref = el.addElement("TimePreferences");
        for (Integer slot : new TreeSet<Integer>(r.getDiscouragedSlots()))
            pref.addElement("Soft").setText(slot.toString());
        for (Integer slot : new TreeSet<Integer>(r.getProhibitedSlots()))
            pref.addElement("Hard").setText(slot.toString());
    }

    resEl = resources.addElement("Special");
    for (Resource r : specials) {
        Element el = resEl.addElement("Resource");
        el.addAttribute("id", r.getResourceId());
        el.addElement("Name").setText(r.getName());
        Element pref = el.addElement("TimePreferences");
        for (Integer slot : new TreeSet<Integer>(r.getDiscouragedSlots()))
            pref.addElement("Soft").setText(slot.toString());
        for (Integer slot : new TreeSet<Integer>(r.getProhibitedSlots()))
            pref.addElement("Hard").setText(slot.toString());
    }

    boolean hasSolution = false;
    Element actEl = problem.addElement("Activities");
    for (Activity a : variables()) {
        Element el = actEl.addElement("Activity");
        el.addAttribute("id", a.getActivityId());
        el.addElement("Name").setText(a.getName());
        el.addElement("Length").setText(String.valueOf(a.getLength()));
        if (assignment.getValue(a) != null)
            hasSolution = true;
        Element pref = el.addElement("TimePreferences");
        for (Integer slot : new TreeSet<Integer>(a.getDiscouragedSlots()))
            pref.addElement("Soft").setText(slot.toString());
        for (Integer slot : new TreeSet<Integer>(a.getProhibitedSlots()))
            pref.addElement("Hard").setText(slot.toString());
        Element reqRes = el.addElement("RequiredResources");
        for (List<Resource> gr : a.getResourceGroups()) {
            if (gr.size() == 1) {
                reqRes.addElement("Resource").setText(gr.get(0).getResourceId());
            } else {
                Element grEl = reqRes.addElement("Group").addAttribute("conjunctive", "no");
                for (Resource r : gr)
                    grEl.addElement("Resource").setText(r.getResourceId());
            }
        }
    }

    Element depEl = problem.addElement("Dependences");
    for (Dependence d : dependencies) {
        Element el = depEl.addElement("Dependence");
        el.addAttribute("id", d.getResourceId());
        el.addElement("FirstActivity").setText((d.first()).getActivityId());
        el.addElement("SecondActivity").setText((d.second()).getActivityId());
        switch (d.getType()) {
        case Dependence.TYPE_AFTER:
            el.addElement("Operator").setText("After");
            break;
        case Dependence.TYPE_BEFORE:
            el.addElement("Operator").setText("Before");
            break;
        case Dependence.TYPE_CLOSELY_BEFORE:
            el.addElement("Operator").setText("Closely before");
            break;
        case Dependence.TYPE_CLOSELY_AFTER:
            el.addElement("Operator").setText("Closely after");
            break;
        case Dependence.TYPE_CONCURRENCY:
            el.addElement("Operator").setText("Concurrently");
            break;
        default:
            el.addElement("Operator").setText("Unknown");
        }
    }

    if (hasSolution) {
        Element solutionEl = root.addElement("Solution");
        solutionEl.addAttribute("version", "2.0");
        for (Activity a : variables()) {
            Element el = solutionEl.addElement("Activity");
            el.addAttribute("id", a.getActivityId());
            Location location = assignment.getValue(a);
            if (location != null) {
                el.addElement("StartTime").setText(String.valueOf(location.getSlot()));
                Element res = el.addElement("UsedResources");
                for (int i = 0; i < location.getResources().length; i++)
                    res.addElement("Resource").setText(location.getResources()[i].getResourceId());
            }
        }
    }

    FileOutputStream fos = new FileOutputStream(outFile);
    (new XMLWriter(fos, OutputFormat.createPrettyPrint())).write(document);
    fos.flush();
    fos.close();
}