List of usage examples for org.dom4j.io XMLWriter close
public void close() throws IOException
From source file:org.infoglue.cms.util.dom.DOMBuilder.java
License:Open Source License
/** * This method writes a document to file nicely. *//*from w ww . j av a2 s .c o m*/ public void writePretty(Document document, String fileName) throws IOException { OutputFormat format = OutputFormat.createPrettyPrint(); XMLWriter writer = new XMLWriter(new FileWriter(fileName), format); writer.write(document); writer.close(); }
From source file:org.infoglue.common.util.dom.DOMBuilder.java
License:Open Source License
/** * This method writes a document to file. *//*from ww w. j a v a 2 s .c o m*/ public void write(Document document, String fileName) throws Exception { OutputFormat format = OutputFormat.createCompactFormat(); format.setEncoding("UTF-8"); XMLWriter writer = new XMLWriter(new FileWriter(fileName), format); writer.write(document); writer.close(); /* FileHelper.writeToFile(new File(fileName + "2"), document.asXML(), false); FileHelper.writeUTF8ToFileSpecial(new File(fileName + "3"), document.asXML(), false); FileHelper.writeUTF8(new File(fileName + "4"), document.asXML(), false); FileHelper.writeUTF8ToFile(new File(fileName + "5"), document.asXML(), false); */ }
From source file:org.itracker.web.util.ImportExportUtilities.java
License:Open Source License
/** * export the issues to an XML and write it to the response. * @param issues// w w w.jav a 2s .c om * @param config * @param request * @param response * @return if <code>true</code> the export was sucessful. * @throws ServletException * @throws IOException */ public static boolean exportIssues(List<Issue> issues, SystemConfiguration config, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/xml; charset=UTF-8"); response.setHeader("Content-Disposition", "attachment; filename=\"issue_export.xml\""); XMLWriter writer = new XMLWriter(response.getOutputStream(), OutputFormat.createCompactFormat()); try { // TODO instead to have a string returned, it should directly serialize the // export to the response-writer. ImportExportUtilities.exportIssues(writer, issues, config); } catch (ImportExportException iee) { logger.error("Error exporting issue data. Message: " + iee.getMessage(), iee); return false; } finally { if (null != writer) { writer.flush(); writer.close(); } } return true; }
From source file:org.itracker.web.util.ImportExportUtilities.java
License:Open Source License
/** * Returns the appropriate XML block for a given model. * * @param abstractBean a model that extends AbstractEntity * @throws ImportExportException thrown if the given model can not be exported *//*w w w . jav a 2s . c o m*/ public static String exportModel(AbstractEntity abstractBean) throws ImportExportException { ByteArrayOutputStream os = new ByteArrayOutputStream(); try { XMLWriter writer = new XMLWriter(os); exportModel(writer, abstractBean); writer.close(); return (os.toString("utf-8")); } catch (Exception e) { logger.error("could not create xml string", e); throw new ImportExportException(e.getMessage(), ImportExportException.TYPE_UNKNOWN); } }
From source file:org.itracker.web.util.ImportExportUtilities.java
License:Open Source License
/** * Generates an XML block that encapsulates an issue for import or export. This * function will not generate the XML for other models needed for a complete import * or export.//from w w w. ja v a2 s . c om * * @param issue an Issue to generate the XML for * @return a String containing the XML for the issue */ public static String getIssueXML(Issue issue) { if (issue == null) { return ""; } ByteArrayOutputStream os = new ByteArrayOutputStream(); try { XMLWriter writer = new XMLWriter(os); getIssueXML(writer, issue); writer.close(); return (os.toString("utf-8")); } catch (Exception e) { logger.error("could not create xml string", e); return ""; } }
From source file:org.itracker.web.util.ImportExportUtilities.java
License:Open Source License
/** * Generates an XML block that encapsulates a project for import or export. This * function will not generate the XML for other models needed for a complete import * or export./*from w ww. j av a 2s .c o m*/ * * @param project a Project to generate the XML for * @return a String containing the XML for the project */ public static String getProjectXML(Project project) { if (project == null) { return ""; } ByteArrayOutputStream os = new ByteArrayOutputStream(); try { XMLWriter writer = new XMLWriter(os); getProjectXML(writer, project); writer.close(); return (os.toString("utf-8")); } catch (Exception e) { logger.error("could not create xml string", e); return ""; } }
From source file:org.itracker.web.util.ImportExportUtilities.java
License:Open Source License
/** * Generates an XML block that encapsulates a user for import or export. This * function will not generate the XML for other models needed for a complete import * or export.// w w w .j av a 2 s . c o m * * @param user a User to generate the XML for * @return a String containing the XML for the user */ public static String getUserXML(User user) { if (user == null) { return ""; } ByteArrayOutputStream os = new ByteArrayOutputStream(); try { XMLWriter writer = new XMLWriter(os); getUserXML(writer, user); writer.close(); return (os.toString("utf-8")); } catch (Exception e) { logger.error("could not create xml string", e); return ""; } }
From source file:org.itracker.web.util.ImportExportUtilities.java
License:Open Source License
/** * Generates an XML block that encapsulates the system configuration for import or export. * This function will not generate the XML for other models needed for a complete import * or export.//w w w . j ava 2s .com * * @param config a SystemConfiguration to generate the XML for * @return a String containing the XML for the configuration */ public static String getConfigurationXML(SystemConfiguration config) { if (config == null) { return ""; } ByteArrayOutputStream os = new ByteArrayOutputStream(); try { XMLWriter writer = new XMLWriter(os); getConfigurationXML(writer, config); writer.close(); return (os.toString("utf-8")); } catch (Exception e) { logger.error("could not create xml string", e); return ""; } }
From source file:org.jahia.utils.maven.plugin.osgi.ConvertToOSGiMojo.java
License:Open Source License
private void parsePom() throws DocumentException, IOException { SAXReader reader = new SAXReader(); File pom = new File(baseDir, "pom.xml"); Document pomDocument = reader.read(pom); Document bundleModuleDocument = reader .read(getClass().getClassLoader().getResourceAsStream("bundleModule.xml")); Element root = pomDocument.getRootElement(); // Set packaging Element packaging = root.element("packaging"); if (packaging == null) { root.addElement("packaging"); } else {/*from w w w . j a v a2 s . c o m*/ if (packaging.getTextTrim().toLowerCase().equals("war")) { packaging.setText("bundle"); } else { getLog().info("Non WAR packaging found : " + packaging.getTextTrim() + ", not modifying it to bundle, but you might want to double-check this."); } } // Copy template dependencies Element dependencies = root.element("dependencies"); if (dependencies == null) { dependencies = root.addElement("dependencies"); } List dependenciesTemplate = bundleModuleDocument.selectNodes("/project/*[local-name()='dependencies']/*"); for (Element dep : (Iterable<? extends Element>) dependenciesTemplate) { dependencies.add(dep.detach()); } // Generate plugin instructions Element plugins = (Element) pomDocument .selectSingleNode("/project/*[local-name()='build']/*[local-name()='plugins']"); if (plugins != null) { Element mavenWarPluginArtifactId = (Element) plugins .selectSingleNode("//*[local-name()='artifactId'][text()='maven-war-plugin']"); if (mavenWarPluginArtifactId != null) { Element previousPluginConfig = (Element) mavenWarPluginArtifactId.getParent().detach(); Element manifestEntries = previousPluginConfig.element("configuration").element("archive") .element("manifestEntries"); Element pluginTemplate = (Element) bundleModuleDocument.selectSingleNode( "/project/*[local-name()='build']/*[local-name()='plugins']/*[local-name()='plugin']"); if (pluginTemplate != null) { Element instructionsTemplate = (Element) pluginTemplate.element("configuration") .element("instructions").detach(); Element instructions = pluginTemplate.element("configuration").addElement("instructions"); generateBundlePlugin(manifestEntries, instructions, instructionsTemplate); if (!instructions.elements().isEmpty()) { plugins.add(pluginTemplate.detach()); } } } } // Export pom XMLWriter writer = new XMLWriter(new FileOutputStream(pom), OutputFormat.createPrettyPrint()); writer.write(pomDocument); writer.close(); }
From source file:org.jasig.portal.layout.dlm.RDBMDistributedLayoutStore.java
License:Apache License
private org.dom4j.Element getExportLayoutDom(IPerson person, IUserProfile profile) { if (!this.layoutExistsForUser(person)) { return null; }// ww w . j a va 2s .c o m org.dom4j.Document layoutDoc = null; try { final Document layoutDom = this._safeGetUserLayout(person, profile); person.setAttribute(Constants.PLF, layoutDom); layoutDoc = this.reader.get().read(layoutDom); } catch (final Throwable t) { final String msg = "Unable to obtain layout & profile for user '" + person.getUserName() + "', profileId " + profile.getProfileId(); throw new RuntimeException(msg, t); } if (logger.isDebugEnabled()) { // Write out this version of the layout to the log for dev purposes... final StringWriter str = new StringWriter(); final XMLWriter xml = new XMLWriter(str, new OutputFormat(" ", true)); try { xml.write(layoutDoc); xml.close(); } catch (final Throwable t) { throw new RuntimeException( "Failed to write the layout for user '" + person.getUserName() + "' to the DEBUG log", t); } logger.debug("Layout for user: {}\n{}", person.getUserName(), str.getBuffer().toString()); } /* * Attempt to detect a corrupted layout; return null in such cases */ if (isLayoutCorrupt(layoutDoc)) { logger.warn("Layout for user: {} is corrupt; layout structures will not be exported.", person.getUserName()); return null; } /* * Clean up the DOM for export. */ // (1) Add structure & theme attributes... final int structureStylesheetId = profile.getStructureStylesheetId(); this.addStylesheetUserPreferencesAttributes(person, profile, layoutDoc, structureStylesheetId, "structure"); final int themeStylesheetId = profile.getThemeStylesheetId(); this.addStylesheetUserPreferencesAttributes(person, profile, layoutDoc, themeStylesheetId, "theme"); // (2) Remove locale info... final Iterator<org.dom4j.Attribute> locale = (Iterator<org.dom4j.Attribute>) layoutDoc .selectNodes("//@locale").iterator(); while (locale.hasNext()) { final org.dom4j.Attribute loc = locale.next(); loc.getParent().remove(loc); } // (3) Scrub unnecessary channel information... for (final Iterator<org.dom4j.Element> orphanedChannels = (Iterator<org.dom4j.Element>) layoutDoc .selectNodes("//channel[@fname = '']").iterator(); orphanedChannels.hasNext();) { // These elements represent UP_LAYOUT_STRUCT rows where the // CHAN_ID field was not recognized by ChannelRegistryStore; // best thing to do is remove the elements... final org.dom4j.Element ch = orphanedChannels.next(); ch.getParent().remove(ch); } final List<String> channelAttributeWhitelist = Arrays.asList(new String[] { "fname", "unremovable", "hidden", "immutable", "ID", "dlm:plfID", "dlm:moveAllowed", "dlm:deleteAllowed" }); final Iterator<org.dom4j.Element> channels = (Iterator<org.dom4j.Element>) layoutDoc .selectNodes("//channel").iterator(); while (channels.hasNext()) { final org.dom4j.Element oldCh = channels.next(); final org.dom4j.Element parent = oldCh.getParent(); final org.dom4j.Element newCh = this.fac.createElement("channel"); for (final String aName : channelAttributeWhitelist) { final org.dom4j.Attribute a = (org.dom4j.Attribute) oldCh.selectSingleNode("@" + aName); if (a != null) { newCh.addAttribute(a.getQName(), a.getValue()); } } parent.elements().add(parent.elements().indexOf(oldCh), newCh); parent.remove(oldCh); } // (4) Convert internal DLM noderefs to external form (pathrefs)... for (final Iterator<org.dom4j.Attribute> origins = (Iterator<org.dom4j.Attribute>) layoutDoc .selectNodes("//@dlm:origin").iterator(); origins.hasNext();) { final org.dom4j.Attribute org = origins.next(); final Pathref dlmPathref = this.nodeReferenceFactory.getPathrefFromNoderef( (String) person.getAttribute(IPerson.USERNAME), org.getValue(), layoutDoc.getRootElement()); if (dlmPathref != null) { // Change the value only if we have a valid pathref... org.setValue(dlmPathref.toString()); } else { if (logger.isWarnEnabled()) { logger.warn("Layout element '{}' from user '{}' failed to match noderef '{}'", org.getUniquePath(), person.getAttribute(IPerson.USERNAME), org.getValue()); } } } for (final Iterator<org.dom4j.Attribute> it = (Iterator<org.dom4j.Attribute>) layoutDoc .selectNodes("//@dlm:target").iterator(); it.hasNext();) { final org.dom4j.Attribute target = it.next(); final Pathref dlmPathref = this.nodeReferenceFactory.getPathrefFromNoderef( (String) person.getAttribute(IPerson.USERNAME), target.getValue(), layoutDoc.getRootElement()); if (dlmPathref != null) { // Change the value only if we have a valid pathref... target.setValue(dlmPathref.toString()); } else { if (logger.isWarnEnabled()) { logger.warn("Layout element '{}' from user '{}' failed to match noderef '{}'", target.getUniquePath(), person.getAttribute(IPerson.USERNAME), target.getValue()); } } } for (final Iterator<org.dom4j.Attribute> names = (Iterator<org.dom4j.Attribute>) layoutDoc .selectNodes("//dlm:*/@name").iterator(); names.hasNext();) { final org.dom4j.Attribute n = names.next(); if (n.getValue() == null || n.getValue().trim().length() == 0) { // Outer <dlm:positionSet> elements don't seem to use the name // attribute, though their childern do. Just skip these so we // don't send a false WARNING. continue; } final Pathref dlmPathref = this.nodeReferenceFactory.getPathrefFromNoderef( (String) person.getAttribute(IPerson.USERNAME), n.getValue(), layoutDoc.getRootElement()); if (dlmPathref != null) { // Change the value only if we have a valid pathref... n.setValue(dlmPathref.toString()); // These *may* have fnames... if (dlmPathref.getPortletFname() != null) { n.getParent().addAttribute("fname", dlmPathref.getPortletFname()); } } else { if (logger.isWarnEnabled()) { logger.warn("Layout element '{}' from user '{}' failed to match noderef '{}'", n.getUniquePath(), person.getAttribute(IPerson.USERNAME), n.getValue()); } } } // Remove synthetic Ids, but from non-fragment owners only... if (!this.isFragmentOwner(person)) { /* * In the case of fragment owners, the original database Ids allow * us keep (not break) the associations that subscribers have with * nodes on the fragment layout. */ // (5) Remove dlm:plfID... for (final Iterator<org.dom4j.Attribute> plfid = (Iterator<org.dom4j.Attribute>) layoutDoc .selectNodes("//@dlm:plfID").iterator(); plfid.hasNext();) { final org.dom4j.Attribute plf = plfid.next(); plf.getParent().remove(plf); } // (6) Remove database Ids... for (final Iterator<org.dom4j.Attribute> ids = (Iterator<org.dom4j.Attribute>) layoutDoc .selectNodes("//@ID").iterator(); ids.hasNext();) { final org.dom4j.Attribute a = ids.next(); a.getParent().remove(a); } } return layoutDoc.getRootElement(); }