Example usage for org.dom4j DocumentHelper createDocument

List of usage examples for org.dom4j DocumentHelper createDocument

Introduction

In this page you can find the example usage for org.dom4j DocumentHelper createDocument.

Prototype

public static Document createDocument() 

Source Link

Usage

From source file:net.bpfurtado.ljcolligo.persistence.xml.Events2XMLWriter.java

License:Open Source License

public Events2XMLWriter() {
    Document doc = DocumentHelper.createDocument();
    Element root = doc.addElement("events");
    this.root = root;
}

From source file:net.bpfurtado.ljcolligo.persistence.xml.Map2XMLWriter.java

License:Open Source License

public Map2XMLWriter() {
    Document doc = DocumentHelper.createDocument();
    Element root = doc.addElement("events");
    this.root = root;
}

From source file:net.bpfurtado.tas.model.persistence.XMLAdventureWriter.java

License:Open Source License

private Document createXML() {
    Document doc = DocumentHelper.createDocument();
    Element root = doc.addElement("adventure");
    root.addAttribute("startScene", adventure.getStart().getId() + "");
    root.addElement("name").setText(adventure.getName());
    // root.addElement("id").setText(adventure.getId());

    Element assertions = root.addElement("assertions");
    assertions.addCDATA(adventure.getAssertions());

    Element scenes = root.addElement("scenes");
    createSceneNodes(scenes);//w  w  w  .  java2 s.c o m

    return doc;
}

From source file:net.bpfurtado.tas.runner.savegame.SaveGamePersister.java

License:Open Source License

public static Document createXML(SaveGame saveGame) {
    Document xml = DocumentHelper.createDocument();

    Element root = xml.addElement("savegame");
    root.addAttribute("sceneId", saveGame.getSceneId() + "");
    root.addAttribute("creation", saveGame.getCreationAsString());
    root.addAttribute("workspaceId", saveGame.getWorkspace().getId());

    Player player = saveGame.getPlayer();

    Element xmlPlayer = root.addElement("player");
    xmlPlayer.addAttribute("stamina", player.getStamina() + "");
    xmlPlayer.addAttribute("damage", player.getDamage() + "");

    Element skills = xmlPlayer.addElement("skills");
    for (Skill sk : player.getSkills()) {
        Element skill = skills.addElement("skill");
        skill.addAttribute("name", sk.getName());
        skill.addAttribute("level", sk.getLevel() + "");
    }// w w  w  . j ava 2 s.c  o  m

    Element attributes = xmlPlayer.addElement("attributes");
    for (Entry<String, String> e : player.getAttributesEntrySet()) {
        Element attribute = attributes.addElement("attribute");
        attribute.addAttribute("key", e.getKey());
        attribute.addAttribute("value", e.getValue());
    }

    return xml;
}

From source file:net.contextfw.web.application.component.DOMBuilder.java

License:Apache License

public DOMBuilder(String rootName, AttributeSerializer<Object> serializer, ComponentBuilder componentBuilder,
        Collection<KeyValue<String, String>> namespaces) {

    this.serializer = serializer;
    root = DocumentHelper.createElement(rootName);
    document = DocumentHelper.createDocument();
    document.setRootElement(root);//from ww w. j  ava2s  . c  o m
    for (KeyValue<String, String> namespace : namespaces) {
        root.add(DocumentHelper.createNamespace(namespace.getKey(), namespace.getValue()));
    }

    this.componentBuilder = componentBuilder;
}

From source file:net.daimonin.client3d.editor.main.Editor3D.java

License:Open Source License

/**
* Builds image groups/categories by file name, creates and writes the XML
* containing all images with their attributes.
* 
* @param fileNameImageSet Name of resulting PNG.
* @param fileNameXML Name of the XML./* w w w . j a v a  2  s  . c  om*/
* @throws IOException IOException.
*/
private static void writeXML(final String fileNameImageSet, final String fileNameXML) throws IOException {

    // group ImageSetImages by name/category.
    // the left side of the image file name up to the '_' is taken as the
    // category
    Hashtable<String, List<ImageSetImage>> names = new Hashtable<String, List<ImageSetImage>>();
    for (int i = 0; i < images.size(); i++) {
        if (!names.containsKey(images.get(i).getName())) {
            List<ImageSetImage> values = new ArrayList<ImageSetImage>();
            values.add(images.get(i));
            names.put(images.get(i).getName(), values);
        } else {
            names.get(images.get(i).getName()).add(images.get(i));
        }
    }

    // check if every category has a default state (except FontExtensions)
    Enumeration<String> keys2 = names.keys();
    while (keys2.hasMoreElements()) {
        List<ImageSetImage> img2 = names.get(keys2.nextElement());
        if (!"fontextensions".equals(img2.get(0).getName())) {
            boolean hasDefault = false;
            for (int i = 0; i < img2.size(); i++) {
                if ("default".equals(img2.get(i).getState().toLowerCase())) {
                    hasDefault = true;
                }
            }
            if (!hasDefault) {
                printError("WARNING: image category '" + img2.get(0).getName()
                        + "' has no image with a default state!");
            }
        }
    }

    // create the XML structure
    Document document = DocumentHelper.createDocument();
    Element root = document.addElement("ImageSet").addAttribute("file", fileNameImageSet);

    List<ImageSetImage> fntex = names.get("fontextensions");
    if (fntex != null) {
        Element category = root.addElement("ImageFntExt").addAttribute("name", fntex.get(0).getName());
        for (int i = 0; i < fntex.size(); i++) {
            category.addElement("State").addAttribute("name", fntex.get(i).getState())
                    .addAttribute("posX", String.valueOf(fntex.get(i).getPosX() + fntex.get(i).getBorderSize()))
                    .addAttribute("posY", String.valueOf(fntex.get(i).getPosY() + fntex.get(i).getBorderSize()))
                    .addAttribute("width", String.valueOf(fntex.get(i).getWidth()))
                    .addAttribute("height", String.valueOf(fntex.get(i).getHeight()));
        }
        names.remove("fontextensions");
    }

    List<ImageSetImage> mouse = names.get("mousecursor");
    if (mouse != null) {
        Element category = root.addElement("Image").addAttribute("name", mouse.get(0).getName())
                .addAttribute("width", String.valueOf(mouse.get(0).getImage().getWidth()))
                .addAttribute("height", String.valueOf(mouse.get(0).getImage().getHeight()))
                .addAttribute("alpha", mouse.get(0).getImage().getColorModel().hasAlpha() ? String.valueOf(1)
                        : String.valueOf(0));

        for (int i = 0; i < mouse.size(); i++) {
            checkImageSameDimension(mouse.get(0), mouse.get(i),
                    "Images of same category have different dimension");
            checkImageSameAlpha(mouse.get(0), mouse.get(i), "Images of same category have different alpha");
            category.addElement("State").addAttribute("name", mouse.get(i).getState())
                    .addAttribute("posX", String.valueOf(mouse.get(i).getPosX() + mouse.get(i).getBorderSize()))
                    .addAttribute("posY",
                            String.valueOf(mouse.get(i).getPosY() + mouse.get(i).getBorderSize()));
        }
        names.remove("mousecursor");
    }

    Enumeration<String> keys = names.keys();
    while (keys.hasMoreElements()) {
        List<ImageSetImage> img = names.get(keys.nextElement());
        Element category = root.addElement("Image").addAttribute("name", img.get(0).getName())
                .addAttribute("width", String.valueOf(img.get(0).getImage().getWidth()))
                .addAttribute("height", String.valueOf(img.get(0).getImage().getHeight()))
                .addAttribute("alpha", img.get(0).getImage().getColorModel().hasAlpha() ? String.valueOf(1)
                        : String.valueOf(0));

        for (int i = 0; i < img.size(); i++) {
            checkImageSameDimension(img.get(0), img.get(i), "Images of same category have different dimension");
            checkImageSameAlpha(img.get(0), img.get(i), "Images of same category have different alpha");
            category.addElement("State").addAttribute("name", img.get(i).getState())
                    .addAttribute("posX", String.valueOf(img.get(i).getPosX() + img.get(i).getBorderSize()))
                    .addAttribute("posY", String.valueOf(img.get(i).getPosY() + img.get(i).getBorderSize()));
        }
    }

    // write the XML
    OutputFormat format = OutputFormat.createPrettyPrint();
    XMLWriter writer = new XMLWriter(new FileWriter(fileNameXML), format);
    writer.write(document);
    writer.close();
    printInfo(System.getProperty("user.dir") + "/" + imagesetxml + " created");
}

From source file:net.sf.cpsolver.coursett.IdConvertor.java

License:Open Source License

/**
 * Save id conversion file. Name of the file needs to be provided by system
 * property IdConvertor.File/*from  w ww.j a  va2s  .  c  om*/
 */
public void save() {
    (new File(iFile)).getParentFile().mkdirs();
    Document document = DocumentHelper.createDocument();
    Element root = document.addElement("id-convertor");
    synchronized (iConversion) {
        for (Map.Entry<String, HashMap<String, String>> entry : iConversion.entrySet()) {
            String type = entry.getKey();
            HashMap<String, String> conversion = entry.getValue();
            Element convEl = root.addElement(type);
            for (Map.Entry<String, String> idConv : conversion.entrySet()) {
                convEl.addElement("conv").addAttribute("old", idConv.getKey()).addAttribute("new",
                        idConv.getValue());
            }
        }
    }
    FileOutputStream fos = null;
    try {
        fos = new FileOutputStream(iFile);
        (new XMLWriter(fos, OutputFormat.createPrettyPrint())).write(document);
        fos.flush();
        fos.close();
        fos = null;
    } catch (Exception e) {
        sLogger.error("Unable to save id conversions, reason: " + e.getMessage(), e);
    } finally {
        try {
            if (fos != null)
                fos.close();
        } catch (IOException e) {
        }
    }
}

From source file:net.sf.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();//from  w  w  w  .j  a va2s  . c o  m
    sLogger.debug("Writting XML data to:" + outFile);

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

    if (iSaveCurrent && !getModel().assignedVariables().isEmpty()) {
        StringBuffer comments = new StringBuffer("Solution Info:\n");
        Map<String, String> solutionInfo = (getSolution() == null ? getModel().getInfo()
                : getSolution().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");
    root.addAttribute("version", "2.5");
    root.addAttribute("initiative", getModel().getProperties().getProperty("Data.Initiative"));
    root.addAttribute("term", getModel().getProperties().getProperty("Data.Term"));
    root.addAttribute("year", String.valueOf(getModel().getYear()));
    root.addAttribute("created", String.valueOf(new Date()));
    root.addAttribute("nrDays", String.valueOf(Constants.DAY_CODES.length));
    root.addAttribute("slotsPerDay", String.valueOf(Constants.SLOTS_PER_DAY));
    if (!iConvertIds && getModel().getProperties().getProperty("General.SessionId") != null)
        root.addAttribute("session", getModel().getProperties().getProperty("General.SessionId"));
    if (iShowNames && !iConvertIds && getModel().getProperties().getProperty("General.SolverGroupId") != null)
        root.addAttribute("solverGroup",
                getId("solverGroup", getModel().getProperties().getProperty("General.SolverGroupId")));

    HashMap<String, Element> roomElements = new HashMap<String, Element>();

    Element roomsEl = root.addElement("rooms");
    for (RoomConstraint roomConstraint : getModel().getRoomConstraints()) {
        Element roomEl = roomsEl.addElement("room").addAttribute("id",
                getId("room", roomConstraint.getResourceId()));
        roomEl.addAttribute("constraint", "true");
        if (roomConstraint instanceof DiscouragedRoomConstraint)
            roomEl.addAttribute("discouraged", "true");
        if (iShowNames) {
            roomEl.addAttribute("name", roomConstraint.getRoomName());
        }
        if (!iConvertIds && roomConstraint.getBuildingId() != null)
            roomEl.addAttribute("building", getId("bldg", roomConstraint.getBuildingId()));
        roomElements.put(getId("room", roomConstraint.getResourceId()), roomEl);
        roomEl.addAttribute("capacity", String.valueOf(roomConstraint.getCapacity()));
        if (roomConstraint.getPosX() != null && roomConstraint.getPosY() != null)
            roomEl.addAttribute("location", roomConstraint.getPosX() + "," + roomConstraint.getPosY());
        if (roomConstraint.getIgnoreTooFar())
            roomEl.addAttribute("ignoreTooFar", "true");
        if (!roomConstraint.getConstraint())
            roomEl.addAttribute("fake", "true");
        if (roomConstraint.getSharingModel() != null) {
            RoomSharingModel sharingModel = roomConstraint.getSharingModel();
            Element sharingEl = roomEl.addElement("sharing");
            sharingEl.addElement("pattern").addAttribute("unit", "6").setText(sharingModel.getPreferences());
            sharingEl.addElement("freeForAll").addAttribute("value",
                    String.valueOf(RoomSharingModel.sFreeForAllPrefChar));
            sharingEl.addElement("notAvailable").addAttribute("value",
                    String.valueOf(RoomSharingModel.sNotAvailablePrefChar));
            for (int i = 0; i < sharingModel.getNrDepartments(); i++) {
                sharingEl.addElement("department").addAttribute("value", String.valueOf((char) ('0' + i)))
                        .addAttribute("id", getId("dept", sharingModel.getDepartmentIds()[i]));
            }
        }
        if (roomConstraint.getType() != null && iShowNames)
            roomEl.addAttribute("type", roomConstraint.getType().toString());
    }

    Element instructorsEl = root.addElement("instructors");

    Element departmentsEl = root.addElement("departments");
    HashMap<Long, String> depts = new HashMap<Long, String>();

    Element configsEl = (iShowNames ? root.addElement("configurations") : null);
    HashSet<Configuration> configs = new HashSet<Configuration>();

    Element classesEl = root.addElement("classes");
    HashMap<Long, Element> classElements = new HashMap<Long, Element>();
    List<Lecture> vars = new ArrayList<Lecture>(getModel().variables());
    if (getModel().hasConstantVariables())
        vars.addAll(getModel().constantVariables());
    for (Lecture lecture : vars) {
        Placement placement = lecture.getAssignment();
        if (lecture.isCommitted() && placement == null)
            placement = lecture.getInitialAssignment();
        Placement initialPlacement = lecture.getInitialAssignment();
        // if (initialPlacement==null) initialPlacement =
        // (Placement)lecture.getAssignment();
        Placement bestPlacement = lecture.getBestAssignment();
        Element classEl = classesEl.addElement("class").addAttribute("id",
                getId("class", lecture.getClassId()));
        classElements.put(lecture.getClassId(), classEl);
        if (iShowNames && lecture.getNote() != null)
            classEl.addAttribute("note", lecture.getNote());
        if (iShowNames && !lecture.isCommitted())
            classEl.addAttribute("ord", String.valueOf(lecture.getOrd()));
        if (iShowNames && lecture.getSolverGroupId() != null)
            classEl.addAttribute("solverGroup", getId("solverGroup", lecture.getSolverGroupId()));
        if (lecture.getParent() == null && lecture.getConfiguration() != null) {
            if (!iShowNames)
                classEl.addAttribute("offering",
                        getId("offering", lecture.getConfiguration().getOfferingId().toString()));
            classEl.addAttribute("config",
                    getId("config", lecture.getConfiguration().getConfigId().toString()));
            if (iShowNames && configs.add(lecture.getConfiguration())) {
                configsEl.addElement("config")
                        .addAttribute("id",
                                getId("config", lecture.getConfiguration().getConfigId().toString()))
                        .addAttribute("limit", String.valueOf(lecture.getConfiguration().getLimit()))
                        .addAttribute("offering",
                                getId("offering", lecture.getConfiguration().getOfferingId().toString()));
            }
        }
        classEl.addAttribute("committed", (lecture.isCommitted() ? "true" : "false"));
        if (lecture.getParent() != null)
            classEl.addAttribute("parent", getId("class", lecture.getParent().getClassId()));
        if (lecture.getSchedulingSubpartId() != null)
            classEl.addAttribute("subpart", getId("subpart", lecture.getSchedulingSubpartId()));
        if (iShowNames && lecture.isCommitted() && placement != null && placement.getAssignmentId() != null) {
            classEl.addAttribute("assignment", getId("assignment", placement.getAssignmentId()));
        }
        if (!lecture.isCommitted()) {
            if (lecture.minClassLimit() == lecture.maxClassLimit()) {
                classEl.addAttribute("classLimit", String.valueOf(lecture.maxClassLimit()));
            } else {
                classEl.addAttribute("minClassLimit", String.valueOf(lecture.minClassLimit()));
                classEl.addAttribute("maxClassLimit", String.valueOf(lecture.maxClassLimit()));
            }
            if (lecture.roomToLimitRatio() != 1.0)
                classEl.addAttribute("roomToLimitRatio", String.valueOf(lecture.roomToLimitRatio()));
        }
        if (lecture.getNrRooms() != 1)
            classEl.addAttribute("nrRooms", String.valueOf(lecture.getNrRooms()));
        if (iShowNames)
            classEl.addAttribute("name", lecture.getName());
        if (lecture.getDeptSpreadConstraint() != null) {
            classEl.addAttribute("department",
                    getId("dept", lecture.getDeptSpreadConstraint().getDepartmentId()));
            depts.put(lecture.getDeptSpreadConstraint().getDepartmentId(),
                    lecture.getDeptSpreadConstraint().getName());
        }
        if (lecture.getScheduler() != null)
            classEl.addAttribute("scheduler", getId("dept", lecture.getScheduler()));
        for (InstructorConstraint ic : lecture.getInstructorConstraints()) {
            Element instrEl = classEl.addElement("instructor").addAttribute("id",
                    getId("inst", ic.getResourceId()));
            if ((lecture.isCommitted() || iSaveCurrent) && placement != null)
                instrEl.addAttribute("solution", "true");
            if (iSaveInitial && initialPlacement != null)
                instrEl.addAttribute("initial", "true");
            if (iSaveBest && bestPlacement != null && !bestPlacement.equals(placement))
                instrEl.addAttribute("best", "true");
        }
        for (RoomLocation rl : lecture.roomLocations()) {
            Element roomLocationEl = classEl.addElement("room");
            roomLocationEl.addAttribute("id", getId("room", rl.getId()));
            roomLocationEl.addAttribute("pref", String.valueOf(rl.getPreference()));
            if ((lecture.isCommitted() || iSaveCurrent) && placement != null
                    && placement.hasRoomLocation(rl.getId()))
                roomLocationEl.addAttribute("solution", "true");
            if (iSaveInitial && initialPlacement != null && initialPlacement.hasRoomLocation(rl.getId()))
                roomLocationEl.addAttribute("initial", "true");
            if (iSaveBest && bestPlacement != null && !bestPlacement.equals(placement)
                    && bestPlacement.hasRoomLocation(rl.getId()))
                roomLocationEl.addAttribute("best", "true");
            if (!roomElements.containsKey(getId("room", rl.getId()))) {
                // room location without room constraint
                Element roomEl = roomsEl.addElement("room").addAttribute("id", getId("room", rl.getId()));
                roomEl.addAttribute("constraint", "false");
                if (!iConvertIds && rl.getBuildingId() != null)
                    roomEl.addAttribute("building", getId("bldg", rl.getBuildingId()));
                if (iShowNames) {
                    roomEl.addAttribute("name", rl.getName());
                }
                roomElements.put(getId("room", rl.getId()), roomEl);
                roomEl.addAttribute("capacity", String.valueOf(rl.getRoomSize()));
                if (rl.getPosX() != null && rl.getPosY() != null)
                    roomEl.addAttribute("location", rl.getPosX() + "," + rl.getPosY());
                if (rl.getIgnoreTooFar())
                    roomEl.addAttribute("ignoreTooFar", "true");
            }
        }
        boolean first = true;
        for (TimeLocation tl : lecture.timeLocations()) {
            Element timeLocationEl = classEl.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()));
            timeLocationEl.addAttribute("breakTime", String.valueOf(tl.getBreakTime()));
            if (iShowNames) {
                timeLocationEl.addAttribute("pref", String.valueOf(tl.getPreference()));
                timeLocationEl.addAttribute("npref", String.valueOf(tl.getNormalizedPreference()));
            } else {
                timeLocationEl.addAttribute("pref", String.valueOf(tl.getNormalizedPreference()));
            }
            if (!iConvertIds && tl.getTimePatternId() != null)
                timeLocationEl.addAttribute("pattern", getId("pat", tl.getTimePatternId()));
            if (first) {
                if (!iConvertIds && tl.getDatePatternId() != null)
                    classEl.addAttribute("datePattern", getId("dpat", String.valueOf(tl.getDatePatternId())));
                if (iShowNames)
                    classEl.addAttribute("datePatternName", tl.getDatePatternName());
                classEl.addAttribute("dates", bitset2string(tl.getWeekCode()));
                first = false;
            }
            if ((lecture.isCommitted() || iSaveCurrent) && placement != null
                    && placement.getTimeLocation().equals(tl))
                timeLocationEl.addAttribute("solution", "true");
            if (iSaveInitial && initialPlacement != null && initialPlacement.getTimeLocation().equals(tl))
                timeLocationEl.addAttribute("initial", "true");
            if (iSaveBest && bestPlacement != null && !bestPlacement.equals(placement)
                    && bestPlacement.getTimeLocation().equals(tl))
                timeLocationEl.addAttribute("best", "true");
        }
    }

    for (InstructorConstraint ic : getModel().getInstructorConstraints()) {
        if (iShowNames || ic.isIgnoreDistances()) {
            Element instrEl = instructorsEl.addElement("instructor").addAttribute("id",
                    getId("inst", ic.getResourceId()));
            if (iShowNames) {
                if (ic.getPuid() != null && ic.getPuid().length() > 0)
                    instrEl.addAttribute("puid", ic.getPuid());
                instrEl.addAttribute("name", ic.getName());
                if (ic.getType() != null && iShowNames)
                    instrEl.addAttribute("type", ic.getType().toString());
            }
            if (ic.isIgnoreDistances()) {
                instrEl.addAttribute("ignDist", "true");
            }
        }
        if (ic.getAvailableArray() != null) {
            HashSet<Long> done = new HashSet<Long>();
            for (int i = 0; i < ic.getAvailableArray().length; i++) {
                if (ic.getAvailableArray()[i] != null) {
                    for (Placement placement : ic.getAvailableArray()[i]) {
                        Lecture lecture = placement.variable();
                        if (done.add(lecture.getClassId())) {
                            Element classEl = classElements.get(lecture.getClassId());
                            classEl.addElement("instructor")
                                    .addAttribute("id", getId("inst", ic.getResourceId()))
                                    .addAttribute("solution", "true");
                        }
                    }
                }
            }
        }
    }
    if (instructorsEl.elements().isEmpty())
        root.remove(instructorsEl);

    Element grConstraintsEl = root.addElement("groupConstraints");
    for (GroupConstraint gc : getModel().getGroupConstraints()) {
        Element grEl = grConstraintsEl.addElement("constraint").addAttribute("id",
                getId("gr", String.valueOf(gc.getId())));
        grEl.addAttribute("type", gc.getType().reference());
        grEl.addAttribute("pref", gc.getPrologPreference());
        for (Lecture l : gc.variables()) {
            grEl.addElement("class").addAttribute("id", getId("class", l.getClassId()));
        }
    }
    for (SpreadConstraint spread : getModel().getSpreadConstraints()) {
        Element grEl = grConstraintsEl.addElement("constraint").addAttribute("id",
                getId("gr", String.valueOf(spread.getId())));
        grEl.addAttribute("type", "SPREAD");
        grEl.addAttribute("pref", Constants.sPreferenceRequired);
        if (iShowNames)
            grEl.addAttribute("name", spread.getName());
        for (Lecture l : spread.variables()) {
            grEl.addElement("class").addAttribute("id", getId("class", l.getClassId()));
        }
    }
    for (Constraint<Lecture, Placement> c : getModel().constraints()) {
        if (c instanceof MinimizeNumberOfUsedRoomsConstraint) {
            Element grEl = grConstraintsEl.addElement("constraint").addAttribute("id",
                    getId("gr", String.valueOf(c.getId())));
            grEl.addAttribute("type", "MIN_ROOM_USE");
            grEl.addAttribute("pref", Constants.sPreferenceRequired);
            for (Lecture l : c.variables()) {
                grEl.addElement("class").addAttribute("id", getId("class", l.getClassId()));
            }
        }
        if (c instanceof MinimizeNumberOfUsedGroupsOfTime) {
            Element grEl = grConstraintsEl.addElement("constraint").addAttribute("id",
                    getId("gr", String.valueOf(c.getId())));
            grEl.addAttribute("type", ((MinimizeNumberOfUsedGroupsOfTime) c).getConstraintName());
            grEl.addAttribute("pref", Constants.sPreferenceRequired);
            for (Lecture l : c.variables()) {
                grEl.addElement("class").addAttribute("id", getId("class", l.getClassId()));
            }
        }
    }
    for (ClassLimitConstraint clc : getModel().getClassLimitConstraints()) {
        Element grEl = grConstraintsEl.addElement("constraint").addAttribute("id",
                getId("gr", String.valueOf(clc.getId())));
        grEl.addAttribute("type", "CLASS_LIMIT");
        grEl.addAttribute("pref", Constants.sPreferenceRequired);
        if (clc.getParentLecture() != null) {
            grEl.addElement("parentClass").addAttribute("id",
                    getId("class", clc.getParentLecture().getClassId()));
        } else
            grEl.addAttribute("courseLimit", String.valueOf(clc.classLimit() - clc.getClassLimitDelta()));
        if (clc.getClassLimitDelta() != 0)
            grEl.addAttribute("delta", String.valueOf(clc.getClassLimitDelta()));
        if (iShowNames)
            grEl.addAttribute("name", clc.getName());
        for (Lecture l : clc.variables()) {
            grEl.addElement("class").addAttribute("id", getId("class", l.getClassId()));
        }
    }

    HashMap<Student, List<String>> students = new HashMap<Student, List<String>>();
    for (Lecture lecture : vars) {
        for (Student student : lecture.students()) {
            List<String> enrls = students.get(student);
            if (enrls == null) {
                enrls = new ArrayList<String>();
                students.put(student, enrls);
            }
            enrls.add(getId("class", lecture.getClassId()));
        }
    }

    Element studentsEl = root.addElement("students");
    for (Student student : new TreeSet<Student>(students.keySet())) {
        Element stEl = studentsEl.addElement("student").addAttribute("id", getId("student", student.getId()));
        if (iShowNames) {
            if (student.getAcademicArea() != null)
                stEl.addAttribute("area", student.getAcademicArea());
            if (student.getAcademicClassification() != null)
                stEl.addAttribute("classification", student.getAcademicClassification());
            if (student.getMajor() != null)
                stEl.addAttribute("major", student.getMajor());
            if (student.getCurriculum() != null)
                stEl.addAttribute("curriculum", student.getCurriculum());
        }
        for (Map.Entry<Long, Double> entry : student.getOfferingsMap().entrySet()) {
            Long offeringId = entry.getKey();
            Double weight = entry.getValue();
            Element offEl = stEl.addElement("offering").addAttribute("id",
                    getId("offering", offeringId.toString()));
            if (weight.doubleValue() != 1.0)
                offEl.addAttribute("weight", sStudentWeightFormat.format(weight));
        }
        if (iExportStudentSectioning || getModel().unassignedVariables().isEmpty()
                || student.getOfferingsMap().isEmpty()) {
            List<String> lectures = students.get(student);
            Collections.sort(lectures);
            for (String classId : lectures) {
                stEl.addElement("class").addAttribute("id", classId);
            }
        }
        Map<Long, Set<Lecture>> canNotEnroll = student.canNotEnrollSections();
        if (canNotEnroll != null) {
            for (Set<Lecture> canNotEnrollLects : canNotEnroll.values()) {
                for (Iterator<Lecture> i3 = canNotEnrollLects.iterator(); i3.hasNext();) {
                    stEl.addElement("prohibited-class").addAttribute("id",
                            getId("class", (i3.next()).getClassId()));
                }
            }
        }

        if (student.getCommitedPlacements() != null) {
            for (Placement placement : student.getCommitedPlacements()) {
                stEl.addElement("class").addAttribute("id", getId("class", placement.variable().getClassId()));
            }
        }
    }

    if (getModel().getProperties().getPropertyInt("MPP.GenTimePert", 0) > 0) {
        Element perturbationsEl = root.addElement("perturbations");
        int nrChanges = getModel().getProperties().getPropertyInt("MPP.GenTimePert", 0);
        List<Lecture> lectures = new ArrayList<Lecture>();
        while (lectures.size() < nrChanges) {
            Lecture lecture = ToolBox.random(getModel().assignedVariables());
            if (lecture.isCommitted() || lecture.timeLocations().size() <= 1 || lectures.contains(lecture))
                continue;
            Placement placement = lecture.getAssignment();
            TimeLocation tl = placement.getTimeLocation();
            perturbationsEl.addElement("class").addAttribute("id", getId("class", lecture.getClassId()))
                    .addAttribute("days",
                            sDF[7].format(Long.parseLong(Integer.toBinaryString(tl.getDayCode()))))
                    .addAttribute("start", String.valueOf(tl.getStartSlot()))
                    .addAttribute("length", String.valueOf(tl.getLength()));
            lectures.add(lecture);
        }
    }

    for (Map.Entry<Long, String> entry : depts.entrySet()) {
        Long id = entry.getKey();
        String name = entry.getValue();
        if (iShowNames) {
            departmentsEl.addElement("department").addAttribute("id", getId("dept", id.toString()))
                    .addAttribute("name", name);
        }
    }
    if (departmentsEl.elements().isEmpty())
        root.remove(departmentsEl);

    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:net.sf.cpsolver.exam.model.ExamModel.java

License:Open Source License

/**
 * Save model (including its solution) into XML.
 *///w  w  w  . j a v  a 2s .c o  m
public Document save() {
    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);
    Document document = DocumentHelper.createDocument();
    document.addComment("Examination Timetable");
    if (nrAssignedVariables() > 0) {
        StringBuffer comments = new StringBuffer("Solution Info:\n");
        Map<String, String> solutionInfo = (getProperties().getPropertyBoolean("Xml.ExtendedInfo", false)
                ? getExtendedInfo()
                : 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("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) {
        Element params = root.addElement("parameters");
        params.addElement("property").addAttribute("name", "isDayBreakBackToBack").addAttribute("value",
                (isDayBreakBackToBack() ? "true" : "false"));
        params.addElement("property").addAttribute("name", "directConflictWeight").addAttribute("value",
                String.valueOf(getDirectConflictWeight()));
        params.addElement("property").addAttribute("name", "moreThanTwoADayWeight").addAttribute("value",
                String.valueOf(getMoreThanTwoADayWeight()));
        params.addElement("property").addAttribute("name", "backToBackConflictWeight").addAttribute("value",
                String.valueOf(getBackToBackConflictWeight()));
        params.addElement("property").addAttribute("name", "distanceBackToBackConflictWeight")
                .addAttribute("value", String.valueOf(getDistanceBackToBackConflictWeight()));
        params.addElement("property").addAttribute("name", "backToBackDistance").addAttribute("value",
                String.valueOf(getBackToBackDistance()));
        params.addElement("property").addAttribute("name", "maxRooms").addAttribute("value",
                String.valueOf(getMaxRooms()));
        params.addElement("property").addAttribute("name", "periodWeight").addAttribute("value",
                String.valueOf(getPeriodWeight()));
        params.addElement("property").addAttribute("name", "periodSizeWeight").addAttribute("value",
                String.valueOf(getPeriodSizeWeight()));
        params.addElement("property").addAttribute("name", "periodIndexWeight").addAttribute("value",
                String.valueOf(getPeriodIndexWeight()));
        params.addElement("property").addAttribute("name", "examRotationWeight").addAttribute("value",
                String.valueOf(getExamRotationWeight()));
        params.addElement("property").addAttribute("name", "roomSizeWeight").addAttribute("value",
                String.valueOf(getRoomSizeWeight()));
        params.addElement("property").addAttribute("name", "roomSplitWeight").addAttribute("value",
                String.valueOf(getRoomSplitWeight()));
        params.addElement("property").addAttribute("name", "roomWeight").addAttribute("value",
                String.valueOf(getRoomWeight()));
        params.addElement("property").addAttribute("name", "distributionWeight").addAttribute("value",
                String.valueOf(getDistributionWeight()));
        params.addElement("property").addAttribute("name", "instructorDirectConflictWeight")
                .addAttribute("value", String.valueOf(getInstructorDirectConflictWeight()));
        params.addElement("property").addAttribute("name", "instructorMoreThanTwoADayWeight")
                .addAttribute("value", String.valueOf(getInstructorMoreThanTwoADayWeight()));
        params.addElement("property").addAttribute("name", "instructorBackToBackConflictWeight")
                .addAttribute("value", String.valueOf(getInstructorBackToBackConflictWeight()));
        params.addElement("property").addAttribute("name", "instructorDistanceBackToBackConflictWeight")
                .addAttribute("value", String.valueOf(getInstructorDistanceBackToBackConflictWeight()));
        params.addElement("property").addAttribute("name", "perturbationWeight").addAttribute("value",
                String.valueOf(getPerturbationWeight()));
        params.addElement("property").addAttribute("name", "roomPerturbationWeight").addAttribute("value",
                String.valueOf(getRoomPerturbationWeight()));
        params.addElement("property").addAttribute("name", "roomSplitDistanceWeight").addAttribute("value",
                String.valueOf(getRoomSplitDistanceWeight()));
        params.addElement("property").addAttribute("name", "largeSize").addAttribute("value",
                String.valueOf(getLargeSize()));
        params.addElement("property").addAttribute("name", "largePeriod").addAttribute("value",
                String.valueOf(getLargePeriod()));
        params.addElement("property").addAttribute("name", "largeWeight").addAttribute("value",
                String.valueOf(getLargeWeight()));
    }
    Element periods = root.addElement("periods");
    for (ExamPeriod period : getPeriods()) {
        periods.addElement("period")
                .addAttribute("id", getId(anonymize, "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(anonymize, "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(anonymize, "period", String.valueOf(period.getId())))
                        .addAttribute("available", "false");
            else if (room.getPenalty(period) != 0)
                r.addElement("period")
                        .addAttribute("id", getId(anonymize, "period", String.valueOf(period.getId())))
                        .addAttribute("penalty", String.valueOf(room.getPenalty(period)));
        }
    }
    Element exams = root.addElement("exams");
    for (Exam exam : variables()) {
        Element ex = exams.addElement("exam");
        ex.addAttribute("id", getId(anonymize, "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)
            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(anonymize, "owner", String.valueOf(owner.getId())));
                o.addAttribute("name", owner.getName());
            }
        for (ExamPeriodPlacement period : exam.getPeriodPlacements()) {
            Element pe = ex.addElement("period").addAttribute("id",
                    getId(anonymize, "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(anonymize, "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 = exam.getAssignment();
        if (p != null && saveSolution) {
            Element asg = ex.addElement("assignment");
            asg.addElement("period").addAttribute("id",
                    getId(anonymize, "period", String.valueOf(p.getPeriod().getId())));
            for (ExamRoomPlacement r : p.getRoomPlacements()) {
                asg.addElement("room").addAttribute("id", getId(anonymize, "room", String.valueOf(r.getId())));
            }
        }
        p = exam.getInitialAssignment();
        if (p != null && saveInitial) {
            Element ini = ex.addElement("initial");
            ini.addElement("period").addAttribute("id",
                    getId(anonymize, "period", String.valueOf(p.getPeriod().getId())));
            for (ExamRoomPlacement r : p.getRoomPlacements()) {
                ini.addElement("room").addAttribute("id", getId(anonymize, "room", String.valueOf(r.getId())));
            }
        }
        p = exam.getBestAssignment();
        if (p != null && saveBest) {
            Element ini = ex.addElement("best");
            ini.addElement("period").addAttribute("id",
                    getId(anonymize, "period", String.valueOf(p.getPeriod().getId())));
            for (ExamRoomPlacement r : p.getRoomPlacements()) {
                ini.addElement("room").addAttribute("id", getId(anonymize, "room", String.valueOf(r.getId())));
            }
        }
    }
    Element students = root.addElement("students");
    for (ExamStudent student : getStudents()) {
        Element s = students.addElement("student");
        s.addAttribute("id", getId(anonymize, "student", String.valueOf(student.getId())));
        for (Exam ex : student.variables()) {
            Element x = s.addElement("exam").addAttribute("id",
                    getId(anonymize, "exam", String.valueOf(ex.getId())));
            if (!anonymize)
                for (ExamOwner owner : ex.getOwners(student)) {
                    x.addElement("owner").addAttribute("id",
                            getId(anonymize, "owner", String.valueOf(owner.getId())));
                }
        }
        for (ExamPeriod period : getPeriods()) {
            if (!student.isAvailable(period))
                s.addElement("period")
                        .addAttribute("id", getId(anonymize, "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(anonymize, "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(anonymize, "exam", String.valueOf(ex.getId())));
            if (!anonymize)
                for (ExamOwner owner : ex.getOwners(instructor)) {
                    x.addElement("owner").addAttribute("id",
                            getId(anonymize, "owner", String.valueOf(owner.getId())));
                }
        }
        for (ExamPeriod period : getPeriods()) {
            if (!instructor.isAvailable(period))
                i.addElement("period")
                        .addAttribute("id", getId(anonymize, "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(anonymize, "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(anonymize, "exam", String.valueOf(exam.getId())));
        }
    }
    if (saveConflictTable) {
        Element conflicts = root.addElement("conflicts");
        for (ExamStudent student : getStudents()) {
            for (ExamPeriod period : getPeriods()) {
                int nrExams = student.getExams(period).size();
                if (nrExams > 1) {
                    Element dir = conflicts.addElement("direct").addAttribute("student",
                            getId(anonymize, "student", String.valueOf(student.getId())));
                    for (Exam exam : student.getExams(period)) {
                        dir.addElement("exam").addAttribute("id",
                                getId(anonymize, "exam", String.valueOf(exam.getId())));
                    }
                }
                if (nrExams > 0) {
                    if (period.next() != null && !student.getExams(period.next()).isEmpty()
                            && (!isDayBreakBackToBack() || period.next().getDay() == period.getDay())) {
                        for (Exam ex1 : student.getExams(period)) {
                            for (Exam ex2 : student.getExams(period.next())) {
                                Element btb = conflicts.addElement("back-to-back").addAttribute("student",
                                        getId(anonymize, "student", String.valueOf(student.getId())));
                                btb.addElement("exam").addAttribute("id",
                                        getId(anonymize, "exam", String.valueOf(ex1.getId())));
                                btb.addElement("exam").addAttribute("id",
                                        getId(anonymize, "exam", String.valueOf(ex2.getId())));
                                if (getBackToBackDistance() >= 0) {
                                    double dist = (ex1.getAssignment())
                                            .getDistanceInMeters(ex2.getAssignment());
                                    if (dist > 0)
                                        btb.addAttribute("distance", String.valueOf(dist));
                                }
                            }
                        }
                    }
                }
                if (period.next() == null || period.next().getDay() != period.getDay()) {
                    int nrExamsADay = student.getExamsADay(period.getDay()).size();
                    if (nrExamsADay > 2) {
                        Element mt2 = conflicts.addElement("more-2-day").addAttribute("student",
                                getId(anonymize, "student", String.valueOf(student.getId())));
                        for (Exam exam : student.getExamsADay(period.getDay())) {
                            mt2.addElement("exam").addAttribute("id",
                                    getId(anonymize, "exam", String.valueOf(exam.getId())));
                        }
                    }
                }
            }
        }

    }
    return document;
}

From source file:net.sf.cpsolver.ifs.example.tt.TimetableModel.java

License:Open Source License

public void saveAsXML(DataProperties cfg, boolean gen, Solution<Activity, Location> solution, File outFile)
        throws IOException {
    outFile.getParentFile().mkdirs();/*ww  w. j a v  a  2  s  . c  o m*/
    sLogger.debug("Writting XML data to:" + outFile);

    Document document = DocumentHelper.createDocument();
    document.addComment("Interactive Timetabling - University Timetable Generator (version 2.0)");

    if (!assignedVariables().isEmpty()) {
        StringBuffer comments = new StringBuffer("Solution Info:\n");
        Map<String, String> solutionInfo = (solution == null ? getInfo() : 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 (a.getAssignment() != 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());
            if (a.getAssignment() != null) {
                Location location = a.getAssignment();
                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();
}