List of usage examples for org.dom4j.io OutputFormat createPrettyPrint
public static OutputFormat createPrettyPrint()
From source file:org.codehaus.mojo.hibernate2.MappingsAggregatorMojo.java
License:Apache License
public void execute() throws MojoExecutionException { try {//w w w .ja v a 2s .c om String version = null; if (getBasedir() == null) { throw new MojoExecutionException("Required configuration missing: basedir"); } File files[] = getIncludeFiles(); if (files == null || files.length <= 0) { return; } File f = new File(getOutputFile()); if (!f.exists()) { f.getParentFile().mkdirs(); f.createNewFile(); } OutputFormat format = OutputFormat.createPrettyPrint(); XMLWriter writer = new XMLWriter(new FileWriter(f), format); writer.setEntityResolver(new HibernateEntityResolver()); //writer.setResolveEntityRefs(false); Document finalDoc = DocumentHelper.createDocument(); Element rootHM = null; for (int i = 0; i < files.length; i++) { print("Parsing: " + files[i].getAbsolutePath()); SAXReader reader = new SAXReader(false); reader.setEntityResolver(new HibernateEntityResolver()); //reader.setIncludeExternalDTDDeclarations(false); //reader.setIncludeExternalDTDDeclarations(false); Document current = reader.read(files[i]); String currentVersion = getVersion(current); if (version == null) { version = currentVersion; finalDoc.setProcessingInstructions(current.processingInstructions()); finalDoc.setDocType(current.getDocType()); rootHM = finalDoc.addElement("hibernate-mapping"); } else if (!version.equals(currentVersion)) { //LOG.warn("Mapping in " + files[i].getName() + " is not of the same mapping version as " + files[0].getName() + " mapping, so merge is impossible. Skipping"); continue; } for (Iterator iter = current.selectSingleNode("hibernate-mapping").selectNodes("class") .iterator(); iter.hasNext(); rootHM.add((Element) ((Element) iter.next()).clone())) { } } print("Writing aggregate file: " + f.getAbsolutePath()); writer.write(finalDoc); writer.close(); } catch (Exception ex) { throw new MojoExecutionException("Error in executing MappingsAgrregatorBean", ex); } }
From source file:org.cpsolver.coursett.IdConvertor.java
License:Open Source License
/** * Save id conversion file./* w w w . j a v a 2s. co m*/ * @param file id file to save */ public void save(File file) { file.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(file); (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:org.cpsolver.coursett.TimetableXMLSaver.java
License:Open Source License
public void save(File outFile) throws Exception { if (outFile == null) outFile = new File(iOutputFolder, "solution.xml"); outFile.getParentFile().mkdirs();// ww w . j av a 2 s .c om sLogger.debug("Writting XML data to:" + outFile); Document document = DocumentHelper.createDocument(); document.addComment("University Course Timetabling"); if (iSaveCurrent && getAssignment().nrAssignedVariables() != 0) { StringBuffer comments = new StringBuffer("Solution Info:\n"); Map<String, String> solutionInfo = (getSolution() == null ? getModel().getExtendedInfo(getAssignment()) : getSolution().getExtendedInfo()); for (String key : new TreeSet<String>(solutionInfo.keySet())) { String value = solutionInfo.get(key); comments.append(" " + key + ": " + value + "\n"); } document.addComment(comments.toString()); } Element root = document.addElement("timetable"); doSave(root); if (iShowNames) { Progress.getInstance(getModel()).save(root); try { getSolver().getClass().getMethod("save", new Class[] { Element.class }).invoke(getSolver(), new Object[] { root }); } catch (Exception e) { } } FileOutputStream fos = null; try { fos = new FileOutputStream(outFile); (new XMLWriter(fos, OutputFormat.createPrettyPrint())).write(document); fos.flush(); fos.close(); fos = null; } finally { try { if (fos != null) fos.close(); } catch (IOException e) { } } if (iConvertIds) iIdConvertor.save(); }
From source file:org.cpsolver.ifs.example.tt.TimetableModel.java
License:Open Source License
public void saveAsXML(DataProperties cfg, boolean gen, Solution<Activity, Location> solution, Assignment<Activity, Location> assignment, File outFile) throws IOException { outFile.getParentFile().mkdirs();// w w w .j a v a2s. 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 (assignment == null && solution != null) assignment = solution.getAssignment(); if (assignment == null) assignment = new DefaultSingleAssignment<Activity, Location>(); if (!assignedVariables(assignment).isEmpty()) { StringBuffer comments = new StringBuffer("Solution Info:\n"); Map<String, String> solutionInfo = (solution == null ? getInfo(assignment) : solution.getInfo()); for (String key : new TreeSet<String>(solutionInfo.keySet())) { String value = solutionInfo.get(key); comments.append(" " + key + ": " + value + "\n"); } document.addComment(comments.toString()); } Element root = document.addElement("Timetable"); if (gen) { Element generator = root.addElement("Generator"); generator.addAttribute("version", "2.0"); generator.addElement("DaysPerWeek").setText(String.valueOf(iNrDays)); generator.addElement("SlotsPerDay").setText(String.valueOf(iNrHours)); generator.addElement("NrRooms").setText(cfg.getProperty("Generator.NrRooms", "20")); generator.addElement("NrInstructors").setText(cfg.getProperty("Generator.NrInstructors", "20")); generator.addElement("NrClasses").setText(cfg.getProperty("Generator.NrClasses", "20")); generator.addElement("FillFactor").setText(cfg.getProperty("Generator.FillFactor", "0.8")); generator.addElement("ActivityLengthMax").setText(cfg.getProperty("Generator.ActivityLengthMax", "5")); generator.addElement("NrGroupsOfRooms").setText(cfg.getProperty("Generator.NrGroupsOfRooms", "20")); generator.addElement("NrRoomsInGroupMin").setText(cfg.getProperty("Generator.NrRoomsInGroupMin", "1")); generator.addElement("NrRoomsInGroupMax").setText(cfg.getProperty("Generator.NrRoomsInGroupMax", "10")); generator.addElement("NrRoomInGroupMin").setText(cfg.getProperty("Generator.NrRoomInGroupMin", "1")); generator.addElement("HardFreeResource").setText(cfg.getProperty("Generator.HardFreeResource", "0.05")); generator.addElement("SoftFreeResource").setText(cfg.getProperty("Generator.SoftFreeResource", "0.3")); generator.addElement("SoftUsedResource").setText(cfg.getProperty("Generator.SoftUsedResource", "0.05")); generator.addElement("SoftUsedActivity").setText(cfg.getProperty("Generator.SoftUsedActivity", "0.05")); generator.addElement("SoftFreeActivity").setText(cfg.getProperty("Generator.SoftFreeActivity", "0.3")); generator.addElement("HardFreeActivity").setText(cfg.getProperty("Generator.HardFreeActivity", "0.05")); generator.addElement("NrDependencies").setText(cfg.getProperty("Generator.NrDependencies", "50")); } ArrayList<Resource> rooms = new ArrayList<Resource>(); ArrayList<Resource> classes = new ArrayList<Resource>(); ArrayList<Resource> instructors = new ArrayList<Resource>(); ArrayList<Resource> specials = new ArrayList<Resource>(); ArrayList<Dependence> dependencies = new ArrayList<Dependence>(); for (Constraint<Activity, Location> c : constraints()) { if (c instanceof Resource) { Resource r = (Resource) c; switch (r.getType()) { case Resource.TYPE_ROOM: rooms.add(r); break; case Resource.TYPE_CLASS: classes.add(r); break; case Resource.TYPE_INSTRUCTOR: instructors.add(r); break; default: specials.add(r); } } else if (c instanceof Dependence) { dependencies.add((Dependence) c); } } Element problem = root.addElement("Problem"); problem.addAttribute("version", "2.0"); Element problemGen = problem.addElement("General"); problemGen.addElement("DaysPerWeek").setText(String.valueOf(iNrDays)); problemGen.addElement("SlotsPerDay").setText(String.valueOf(iNrHours)); Element resourceGen = problemGen.addElement("Resources"); resourceGen.addElement("Classrooms").setText(String.valueOf(rooms.size())); resourceGen.addElement("Teachers").setText(String.valueOf(instructors.size())); resourceGen.addElement("Classes").setText(String.valueOf(classes.size())); resourceGen.addElement("Special").setText(String.valueOf(specials.size())); problemGen.addElement("Activities").setText(String.valueOf(variables().size())); problemGen.addElement("Dependences").setText(String.valueOf(dependencies.size())); Element resources = problem.addElement("Resources"); Element resEl = resources.addElement("Classrooms"); for (Resource r : rooms) { Element el = resEl.addElement("Resource"); el.addAttribute("id", r.getResourceId()); el.addElement("Name").setText(r.getName()); Element pref = el.addElement("TimePreferences"); for (Integer slot : new TreeSet<Integer>(r.getDiscouragedSlots())) pref.addElement("Soft").setText(slot.toString()); for (Integer slot : new TreeSet<Integer>(r.getProhibitedSlots())) pref.addElement("Hard").setText(slot.toString()); } resEl = resources.addElement("Teachers"); for (Resource r : instructors) { Element el = resEl.addElement("Resource"); el.addAttribute("id", r.getResourceId()); el.addElement("Name").setText(r.getName()); Element pref = el.addElement("TimePreferences"); for (Integer slot : new TreeSet<Integer>(r.getDiscouragedSlots())) pref.addElement("Soft").setText(slot.toString()); for (Integer slot : new TreeSet<Integer>(r.getProhibitedSlots())) pref.addElement("Hard").setText(slot.toString()); } resEl = resources.addElement("Classes"); for (Resource r : classes) { Element el = resEl.addElement("Resource"); el.addAttribute("id", r.getResourceId()); el.addElement("Name").setText(r.getName()); Element pref = el.addElement("TimePreferences"); for (Integer slot : new TreeSet<Integer>(r.getDiscouragedSlots())) pref.addElement("Soft").setText(slot.toString()); for (Integer slot : new TreeSet<Integer>(r.getProhibitedSlots())) pref.addElement("Hard").setText(slot.toString()); } resEl = resources.addElement("Special"); for (Resource r : specials) { Element el = resEl.addElement("Resource"); el.addAttribute("id", r.getResourceId()); el.addElement("Name").setText(r.getName()); Element pref = el.addElement("TimePreferences"); for (Integer slot : new TreeSet<Integer>(r.getDiscouragedSlots())) pref.addElement("Soft").setText(slot.toString()); for (Integer slot : new TreeSet<Integer>(r.getProhibitedSlots())) pref.addElement("Hard").setText(slot.toString()); } boolean hasSolution = false; Element actEl = problem.addElement("Activities"); for (Activity a : variables()) { Element el = actEl.addElement("Activity"); el.addAttribute("id", a.getActivityId()); el.addElement("Name").setText(a.getName()); el.addElement("Length").setText(String.valueOf(a.getLength())); if (assignment.getValue(a) != null) hasSolution = true; Element pref = el.addElement("TimePreferences"); for (Integer slot : new TreeSet<Integer>(a.getDiscouragedSlots())) pref.addElement("Soft").setText(slot.toString()); for (Integer slot : new TreeSet<Integer>(a.getProhibitedSlots())) pref.addElement("Hard").setText(slot.toString()); Element reqRes = el.addElement("RequiredResources"); for (List<Resource> gr : a.getResourceGroups()) { if (gr.size() == 1) { reqRes.addElement("Resource").setText(gr.get(0).getResourceId()); } else { Element grEl = reqRes.addElement("Group").addAttribute("conjunctive", "no"); for (Resource r : gr) grEl.addElement("Resource").setText(r.getResourceId()); } } } Element depEl = problem.addElement("Dependences"); for (Dependence d : dependencies) { Element el = depEl.addElement("Dependence"); el.addAttribute("id", d.getResourceId()); el.addElement("FirstActivity").setText((d.first()).getActivityId()); el.addElement("SecondActivity").setText((d.second()).getActivityId()); switch (d.getType()) { case Dependence.TYPE_AFTER: el.addElement("Operator").setText("After"); break; case Dependence.TYPE_BEFORE: el.addElement("Operator").setText("Before"); break; case Dependence.TYPE_CLOSELY_BEFORE: el.addElement("Operator").setText("Closely before"); break; case Dependence.TYPE_CLOSELY_AFTER: el.addElement("Operator").setText("Closely after"); break; case Dependence.TYPE_CONCURRENCY: el.addElement("Operator").setText("Concurrently"); break; default: el.addElement("Operator").setText("Unknown"); } } if (hasSolution) { Element solutionEl = root.addElement("Solution"); solutionEl.addAttribute("version", "2.0"); for (Activity a : variables()) { Element el = solutionEl.addElement("Activity"); el.addAttribute("id", a.getActivityId()); Location location = assignment.getValue(a); if (location != null) { el.addElement("StartTime").setText(String.valueOf(location.getSlot())); Element res = el.addElement("UsedResources"); for (int i = 0; i < location.getResources().length; i++) res.addElement("Resource").setText(location.getResources()[i].getResourceId()); } } } FileOutputStream fos = new FileOutputStream(outFile); (new XMLWriter(fos, OutputFormat.createPrettyPrint())).write(document); fos.flush(); fos.close(); }
From source file:org.cpsolver.studentsct.StudentRequestXml.java
License:Open Source License
public static void main(String[] args) { try {//w w w.j ava 2 s. c o m ToolBox.configureLogging(); StudentSectioningModel model = new StudentSectioningModel(new DataProperties()); Assignment<Request, Enrollment> assignment = new DefaultSingleAssignment<Request, Enrollment>(); StudentSectioningXMLLoader xmlLoad = new StudentSectioningXMLLoader(model, assignment); xmlLoad.setInputFile(new File(args[0])); xmlLoad.load(); Document document = exportModel(assignment, 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:org.cpsolver.studentsct.StudentSectioningXMLSaver.java
License:Open Source License
/** * Save an XML file/*from ww w. j av a 2 s .c o m*/ * * @param outFile * output file * @throws Exception thrown when the save fails */ public void save(File outFile) throws Exception { if (outFile == null) { outFile = new File(iOutputFolder, "solution.xml"); } else if (outFile.getParentFile() != null) { outFile.getParentFile().mkdirs(); } sLogger.debug("Writting XML data to:" + outFile); Document document = DocumentHelper.createDocument(); document.addComment("Student Sectioning"); populate(document); 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:org.craftercms.core.util.XmlUtils.java
License:Open Source License
/** * Returns the given document as a XML string in a "pretty" format. * * @param document//from w w w. j a va 2s .c o m * @return the document as an XML string */ public static String documentToPrettyString(Document document) { StringWriter stringWriter = new StringWriter(); OutputFormat prettyPrintFormat = OutputFormat.createPrettyPrint(); XMLWriter xmlWriter = new XMLWriter(stringWriter, prettyPrintFormat); try { xmlWriter.write(document); } catch (IOException e) { // Ignore, shouldn't happen. } return stringWriter.toString(); }
From source file:org.danann.cernunnos.xml.WriteDocumentTask.java
License:Apache License
public void perform(TaskRequest req, TaskResponse res) { File f = new File((String) file.evaluate(req, res)); if (f.getParentFile() != null) { // Make sure the necessary directories are in place... f.getParentFile().mkdirs();//from w ww . ja v a2s . co m } try { XMLWriter writer = new XMLWriter(new FileOutputStream(f), OutputFormat.createPrettyPrint()); writer.write((Node) node.evaluate(req, res)); } catch (Throwable t) { String msg = "Unable to write the specified file: " + f.getPath(); throw new RuntimeException(msg, t); } }
From source file:org.dentaku.gentaku.tools.cgen.plugin.GenGenPlugin.java
License:Apache License
private void prettyPrint(Document document, Writer writer) throws IOException { OutputFormat format = OutputFormat.createPrettyPrint(); format.setEncoding(encoding);// w ww. j a v a 2s . c o m format.setSuppressDeclaration(false); format.setExpandEmptyElements(false); XMLWriter xmlWriter = new XMLWriter(writer, format); xmlWriter.write(document); xmlWriter.flush(); }
From source file:org.dentaku.gentaku.tools.cgen.visitor.JellyTemplateGeneratingVisitor.java
License:Apache License
public void handleElement(Element element) throws VisitorException { if (element.getParent().getName().equals("schema")) { QName rootName = DocumentFactory.getInstance().createQName("jelly", "j", "jelly:core"); Branch parent = DocumentHelper.createDocument().addElement(rootName).addNamespace("x", "jelly:xml"); OutputFormat format = OutputFormat.createPrettyPrint(); format.setEncoding(getEncoding()); format.setSuppressDeclaration(false); format.setExpandEmptyElements(false); pushParent(parent.addElement(element.getName())); for (Iterator it = element.elementIterator(); it.hasNext();) { visit((Element) it.next()); }/*from ww w .ja va 2s . c o m*/ popParent(); try { String filename = element.getName() + ".jelly"; Writer out = new FileWriter(new File(getRootDir(), filename)); final XMLWriter xmlWriter = new XMLWriter(out, format); xmlWriter.setEscapeText(false); xmlWriter.write(parent); xmlWriter.flush(); xmlWriter.close(); } catch (Exception e) { throw new VisitorException("Exception occurred when running Jelly", e); } topLevelElements.put(element.getName(), element); } else { String refName = element.attributeValue("ref"); if (refName != null) { Branch parent = getCurrentParent(); // create an include QName qName = DocumentFactory.getInstance().createQName("import", "j", "jelly:core"); parent.addElement(qName).addAttribute("uri", refName + ".jelly").addAttribute("inherit", "true"); } } }