List of usage examples for org.dom4j Document addComment
Document addComment(String comment);
Comment
node with the given text to this branch. From source file:at.jabberwocky.impl.core.io.PacketReader.java
private Document parseDocument() throws DocumentException, IOException, XmlPullParserException { DocumentFactory df = docFactory;//from ww w .j a v a 2 s.c om Document document = df.createDocument(); Element parent = null; XmlPullParser pp = parser; int count = 0; while (true) { int type = -1; type = pp.nextToken(); switch (type) { case XmlPullParser.PROCESSING_INSTRUCTION: { String text = pp.getText(); int loc = text.indexOf(" "); if (loc >= 0) { document.addProcessingInstruction(text.substring(0, loc), text.substring(loc + 1)); } else { document.addProcessingInstruction(text, ""); } break; } case XmlPullParser.COMMENT: { if (parent != null) { parent.addComment(pp.getText()); } else { document.addComment(pp.getText()); } break; } case XmlPullParser.CDSECT: { String text = pp.getText(); if (parent != null) { parent.addCDATA(text); } else { if (text.trim().length() > 0) { throw new DocumentException("Cannot have text content outside of the root document"); } } break; } case XmlPullParser.ENTITY_REF: { String text = pp.getText(); if (parent != null) { parent.addText(text); } else { if (text.trim().length() > 0) { throw new DocumentException("Cannot have an entityref outside of the root document"); } } break; } case XmlPullParser.END_DOCUMENT: { return document; } case XmlPullParser.START_TAG: { QName qname = (pp.getPrefix() == null) ? df.createQName(pp.getName(), pp.getNamespace()) : df.createQName(pp.getName(), pp.getPrefix(), pp.getNamespace()); Element newElement = null; // Do not include the namespace if this is the start tag of a new packet // This avoids including "jabber:client", "jabber:server" or // "jabber:component:accept" if ("jabber:client".equals(qname.getNamespaceURI()) || "jabber:server".equals(qname.getNamespaceURI()) || "jabber:component:accept".equals(qname.getNamespaceURI()) || "http://jabber.org/protocol/httpbind".equals(qname.getNamespaceURI())) { newElement = df.createElement(pp.getName()); } else { newElement = df.createElement(qname); } int nsStart = pp.getNamespaceCount(pp.getDepth() - 1); int nsEnd = pp.getNamespaceCount(pp.getDepth()); for (int i = nsStart; i < nsEnd; i++) { if (pp.getNamespacePrefix(i) != null) { newElement.addNamespace(pp.getNamespacePrefix(i), pp.getNamespaceUri(i)); } } for (int i = 0; i < pp.getAttributeCount(); i++) { QName qa = (pp.getAttributePrefix(i) == null) ? df.createQName(pp.getAttributeName(i)) : df.createQName(pp.getAttributeName(i), pp.getAttributePrefix(i), pp.getAttributeNamespace(i)); newElement.addAttribute(qa, pp.getAttributeValue(i)); } if (parent != null) { parent.add(newElement); } else { document.add(newElement); } parent = newElement; count++; break; } case XmlPullParser.END_TAG: { if (parent != null) { parent = parent.getParent(); } count--; if (count < 1) { return document; } break; } case XmlPullParser.TEXT: { String text = pp.getText(); if (parent != null) { parent.addText(text); } else { if (text.trim().length() > 0) { throw new DocumentException("Cannot have text content outside of the root document"); } } break; } default: } } }
From source file:com.autoupdater.client.xml.creators.FileCacheXMLCreator.java
License:Apache License
/** * Creates XML document with file cache data and stores it info file. * //from ww w. j a v a 2 s .c o m * @param destination * destination file * @param fileCache * file cache which needs to be saved * @throws IOException * thrown when error occurs during storing data to file */ public void createXML(File destination, Map<String, String> fileCache) throws IOException { logger.debug("Save file cache data at: " + destination.getCanonicalPath()); Document fileCacheXML = DocumentHelper.createDocument(); fileCacheXML.addComment(XMLCreationConfiguration.DO_NOT_EDIT_FILE_MANUALLY_WARNING); Element files = fileCacheXML.addElement(FileCacheSchema.files); addFiles(files, fileCache); Files.write(fileCacheXML.asXML(), destination, XMLCreationConfiguration.XML_ENCODING); logger.trace("Saved file cache data at: " + destination.getCanonicalPath()); }
From source file:com.example.sample.pMainActivity.java
License:Apache License
public Document createXMLDocument() { Document doc = null; doc = DocumentHelper.createDocument(); doc.addComment("edited with XMLSpy v2005 rel. 3 U (http://www.altova.com) by ()"); // doc.addDocType("class","//By Jack Chen","saveXML.xsd"); Element root = doc.addElement("class"); Element company = root.addElement("company"); Element person = company.addElement("person"); person.addAttribute("id", "11"); person.addElement("name").setText("Jack Chen"); person.addElement("sex").setText(""); person.addElement("date").setText("2001-04-01"); person.addElement("email").setText("chen@163.com"); person.addElement("QQ").setText("2366001"); return doc;//from w w w . java 2 s. c o m }
From source file:com.orange.atk.phone.android.wizard.AndroidWizard.java
License:Apache License
public void printReport() { String configXmlFileName = configFileName + ".xml"; Document configxml = DocumentHelper.createDocument(); configxml.addComment(" " + phone.getName() + " configuration file "); configxml.addComment(" Screen resolution " + screenWidth + "x" + screenHeight + " "); Element root = configxml.addElement("Android-config"); Element canalPattern = root.addElement("CanalPattern"); //keyboards/*from w w w.ja v a2s.c o m*/ if (!keyboard.equals("")) printKeyMapping("keyboard", keyboard, canalPattern, root); if (!keyboard2.equals("")) printKeyMapping("keyboard2", keyboard2, canalPattern, root); if (!keyboard3.equals("")) printKeyMapping("keyboard3", keyboard3, canalPattern, root); Set<String> softKeySet = softKeyMap.keySet(); Element keyMapping = root.addElement("SoftKeyMapping"); for (String key : softKeySet) { keyMapping.addElement("Key").addAttribute("name", key) .addAttribute("avgX", "" + softKeyMap.get(key).getX()) .addAttribute("avgY", "" + softKeyMap.get(key).getY()); } //touchscreen if (!touchscreen.equals("")) { canalPattern.addElement("Pattern").addAttribute("canal", "touchscreen").addAttribute("value", touchscreen.replace("\"", "")); Element Touchscreen = root.addElement("Touchscreen"); Touchscreen.addComment("!!! THIS IS JUST TOUCHSCREEN Elements TEMPLATE !!!"); Touchscreen .addComment("!!! SEE ATK User Guide - Configuration section - and UPDATE following values !!!"); if (codeX != -1 && codeY != -1) { Touchscreen.addComment("!!! Please check following X Y ratioX and ratioY patterns"); Touchscreen.addElement("Pattern").addAttribute("name", "X").addAttribute("value", "3 " + codeX + " "); Touchscreen.addElement("Pattern").addAttribute("name", "Y").addAttribute("value", "3 " + codeY + " "); long ratio = maxX * 100 / screenWidth; Touchscreen.addElement("Pattern").addAttribute("name", "ratioX").addAttribute("value", String.valueOf((double) ratio / 100.0)); ratio = maxY * 100 / screenHeight; Touchscreen.addElement("Pattern").addAttribute("name", "ratioY").addAttribute("value", String.valueOf((double) ratio / 100.0)); Touchscreen.addComment("!!! Please update following patterns"); } else { Touchscreen.addElement("Pattern").addAttribute("name", "X").addAttribute("value", "0 0 "); Touchscreen.addElement("Pattern").addAttribute("name", "Y").addAttribute("value", "0 0 "); Touchscreen.addElement("Pattern").addAttribute("name", "ratioX").addAttribute("value", "1.0"); Touchscreen.addElement("Pattern").addAttribute("name", "ratioY").addAttribute("value", "1.0"); } Touchscreen.addElement("Pattern").addAttribute("name", "down").addAttribute("value", "0 0 0"); Touchscreen.addElement("Pattern").addAttribute("name", "downmax").addAttribute("value", "0 0 0"); Touchscreen.addElement("Pattern").addAttribute("name", "up").addAttribute("value", "0 0 0"); Touchscreen.addElement("Pattern").addAttribute("name", "flush").addAttribute("value", "0 0 0"); Touchscreen.addElement("Pattern").addAttribute("name", "flush2").addAttribute("value", "0 2 0"); Touchscreen.addElement("Threshold").addAttribute("name", "move").addAttribute("value", "15"); Touchscreen.addElement("Option").addAttribute("name", "sendMouseDownForMove").addAttribute("value", "true"); Touchscreen.addElement("Option").addAttribute("name", "sendMouseEventFirst").addAttribute("value", "true"); Touchscreen.addElement("Option").addAttribute("name", "useMonkeyForPress").addAttribute("value", "true"); } //Write the file. OutputFormat format = OutputFormat.createPrettyPrint(); XMLWriter writer = null; try { writer = new XMLWriter(new FileWriter(configXmlFileName), format); writer.write(configxml); writer.close(); } catch (IOException e) { e.printStackTrace(); } //Show a confirm dialog and exit the wizard JOptionPane.showConfirmDialog(this, "A template of the config file has been created under \n" + configXmlFileName + "\n" + "See ATK User guide to configure the Touchscreen section of this template\n", "Success", JOptionPane.CLOSED_OPTION); exit(true); }
From source file:com.synesoft.fisp.app.common.utils.XmlFileUtil.java
License:Open Source License
/** * add comment for root ele//from w w w . ja v a 2 s . co m * * @param explain * text * @param doc */ public static void addCommend(String explain, Document doc) { doc.addComment(explain); }
From source file:edu.upenn.cis.orchestra.workloadgenerator.GeneratorJournal.java
License:Apache License
/** * Serializes the journal in the format below. The peer and maping elements * are as in the Orchestra schema file./*www . j a v a2 s . c om*/ * * <pre> * <?xml version="1.0" encoding="UTF-8"?> * <!--00:50:07 06/12/08 EDT * {integers=1, inout=true, oracle=0, skip=0, cutoff=1024, password=password, addBypasses=1, deletions=1, * username=xyz, relsize=15, tukwila=0, fanout=2, olivier=1, schemas=3, dbalias=BIOTBS, insertions=2, * iterations=2, seed=0, mappingsServer=jdbc:db2://localhost:50000, bidir=0, updateAlias=null, addPeers=1, * coverage=1.0, deleteBypasses=1, maxcycles=-1, peers=3, filename=prot, mincycles=-1, deletePeers=1}--> * <deltas> * <iteration idx="0"> * <operation type="addPeer" name="P0"/> * <operation type="addPeer" name="P1"> * <mapping name="M0"/> * <mapping name="M2"/> * </operation> * <operation type="addPeer" name="P2"> * <mapping name="M1"/> * </operation> * </iteration> * <iteration idx="1"> * <operation type="addPeer" name="P3"> * <mapping name="M3"/> * </operation> * <operation type="deletePeer" name="P0"/> * </iteration> * <iteration idx="2"> * <operation type="addPeer" name="P4"> * <mapping name="M4"/> * <mapping name="M5"/> * <mapping name="M6"/> * </operation> * <operation type="deletePeer" name="P2"/> * <operation type="addBypass" name="M23"/> * <operation type="deleteBypass" name="M2"/> * </iteration> * <peer name="P0" address="localhost"> * </peer> * <mapping name="M0" materialized="true"> * </mapping> * </deltas> * * </pre> * * @param params * run parameters, see <code>Generator</code>. * @return serialzed <code>GeneratorJournal</code>. */ @SuppressWarnings("unchecked") public Document serialize(Map<String, Object> params) { // TODO: this method copies code from MetadataXml, needs refactoring. Document deltasDoc = DocumentHelper.createDocument(); deltasDoc.addComment(WorkloadGeneratorUtils.stamp() + "\n" + params); Element deltas = deltasDoc.addElement("deltas"); List<Integer> indexes = new LinkedList<Integer>(_operations.keySet()); Collections.sort(indexes); for (Integer idx : indexes) { Element iteration = deltas.addElement("iteration").addAttribute("idx", idx.toString()); List<List<String>> operations = _operations.get(idx); for (List<String> operation : operations) { Element opElement = iteration.addElement("operation").addAttribute("type", operation.get(0)) .addAttribute("name", operation.get(1)); if ("addPeer".equals(operation.get(0))) { if (null == _peersToMaps.get(operation.get(1))) { continue; } for (String mapping : _peersToMaps.get(operation.get(1))) { opElement.addElement("mapping").addAttribute("name", mapping); } } } } for (int i = 0; i < _peers.size(); i++) { Element peer = deltas.addElement("peer").addAttribute("name", "P" + i).addAttribute("address", "localhost"); int j = _peers.get(i); Element schema = peer.addElement("schema").addAttribute("name", "S" + j); for (int k = 0; k < _logicalSchemas.get(j).size(); k++) { for (String var : iovariations((Boolean) params.get("inout"))) { Element relation = schema.addElement("relation") .addAttribute("name", WorkloadGeneratorUtils.relname(i, j, k) + var) .addAttribute("materialized", "true"); if ((Double) params.get("coverage") == 1) { relation.addAttribute("noNulls", "true"); } String hasLocalData; if (Generator.peerHasLocalData(i, (Integer) params.get("topology"), (Integer) params.get("modlocal"), (Integer) params.get("peers"), (Integer) params.get("fanout"))) { hasLocalData = "true"; } else { hasLocalData = "false"; } relation.addAttribute("hasLocalData", hasLocalData); relation.addElement("dbinfo").addAttribute("schema", (String) params.get("username")) .addAttribute("table", WorkloadGeneratorUtils.relname(i, j, k) + var); relation.addElement("field").addAttribute("name", "KID").addAttribute("type", "integer") .addAttribute("key", "true"); for (String att : _logicalSchemas.get(j).get(k)) { relation.addElement("field").addAttribute("name", att).addAttribute("type", MetadataXml.universalType(att, params)); } } } } for (int k = 0; k < _mappings.size(); k++) { int i = (Integer) _mappings.get(k).get(1); int j = (Integer) _mappings.get(k).get(2); List<String> x = (List<String>) _mappings.get(k).get(3); List<String> source = MetadataXml.selectAtoms(i, "KID", x, "_", _logicalSchemas, _peers, (Boolean) params.get("addValueAttr"), true); // _ means don't care List<String> target = MetadataXml.selectAtoms(j, "KID", x, "-", _logicalSchemas, _peers, (Boolean) params.get("addValueAttr"), false); // - means null Element mapping = deltas.addElement("mapping").addAttribute("name", "M" + k) .addAttribute("materialized", "true"); if (1 == (Integer) params.get("bidir")) { mapping.addAttribute("bidirectional", "true"); } Element head = mapping.addElement("head"); for (String atom : target) { Element atomElem = head.addElement("atom"); if (1 == (Integer) params.get("bidir")) { atomElem.addAttribute("del", "true"); } atomElem.addText(atom); } Element body = mapping.addElement("body"); for (String atom : source) { Element atomElem = body.addElement("atom"); if (1 == (Integer) params.get("bidir")) { atomElem.addAttribute("del", "true"); } atomElem.addText(atom); } } return deltasDoc; }
From source file:edu.upenn.cis.orchestra.workloadgenerator.MetadataXml.java
License:Apache License
@SuppressWarnings("unchecked") public void metadataXml(List<List<List<String>>> schemas, List<Integer> peers, List<List<Object>> mappings, String extension) {/*from ww w . j a va 2 s . co m*/ Writer writer = null; if (null == _params.get("filename")) { writer = new PrintWriter(System.out); } else { try { if (!"".equals(extension)) { extension = "." + extension; } writer = new FileWriter((String) _params.get("filename") + extension + ".schema"); // + ".schema.new"); } catch (IOException e) { throw new IllegalStateException("Unable to create schema file.", e); } } Document document = DocumentHelper.createDocument(); document.addComment(WorkloadGeneratorUtils.stamp() + "\n" + _params); Element catalog = document.addElement("catalog").addAttribute("recMode", "false").addAttribute("name", (String) _params.get("filename")); catalog.addElement("migrated").setText("true"); for (int i = 0; i < peers.size(); i++) { if (null == peers.get(i)) { continue; } Element peer = catalog.addElement("peer").addAttribute("name", "P" + i).addAttribute("address", "localhost"); int j = peers.get(i); Element schema = peer.addElement("schema").addAttribute("name", "S" + j); for (int k = 0; k < schemas.get(j).size(); k++) { for (String var : iovariations()) { Element relation = schema.addElement("relation") .addAttribute("name", WorkloadGeneratorUtils.relname(i, j, k) + var) .addAttribute("materialized", "true"); if ((Double) _params.get("coverage") == 1) { relation.addAttribute("noNulls", "true"); } String hasLocalData; if (Generator.peerHasLocalData(i, (Integer) _params.get("topology"), (Integer) _params.get("modlocal"), (Integer) _params.get("peers"), (Integer) _params.get("fanout"))) { hasLocalData = "true"; } else { hasLocalData = "false"; } relation.addAttribute("hasLocalData", hasLocalData); relation.addElement("dbinfo").addAttribute("schema", (String) _params.get("username")) .addAttribute("table", WorkloadGeneratorUtils.relname(i, j, k) + var); relation.addElement("field").addAttribute("name", "KID").addAttribute("type", "integer") .addAttribute("key", "true"); for (String att : schemas.get(j).get(k)) { if ((Boolean) _params.get("addValueAttr") && att.equals(Relation.valueAttrName)) { relation.addElement("field").addAttribute("name", att).addAttribute("type", "integer") .addAttribute("key", "true"); } else { relation.addElement("field").addAttribute("name", att).addAttribute("type", universalType(att, _params)); } } } } } for (int k = 0; k < mappings.size(); k++) { if (null == mappings.get(k)) { continue; } int i = (Integer) mappings.get(k).get(0); int j = (Integer) mappings.get(k).get(1); List<String> x = (List<String>) mappings.get(k).get(2); List<String> source = selectAtoms(i, "KID", x, "_", schemas, peers, (Boolean) _params.get("addValueAttr"), true); // _ means don't care List<String> target = selectAtoms(j, "KID", x, "-", schemas, peers, (Boolean) _params.get("addValueAttr"), false); // - means null Element mapping = catalog.addElement("mapping").addAttribute("name", "M" + k) .addAttribute("materialized", "true"); if (1 == (Integer) _params.get("bidir")) { mapping.addAttribute("bidirectional", "true"); } Element head = mapping.addElement("head"); for (String atom : target) { Element atomElem = head.addElement("atom"); if (1 == (Integer) _params.get("bidir")) { atomElem.addAttribute("del", "true"); } atomElem.addText(atom); } Element body = mapping.addElement("body"); for (String atom : source) { Element atomElem = body.addElement("atom"); if (1 == (Integer) _params.get("bidir")) { atomElem.addAttribute("del", "true"); } atomElem.addText(atom); } } Element mappingsElem = catalog.addElement("engine").addElement("mappings"); if (1 == (Integer) _params.get("tukwila")) { mappingsElem.addAttribute("type", "tukwila").addAttribute("host", "localhost").addAttribute("port", "7777"); } else { mappingsElem.addAttribute("type", "sql") .addAttribute("server", (String) _params.get("mappingsServer") + "/" // "jdbc:db2://localhost:50000/" + _params.get("dbalias")) .addAttribute("username", (String) _params.get("username")) .addAttribute("password", (String) _params.get("password")); } if (null != _params.get("updateAlias")) { catalog.addElement("updates") .addAttribute("server", "jdbc:db2://localhost:50000/" + _params.get("updateAlias")) .addAttribute("username", (String) _params.get("username")) .addAttribute("password", (String) _params.get("password")); } // Output some default (dummy) reconciliation store info Element store = catalog.addElement("store"); store.addElement("update").addAttribute("type", "bdb").addAttribute("hostname", "localhost") .addAttribute("port", "777"); store.addElement("state").addAttribute("type", "hash"); // Output trust conditions saying that everyone trusts everyone for (int i = 0; i < peers.size(); i++) { if (null == peers.get(i)) { continue; } int j = peers.get(i); Element trustConditions = catalog.addElement("trustConditions").addAttribute("peer", "P" + i) .addAttribute("schema", "S" + j); for (int i2 = 0; i2 < peers.size(); i2++) { if (null == peers.get(i2)) { continue; } int j2 = peers.get(i2); if (i != i2) { for (int k2 = 0; k2 < schemas.get(j2).size(); k2++) { trustConditions.addElement("trusts").addAttribute("pid", "P" + i2) .addAttribute("pidType", "STRING").addAttribute("pidType", "STRING") .addAttribute("priority", "5") .addAttribute("relation", WorkloadGeneratorUtils.relname(i2, j2, k2)); } } } } try { OutputFormat format = OutputFormat.createPrettyPrint(); XMLWriter xmlWriter = new XMLWriter(writer, format); xmlWriter.write(document); writer.flush(); writer.close(); } catch (IOException e) { throw new IllegalStateException("Problem writing schema file.", 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();/* ww w . ja 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 2 s . 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();/*from w ww . j ava 2s. 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(); }