private final void roundTrip(boolean expand, boolean validating, String encoding, String expect) { String docloc = this.getClass().getPackage().getName().replaceAll("\\.", "/") + "/TestIssue008.xml"; URL docurl = ClassLoader.getSystemResource(docloc); if (docurl == null) { throw new IllegalStateException("Unable to get resource " + docloc); } SAXBuilder builder = new SAXBuilder(validating); // builder.setValidation(validating); builder.setExpandEntities(expand); Document doc = null; try { doc = builder.build(docurl); } catch (JDOMException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } if (doc == null) { fail("Unable to parse document, see output."); } Format fmt = Format.getCompactFormat(); if (encoding != null) { fmt.setEncoding(encoding); } XMLOutputter xout = new XMLOutputter(fmt); String actual = xout.outputString(doc.getRootElement()); assertEquals(expect, actual); }
protected String buildJnlpResponse(JnlpTemplate launcher) throws ServletErrorException { launcher.rootElt.setAttribute( JNLP_TAG_ATT_CODEBASE, ServletUtil.getFirstParameter(launcher.parameterMap.get(PARAM_CODEBASE))); launcher.rootElt.removeAttribute( JNLP_TAG_ATT_HREF); // this tag has not to be used inside dynamic JNLP handleRequestPropertyParameter(launcher); handleRequestArgumentParameter(launcher); filterRequestParameterMarker(launcher); String outputStr = null; try { Format format = Format.getPrettyFormat(); // Converts native encodings to ASCII with escaped Unicode like (ô è é...), necessary for jnlp format.setEncoding("US-ASCII"); outputStr = new XMLOutputter(format).outputString(launcher.rootElt); } catch (Exception e) { throw new ServletErrorException( HttpServletResponse.SC_NOT_MODIFIED, "Can't build Jnlp launcher ", e); } return outputStr; }
void prettyPrint(Document d) { Format f = Format.getPrettyFormat(); f.setOmitDeclaration(false); XMLOutputter out = new XMLOutputter(f); System.out.println(out.outputString(d)); }
protected Format getFormat(FormatSetup setup, Format input) { if (setup == null) { input.setLineSeparator("\n"); return input; } input.setLineSeparator("\n"); setup.setup(input); return input; }
/** * Writes to an Writer the XML representation for the given WireFeed. * * <p>If the feed encoding is not NULL, it will be used in the XML prolog encoding attribute. It * is the responsibility of the developer to ensure the Writer instance is using the same charset * encoding. * * <p>NOTE: This method delages to the 'Document WireFeedOutput#outputJDom(WireFeed)'. * * <p> * * @param feed Abstract feed to create XML representation from. The type of the WireFeed must * match the type given to the FeedOuptut constructor. * @param writer Writer to write the XML representation for the given WireFeed. * @param prettyPrint pretty-print XML (true) oder collapsed * @throws IllegalArgumentException thrown if the feed type of the WireFeedOutput and WireFeed * don't match. * @throws IOException thrown if there was some problem writing to the Writer. * @throws FeedException thrown if the XML representation for the feed could not be created. */ public void output(final WireFeed feed, final Writer writer, final boolean prettyPrint) throws IllegalArgumentException, IOException, FeedException { final Document doc = outputJDom(feed, false); final String encoding = feed.getEncoding(); Format format; if (prettyPrint) { format = Format.getPrettyFormat(); } else { format = Format.getCompactFormat(); } if (encoding != null) { format.setEncoding(encoding); } final XMLOutputter outputter = new XMLOutputter(format); outputter.output(doc, writer); }
public void run(File inputDirectory, File outputDirectory) { for (File file : inputDirectory.listFiles()) { if (file.isFile()) { System.out.println("Transforming file " + file.getName()); log(LogLevel.DEBUG, "Transforming file " + file.getName()); Document document = null; try (InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream(file), "UTF8")) { document = saxBuilder.build(inputStreamReader); } catch (JDOMException | IOException e) { log(LogLevel.ERROR, "Can't read xml from file " + file.getAbsolutePath(), e); } if (document != null) for (AbstractTransformer transformer : transformers) transformer.transform(document); File outputFile = new File(outputDirectory, file.getName()); try { outputFile.getParentFile().mkdirs(); outputFile.createNewFile(); } catch (IOException e) { log(LogLevel.ERROR, "Can't create xml file " + file.getAbsolutePath(), e); } try (OutputStreamWriter outputStreamWriter = new OutputStreamWriter(new FileOutputStream(outputFile), "UTF8")) { XMLOutputter xmlOutput = new XMLOutputter(Format.getPrettyFormat()); xmlOutput.output(document, outputStreamWriter); } catch (IOException e) { log(LogLevel.ERROR, "Can't write xml to file " + file.getAbsolutePath(), e); } } } }
public String formatAsXHTML(String xhtml) throws IOException, JDOMException { DocType doctype = new DocType( "html", "-//W3C//DTD XHTML 1.1//EN", "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"); Namespace namespace = Namespace.getNamespace("http://www.w3.org/1999/xhtml"); org.jdom2.Document document = XHTMLUtils.parseXHTMLDocument(xhtml); org.jdom2.Element root = document.getRootElement(); root.setNamespace(namespace); root.addNamespaceDeclaration(namespace); IteratorIterable<org.jdom2.Element> elements = root.getDescendants(Filters.element()); for (org.jdom2.Element element : elements) { if (element.getNamespace() == null) { element.setNamespace(Constants.NAMESPACE_XHTML); } } document.setDocType(doctype); XMLOutputter outputter = new XMLOutputter(); Format xmlFormat = Format.getPrettyFormat(); outputter.setFormat(xmlFormat); outputter.setXMLOutputProcessor(new XHTMLOutputProcessor()); String result = outputter.outputString(document); return result; }
@Override public void writeRecommendations(Recommendations recommendations) { List<Recommendation> topNrecommendations = new ArrayList<>(recommendations.getRecommendations()); if (getNumberOfRecommendations() > 0) { Collections.sort(topNrecommendations); topNrecommendations = topNrecommendations.subList( 0, Math.min(topNrecommendations.size(), getNumberOfRecommendations())); } Recommendations recommendationsWithNewRanking = RecommendationsFactory.copyRecommendationsWithNewRanking( recommendations, topNrecommendations); Element recommendationsElement = RecommendationsToXML.getRecommendationsElement(recommendationsWithNewRanking); Document doc = new Document(recommendationsElement); XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat().setEncoding("ISO-8859-1")); try { outputter.output(doc, System.out); } catch (IOException ex) { ERROR_CODES.CANNOT_WRITE_RECOMMENDATIONS.exit(ex); } }
private void setData() { try { Document doc = builder.build(prefFile); Element rootNode = doc.getRootElement(); Element RWDir = new Element("RWDir"); rootNode.getChild("firstLoad").setText("no"); RWDir.setText(RWDIRECTORY.getAbsolutePath()); rootNode.addContent(RWDir); XMLOutputter xmlOutput = new XMLOutputter(); FileWriter fw = new FileWriter(prefFile); xmlOutput.setFormat(Format.getPrettyFormat()); xmlOutput.output(doc, fw); fw.close(); } catch (IOException io) { io.printStackTrace(); } catch (JDOMException e) { e.printStackTrace(); } }
public void writeConfigXML(TableConfig tc, String tableConfigurerClass, java.util.Formatter sf) throws IOException { this.tc = tc; this.tableConfigurerClass = tableConfigurerClass; XMLOutputter fmt = new XMLOutputter(Format.getPrettyFormat()); sf.format("%s", fmt.outputString(makeDocument())); }
/** * Creates a String with the XML representation for the given WireFeed. * * <p>If the feed encoding is not NULL, it will be used in the XML prolog encoding attribute. It * is the responsibility of the developer to ensure that if the String is written to a character * stream the stream charset is the same as the feed encoding property. * * <p>NOTE: This method delages to the 'Document WireFeedOutput#outputJDom(WireFeed)'. * * <p> * * @param feed Abstract feed to create XML representation from. The type of the WireFeed must * match the type given to the FeedOuptut constructor. * @param prettyPrint pretty-print XML (true) oder collapsed * @return a String with the XML representation for the given WireFeed. * @throws IllegalArgumentException thrown if the feed type of the WireFeedOutput and WireFeed * don't match. * @throws FeedException thrown if the XML representation for the feed could not be created. */ public String outputString( final WireFeed feed, final boolean prettyPrint, final boolean ignoreOptionalErrors) throws IllegalArgumentException, FeedException { final Document doc = outputJDom(feed, ignoreOptionalErrors); final String encoding = feed.getEncoding(); Format format; if (prettyPrint) { format = Format.getPrettyFormat(); } else { format = Format.getCompactFormat(); } if (encoding != null) { format.setEncoding(encoding); } final XMLOutputter outputter = new XMLOutputter(format); return outputter.outputString(doc); }
protected void saveSettings(final String xmlFilename) throws IOException { final Element root = new Element("Settings"); root.addContent(viewer.stateToXml()); root.addContent(setupAssignments.toXml()); root.addContent(manualTransformation.toXml()); root.addContent(bookmarks.toXml()); final Document doc = new Document(root); final XMLOutputter xout = new XMLOutputter(Format.getPrettyFormat()); xout.output(doc, new FileWriter(xmlFilename)); }
public int writeAs(String str) { try { XMLOutputter sortie = new XMLOutputter(Format.getPrettyFormat()); sortie.output(document, new FileOutputStream(str)); } catch (java.io.IOException e) { e.printStackTrace(); return 0; } return 1; }
static { fraw.setLineSeparator("\n"); fcompact.setLineSeparator("\n"); fpretty.setLineSeparator("\n"); ftso.setLineSeparator("\n"); ftso.setSpecifiedAttributesOnly(true); ftfw.setLineSeparator("\n"); ftfw.setTextMode(TextMode.TRIM_FULL_WHITE); }
private String toString(Element emt) { UnitTestUtil.normalizeAttributes(emt); XMLOutputter out = new XMLOutputter(Format.getPrettyFormat()); CharArrayWriter caw = new CharArrayWriter(); try { out.output(emt, caw); } catch (IOException e) { e.printStackTrace(); return null; } return caw.toString(); }
public void write() { Document document = new Document(crearEstructuraXML()); try { XMLOutputter out = new XMLOutputter(Format.getPrettyFormat()); out.output(document, getArchivo()); getArchivo().flush(); close(); } catch (Exception e) { FacesMessages mensaje = (FacesMessages) Component.getInstance(FacesMessages.class); mensaje.add("Se produjo un error técnico :("); } }
@Override public String toString() { final Document document = new Document(root); final XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat()); final StringWriter writer = new StringWriter(); try { outputter.output(document, writer); } catch (final IOException e) { e.printStackTrace(); } return writer.toString(); }
/** * The following method will run the output data through each of the three base formatters, raw, * compact, and pretty. It will also run each of those formatters as the outputString(content), * output(content, OutputStream) and output(content, Writer). * * <p>The expectation is that the results of the three output forms (String, OutputStream, and * Writer) will be identical, and that it will match the expected value for the appropriate * formatter. * * @param content The content to output * @param methodprefix What the methods are called * @param clazz The class used as the parameter for the methods. * @param setup A callback mechanism to modify the formatters * @param raw What we expect the content to look like with the RAW format * @param compact What we expect the content to look like with the COMPACT format * @param pretty What we expect the content to look like with the PRETTY format * @param trimfw What we expect the content to look like with the TRIM_FULL_WHITE format */ protected void checkOutput( Object content, String methodprefix, Class<?> clazz, FormatSetup setup, String raw, String compact, String pretty, String tso, String trimfw) { Method meth = getMyMethod(methodprefix + "String", Format.class, clazz); if (meth == null) { return; } String[] descn = new String[] {"Raw", "Compact", "Pretty", "PrettySpecifiedOnly", "TrimFullWhite"}; Format ftrimfw = Format.getPrettyFormat(); ftrimfw.setTextMode(TextMode.TRIM_FULL_WHITE); Format fattspec = Format.getPrettyFormat(); fattspec.setSpecifiedAttributesOnly(true); Format[] formats = new Format[] { getFormat(setup, Format.getRawFormat()), getFormat(setup, Format.getCompactFormat()), getFormat(setup, Format.getPrettyFormat()), getFormat(setup, fattspec), getFormat(setup, ftrimfw) }; String[] result = new String[] {raw, compact, pretty, tso, trimfw}; for (int i = 0; i < 5; i++) { String mstring; try { mstring = (String) meth.invoke(this, formats[i], content); } catch (Exception e) { e.printStackTrace(); throw new IllegalStateException(e); } String msg = "outputString Format " + descn[i]; assertEquals(msg, expect(result[i]), mstring); } }
private static void scrieInFisierXML(File fisier, LinkedHashMap<String, Produs> toateProdusele) { Document doc = new Document(); Element theRoot = new Element("toate_produsele"); doc.setRootElement(theRoot); int size = toateProdusele.size(); theRoot.setAttribute("nr_produse", Integer.toString(size)); Set<String> Keys = toateProdusele.keySet(); for (String i : Keys) { Element produs = new Element("produs"); Element produs_id = new Element("produs_id"); produs_id.addContent(new Text(Integer.toString(toateProdusele.get(i).getId()))); Element nume = new Element("nume_produs"); nume.addContent(new Text(toateProdusele.get(i).getNume())); Element pret = new Element("pret_produs"); pret.addContent(new Text(Double.toString(toateProdusele.get(i).getPret()))); Element cantiate = new Element("cantitate_produs"); cantiate.addContent(new Text(Integer.toString(toateProdusele.get(i).getnrBucatiInStoc()))); Element id_categorie = new Element("categorie_id"); id_categorie.addContent(new Text(Integer.toString(toateProdusele.get(i).getIdCategorie()))); Element link_img = new Element("link_img"); link_img.addContent(new Text(toateProdusele.get(i).getLinkImg())); produs.addContent(produs_id); produs.addContent(nume); produs.addContent(pret); produs.addContent(cantiate); produs.addContent(id_categorie); produs.addContent(link_img); theRoot.addContent(produs); System.out.println("S-a adaugat elem \t" + i); } XMLOutputter xmlOutput = new XMLOutputter(Format.getPrettyFormat()); try { xmlOutput.output(doc, new FileOutputStream(fisier)); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
private String toString(Document doc) { UnitTestUtil.normalizeAttributes(doc.getRootElement()); normalizeDTD(doc.getDocType()); XMLOutputter out = new XMLOutputter(Format.getPrettyFormat()); CharArrayWriter caw = new CharArrayWriter(); try { out.output(doc, caw); } catch (IOException e) { e.printStackTrace(); return null; } return caw.toString(); }
private static void saveChannel(Channel channel, OutputStream out) throws Exception { Element root = new Element("channel"); root.setAttribute("version", "1.0"); root.setAttribute("type", channel.getClass().getName()); Element elSettings = new Element("settings"); SimpleBeanToXML.objectToXml(elSettings, channel); root.addContent(elSettings); Document doc = new Document(); doc.setRootElement(root); XMLOutputter xout = new XMLOutputter(Format.getPrettyFormat()); xout.output(doc, out); }
public void saveCategories() { System.out.println("XML Writer started..."); result = new ConnectVenueCategories().draw4(); System.out.println("Number of items: " + result.getResult().length); int counter = 0; Element root = new Element("Root"); Document doc = new Document(root); for (Category c : result.getResult()) { System.out.print(c.getName()); System.out.println("\t\t" + c.getId()); Element e1 = new Element("mainCategory").setText(c.getName()); e1.setAttribute("ID", c.getId()); System.out.println(e1.toString()); root.addContent(e1); for (Category subc : c.getCategories()) { System.out.print(subc.getName()); System.out.println("\t\t" + subc.getId()); Element e2 = new Element("subCategory").setText(subc.getName()); e2.setAttribute("ID", subc.getId()); e1.addContent(e2); for (Category subsubc : subc.getCategories()) { System.out.print(subsubc.getName()); System.out.println("\t\t\t" + subsubc.getId()); Element e3 = new Element("subSubCategory").setText(subsubc.getName()); e3.setAttribute("ID", subsubc.getId()); e2.addContent(e3); } } } System.out.println(counter); XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat()); try { FileOutputStream out = new FileOutputStream("Categories.xml"); outputter.output(doc, out); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
public static void enregistre(Document document, String fichierpath) { try { // vérifie si document n'est pas nul if (document == null) { document = new Document(); } // On utilise ici un affichage classique avec getPrettyFormat() XMLOutputter sortie = new XMLOutputter(Format.getPrettyFormat()); // Remarquez qu'il suffit simplement de créer une instance de FileOutputStream // avec en argument le nom du fichier pour effectuer la sérialisation. sortie.output(document, new FileOutputStream(fichierpath)); // new File(fichier).createNewFile(); } catch (java.io.IOException e) { } }
/** * Bibles like TurNTB contain merged (linked) verses which are duplicated when chapters are * displayed- see JS-224. This tests the deduplication code in AbstractPassageBook. * * @throws Exception */ @Test public void testLinkedVersesNotDuplicated() throws Exception { Book turNTB = Books.installed().getBook("TurNTB"); if (turNTB != null) { // Eph 2:4,5 are merged/linked in TurNTB Key eph245 = VerseRangeFactory.fromString( Versifications.instance().getVersification("KJV"), "Eph 2:4-5"); BookData bookData = new BookData(turNTB, eph245); final Element osisFragment = bookData.getOsisFragment(); final XMLOutputter xmlOutputter = new XMLOutputter(Format.getPrettyFormat()); String xml = xmlOutputter.outputString(osisFragment); Assert.assertTrue("Probable duplicate text", xml.length() < 300); } }
/** * This will handle the detail of conversion from a Java <code>Properties</code> object to an XML * do*****ent. * * @param props <code>Properties</code> object to use as input. * @param xmlFilename file to output XML to. * @throws <code>IOException</code> - when errors occur. */ private void convertToXML(Properties props, String xmlFilename) throws IOException { // Create a new JDOM Document with a root element "properties" Element root = new Element("properties"); Document doc = new Document(root); // Get the property names Enumeration propertyNames = props.propertyNames(); while (propertyNames.hasMoreElements()) { String propertyName = (String) propertyNames.nextElement(); String propertyValue = props.getProperty(propertyName); createXMLRepresentation(root, propertyName, propertyValue); } // Output document to supplied filename XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat()); FileOutputStream output = new FileOutputStream(xmlFilename); outputter.output(doc, output); }
/** * Books like Josephus have hierarchical chapters. Only the current chapter should be returned, * not child chapters. * * @throws Exception */ @Test public void testHierarchicalBook() throws Exception { Book josephus = Books.installed().getBook("Josephus"); String section1Text = "THOSE who undertake to write histories"; if (josephus != null) { // navigate down to the Preface Key theAntiquitiesOfTheJewsKey = josephus.getGlobalKeyList().get(1); Key prefaceKey = theAntiquitiesOfTheJewsKey.get(0); String prefaceText = josephus.getRawText(prefaceKey); Assert.assertFalse("Child keys returned in raw text", prefaceText.contains(section1Text)); // Now attempt to parse a key but get the problem is that all child text is returned too BookData bookData = new BookData(josephus, prefaceKey); final Element osisFragment = bookData.getOsisFragment(); final XMLOutputter xmlOutputter = new XMLOutputter(Format.getPrettyFormat()); String prefaceXml = xmlOutputter.outputString(osisFragment); Assert.assertFalse("Child keys returned in xml", prefaceXml.contains(section1Text)); } }
private void checkSave() { if (jt.getTrabajo().isDirty()) { int result = JOptionPane.showConfirmDialog( null, "Desea guardar los cambios?", "Guardar los cambios?", JOptionPane.YES_NO_OPTION); if (result == JOptionPane.YES_OPTION) { try { XMLOutputter xmlo = new XMLOutputter(Format.getPrettyFormat()); URI uri = new URI(tx.getDocument().getBaseURI()); File file = new File(uri); tx.writeTrabajo(jt.getTrabajo()); xmlo.output(tx.getDocument(), new FileWriter(file)); } catch (URISyntaxException | IOException ex) { Logger.getLogger(PodaPresu4.class.getName()).log(Level.SEVERE, null, ex); } } } }
public static void setServerFile() { Element serverFileForServer = new Element("content"); serverFileForServer.addContent(new Element("freigabe").setText("true")); serverFileForServer.addContent(new Element("satzstatus").setText("Satz spielen")); serverFileForServer.addContent(new Element("gegnerzug").setText("-1")); serverFileForServer.addContent(new Element("sieger").setText("offen")); Document document = new Document(serverFileForServer); XMLOutputter xmlOutputter = new XMLOutputter(); xmlOutputter.setFormat(Format.getPrettyFormat()); try { xmlOutputter.output( document, new FileWriter( Controller.getController().getCommunicationController().getServerFilePath())); } catch (IOException e) { e.printStackTrace(); } }
/** * 格式化xml * * @param xml 待格式化xml字符串 * @return xml字符串 * @throws DataFormatException 格式化异常 */ public static String xml(String xml) throws DataFormatException { if (xFormat == null) { xFormat = Format.getCompactFormat().setIndent(" "); } if (xBuilder == null) { xBuilder = new SAXBuilder(); } XMLOutputter xmlout = new XMLOutputter(xFormat); StringReader xmlReader = new StringReader(xml); ByteArrayOutputStream os = new ByteArrayOutputStream(); try { org.jdom2.Document doc = xBuilder.build(xmlReader); xmlout.output(doc, os); } catch (JDOMException e) { throw new DataFormatException("格式化XML字符串失败", e); } catch (IOException e) { throw new RuntimeException(e); } return os.toString(); }
/** ************************************************************************* */ public static String elementToStringDump(Element e) { if (e == null) return null; XMLOutputter out = new XMLOutputter(Format.getCompactFormat()); return out.outputString(e); }