Example usage for org.dom4j.io OutputFormat createPrettyPrint

List of usage examples for org.dom4j.io OutputFormat createPrettyPrint

Introduction

In this page you can find the example usage for org.dom4j.io OutputFormat createPrettyPrint.

Prototype

public static OutputFormat createPrettyPrint() 

Source Link

Document

A static helper method to create the default pretty printing format.

Usage

From source file:net.groupbuy.util.SettingUtils.java

License:Open Source License

/**
 * /*  w w  w.ja  v a  2  s .  c o  m*/
 * 
 * @param setting
 *            
 */
public static void set(Setting setting) {
    try {
        File shopxxXmlFile = new ClassPathResource(CommonAttributes.SHOPXX_XML_PATH).getFile();
        Document document = new SAXReader().read(shopxxXmlFile);
        List<Element> elements = document.selectNodes("/groupbuy/setting");
        for (Element element : elements) {
            try {
                String name = element.attributeValue("name");
                String value = beanUtils.getProperty(setting, name);
                Attribute attribute = element.attribute("value");
                attribute.setValue(value);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            }
        }

        FileOutputStream fileOutputStream = null;
        XMLWriter xmlWriter = null;
        try {
            OutputFormat outputFormat = OutputFormat.createPrettyPrint();
            outputFormat.setEncoding("UTF-8");
            outputFormat.setIndent(true);
            outputFormat.setIndent("   ");
            outputFormat.setNewlines(true);
            fileOutputStream = new FileOutputStream(shopxxXmlFile);
            xmlWriter = new XMLWriter(fileOutputStream, outputFormat);
            xmlWriter.write(document);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (xmlWriter != null) {
                try {
                    xmlWriter.close();
                } catch (IOException e) {
                }
            }
            IOUtils.closeQuietly(fileOutputStream);
        }

        Ehcache cache = cacheManager.getEhcache(Setting.CACHE_NAME);
        cache.put(new net.sf.ehcache.Element(Setting.CACHE_KEY, setting));
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:net.nikr.eve.jeveasset.io.local.update.Update.java

License:Open Source License

void setVersion(final File xml, final int newVersion) throws DocumentException {
    SAXReader xmlReader = new SAXReader();
    Document doc = xmlReader.read(xml);

    XPath xpathSelector = DocumentHelper.createXPath("/settings");
    List<?> results = xpathSelector.selectNodes(doc);
    for (Iterator<?> iter = results.iterator(); iter.hasNext();) {
        Element element = (Element) iter.next();
        Attribute attr = element.attribute("version");
        if (attr == null) {
            element.add(new DefaultAttribute("version", String.valueOf(newVersion)));
        } else {/*from   ww w. jav a  2 s .  c o m*/
            attr.setText(String.valueOf(newVersion));
        }
    }

    try {
        FileOutputStream fos = new FileOutputStream(xml);
        OutputFormat outformat = OutputFormat.createPrettyPrint();
        outformat.setEncoding("UTF-16");
        XMLWriter writer = new XMLWriter(fos, outformat);
        writer.write(doc);
        writer.flush();
    } catch (IOException ioe) {
        LOG.error("Failed to update the serttings.xml version number", ioe);
        throw new RuntimeException(ioe);
    }
}

From source file:net.nikr.eve.jeveasset.io.local.update.updates.Update1To2.java

License:Open Source License

@Override
public void performUpdate(final String path) {
    LOG.info("Performing update from v1 to v2");
    LOG.info(" - modifies files:");
    LOG.info("  - settings.xml");
    try {//from  ww  w  .ja  va 2 s.  c  o m
        // We need to update the settings
        // current changes are:
        // 1. XPath: /settings/filters/filter/row[@mode]
        // changed from (e.g.) "Contains" to the enum value name in AssetFilter.Mode
        // 2. settings/marketstat[@defaultprice] --> another enum: Asset.PriceMode
        // 3. settings/columns/column --> settings/tables/table/column
        // settings/flags/flag --> removed two flags (now in settings/tables/table)
        SAXReader xmlReader = new SAXReader();
        Document doc = xmlReader.read(path);
        convertDefaultPriceModes(doc);
        convertModes(doc);
        convertTableSettings(doc);

        FileOutputStream fos = new FileOutputStream(path);
        OutputFormat outformat = OutputFormat.createPrettyPrint();
        outformat.setEncoding("UTF-16");
        XMLWriter writer = new XMLWriter(fos, outformat);
        writer.write(doc);
        writer.flush();
    } catch (IOException ex) {
        LOG.error("", ex);
        throw new RuntimeException(ex);
    } catch (DocumentException ex) {
        LOG.error("", ex);
        throw new RuntimeException(ex);
    }
}

From source file:net.osxx.util.SettingUtils.java

License:Open Source License

/**
 * /*from   w  w  w . j a  va 2 s  .  co m*/
 * 
 * @param setting
 *            
 */
public static void set(Setting setting) {
    try {
        File osxxXmlFile = new ClassPathResource(CommonAttributes.SHOPXX_XML_PATH).getFile();
        Document document = new SAXReader().read(osxxXmlFile);
        List<Element> elements = document.selectNodes("/osxx/setting");
        for (Element element : elements) {
            try {
                String name = element.attributeValue("name");
                String value = beanUtils.getProperty(setting, name);
                Attribute attribute = element.attribute("value");
                attribute.setValue(value);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            }
        }

        FileOutputStream fileOutputStream = null;
        XMLWriter xmlWriter = null;
        try {
            OutputFormat outputFormat = OutputFormat.createPrettyPrint();
            outputFormat.setEncoding("UTF-8");
            outputFormat.setIndent(true);
            outputFormat.setIndent("   ");
            outputFormat.setNewlines(true);
            fileOutputStream = new FileOutputStream(osxxXmlFile);
            xmlWriter = new XMLWriter(fileOutputStream, outputFormat);
            xmlWriter.write(document);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (xmlWriter != null) {
                try {
                    xmlWriter.close();
                } catch (IOException e) {
                }
            }
            IOUtils.closeQuietly(fileOutputStream);
        }

        Ehcache cache = cacheManager.getEhcache(Setting.CACHE_NAME);
        cache.put(new net.sf.ehcache.Element(Setting.CACHE_KEY, setting));
    } catch (Exception e) {
        e.printStackTrace();
    }
}

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 w w .  j  a  va2s.  co m
 */
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  ava2 s .  co  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.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  va 2 s  .c  om*/
    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();
}

From source file:net.sf.cpsolver.studentsct.StudentRequestXml.java

License:Open Source License

public static void main(String[] args) {
    try {// www.jav a2s .  c om
        ToolBox.configureLogging();
        StudentSectioningModel model = new StudentSectioningModel(new DataProperties());
        StudentSectioningXMLLoader xmlLoad = new StudentSectioningXMLLoader(model);
        xmlLoad.setInputFile(new File(args[0]));
        xmlLoad.load();
        Document document = exportModel(model);
        FileOutputStream fos = new FileOutputStream(new File(args[1]));
        (new XMLWriter(fos, OutputFormat.createPrettyPrint())).write(document);
        fos.flush();
        fos.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:net.sf.cpsolver.studentsct.StudentSectioningXMLSaver.java

License:Open Source License

/**
 * Save an XML file/*w  ww . ja v a 2  s  .  c om*/
 * 
 * @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.util.XMLUtil.java

License:Open Source License

/**
 * Creates a pretty printed representation of the document as a byte array.
 * /*from  w w w .ja v  a2s .  c o m*/
 * @param document the document
 * @return the document as a byte array (UTF-8)
 * @throws IOException Exception while serializing the document
 */
public static byte[] toByteArray(Document document) throws IOException {

    ByteArrayOutputStream byteOut = new ByteArrayOutputStream(512);

    // Pretty print the document to System.out
    OutputFormat format = OutputFormat.createPrettyPrint();
    XMLWriter writer = new XMLWriter(byteOut, format);
    writer.write(document);

    return byteOut.toByteArray();
}