nu.xom.Document Java Examples
The following examples show how to use
nu.xom.Document.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: XMLUtil.java From rest-client with Apache License 2.0 | 8 votes |
@Deprecated public static String indentXML(final String in) throws XMLException, IOException { try { Builder parser = new Builder(); Document doc = parser.build(in, null); ByteArrayOutputStream baos = new ByteArrayOutputStream(); Serializer serializer = new Serializer(baos); serializer.setIndent(4); serializer.setMaxLength(69); serializer.write(doc); return new String(baos.toByteArray()); } catch (ParsingException ex) { // LOG.log(Level.SEVERE, null, ex); throw new XMLException("XML indentation failed.", ex); } }
Example #2
Source File: FreemarkerTest.java From cloud-opensource-java with Apache License 2.0 | 6 votes |
@Test public void testVersionIndex() throws IOException, TemplateException, URISyntaxException, ParsingException { Path output = DashboardMain.generateVersionIndex( "com.google.cloud", "libraries-bom", ImmutableList.of("1.0.0", "2.0.0", "2.1.0-SNAPSHOT")); Assert.assertTrue( output.endsWith(Paths.get("target", "com.google.cloud", "libraries-bom", "index.html"))); Assert.assertTrue(Files.isRegularFile(output)); Document document = builder.build(output.toFile()); Nodes links = document.query("//a/@href"); Assert.assertEquals(3, links.size()); Node snapshotLink = links.get(2); // 2.1.0-SNAPSHOT has directory 'snapshot' Assert.assertEquals("snapshot/index.html", snapshotLink.getValue()); }
Example #3
Source File: XomCreateXML.java From maven-framework-project with MIT License | 6 votes |
/** * Create Document Type */ @Test public void test06() throws Exception{ Element greeting = new Element("greeting"); Document doc = new Document(greeting); String temp = "<!DOCTYPE element [\n" + "<!ELEMENT greeting (#PCDATA)>\n" + "]>\n" + "<root />"; Builder builder = new Builder(); Document tempDoc = builder.build(temp, null); DocType doctype = tempDoc.getDocType(); doctype.detach(); doc.setDocType(doctype); System.out.println(doc.toXML()); }
Example #4
Source File: DashboardTest.java From cloud-opensource-java with Apache License 2.0 | 6 votes |
@Test public void testComponent_linkageCheckResult() throws IOException, ParsingException { Document document = parseOutputFile( "com.google.http-client_google-http-client-appengine_1.29.1.html"); Nodes reports = document.query("//p[@class='jar-linkage-report']"); Assert.assertEquals(1, reports.size()); Truth.assertThat(trimAndCollapseWhiteSpace(reports.get(0).getValue())) .isEqualTo("91 target classes causing linkage errors referenced from 501 source classes."); Nodes causes = document.query("//p[@class='jar-linkage-report-cause']"); Truth.assertWithMessage( "google-http-client-appengine should show linkage errors for RpcStubDescriptor") .that(causes) .comparingElementsUsing(NODE_VALUES) .contains( "Class com.google.net.rpc3.client.RpcStubDescriptor is not found," + " referenced from 21 classes ▶"); // '▶' is the toggle button }
Example #5
Source File: DashboardTest.java From cloud-opensource-java with Apache License 2.0 | 6 votes |
@Test public void testComponent_failure() throws IOException, ParsingException { Document document = parseOutputFile( "com.google.api.grpc_grpc-google-common-protos_1.14.0.html"); // com.google.api.grpc:grpc-google-common-protos:1.14.0 has no green section Nodes greens = document.query("//h3[@style='color: green']"); Assert.assertEquals(0, greens.size()); // "Global Upper Bounds Fixes", "Upper Bounds Fixes", and "Suggested Dependency Updates" are red Nodes reds = document.query("//h3[@style='color: red']"); Assert.assertEquals(3, reds.size()); Nodes presDependencyMediation = document.query("//pre[@class='suggested-dependency-mediation']"); Assert.assertTrue( "For failed component, suggested dependency should be shown", presDependencyMediation.size() >= 1); Nodes dependencyTree = document.query("//p[@class='dependency-tree-node']"); Assert.assertTrue( "Dependency Tree should be shown in dashboard even when FAILED", dependencyTree.size() > 0); }
Example #6
Source File: SettingsManager.java From ciscorouter with MIT License | 6 votes |
/** * Constructs the class. Requires settings.xml to be present to run */ public SettingsManager() { String currentDir = System.getProperty("user.dir"); String settingDir = currentDir + "/settings/"; File f = new File(settingDir + "settings.xml"); if (f.exists() && !f.isDirectory()) { try { Builder parser = new Builder(); Document doc = parser.build(f); Element root = doc.getRootElement(); Element eUsername = root.getFirstChildElement("Username"); username = eUsername.getValue(); Element ePassword = root.getFirstChildElement("Password"); password = ePassword.getValue(); requiresAuth = true; } catch (ParsingException|IOException e) { e.printStackTrace(); } } else { requiresAuth = false; } }
Example #7
Source File: XomCreateXML.java From maven-framework-project with MIT License | 6 votes |
/** * 多個節點 */ @Test public void test02() { BigInteger low = BigInteger.ONE; BigInteger high = BigInteger.ONE; Element root = new Element("Fibonacci_Numbers"); for (int i = 1; i <= 10; i++) { Element fibonacci = new Element("fibonacci"); fibonacci.appendChild(low.toString()); root.appendChild(fibonacci); BigInteger temp = high; high = high.add(low); low = temp; } Document doc = new Document(root); System.out.println(doc.toXML()); }
Example #8
Source File: DashboardTest.java From cloud-opensource-java with Apache License 2.0 | 6 votes |
@Test public void testGlobalUpperBoundUpgradeMessage() throws IOException, ParsingException { // Case 1: BOM needs to be updated Document document = parseOutputFile("com.google.protobuf_protobuf-java-util_3.6.1.html"); Nodes globalUpperBoundBomUpgradeNodes = document.query("//li[@class='global-upper-bound-bom-upgrade']"); Truth.assertThat(globalUpperBoundBomUpgradeNodes.size()).isEqualTo(1); String bomUpgradeMessage = globalUpperBoundBomUpgradeNodes.get(0).getValue(); Truth.assertThat(bomUpgradeMessage).contains( "Upgrade com.google.protobuf:protobuf-java-util:jar:3.6.1 in the BOM to version \"3.7.1\""); // Case 2: Dependency needs to be updated Nodes globalUpperBoundDependencyUpgradeNodes = document.query("//li[@class='global-upper-bound-dependency-upgrade']"); // The artifact report should contain the following 6 global upper bound dependency upgrades: // Upgrade com.google.guava:guava:jar:19.0 to version "27.1-android" // Upgrade com.google.protobuf:protobuf-java:jar:3.6.1 to version "3.7.1" Truth.assertThat(globalUpperBoundDependencyUpgradeNodes.size()).isEqualTo(2); String dependencyUpgradeMessage = globalUpperBoundDependencyUpgradeNodes.get(0).getValue(); Truth.assertThat(dependencyUpgradeMessage).contains( "Upgrade com.google.guava:guava:jar:19.0 to version \"27.1-android\""); }
Example #9
Source File: XmlUtils.java From gemfirexd-oss with Apache License 2.0 | 5 votes |
public static String prettyXml(Document doc) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); Serializer serializer = new Serializer(out); serializer.setIndent(2); serializer.write(doc); return out.toString("UTF-8"); }
Example #10
Source File: XmlPersistenceRead.java From rest-client with Apache License 2.0 | 5 votes |
protected Document getDocumentFromFile(final File f) throws IOException, XMLException { try { Builder parser = new Builder(); Document doc = parser.build(f); return doc; } catch (ParsingException | IOException ex) { throw new XMLException(ex.getMessage(), ex); } }
Example #11
Source File: XmlPersistenceRead.java From rest-client with Apache License 2.0 | 5 votes |
protected Request xml2Request(final Document doc) throws MalformedURLException, XMLException { // get the rootNode Element rootNode = doc.getRootElement(); if (!"rest-client".equals(rootNode.getQualifiedName())) { throw new XMLException("Root node is not <rest-client>"); } // checking correct rest version final String rcVersion = rootNode.getAttributeValue("version"); try { Versions.versionValidCheck(rcVersion); } catch(Versions.VersionValidationException ex) { throw new XMLException(ex); } readVersion = rcVersion; // if more than two request element is present then throw the exception if (rootNode.getChildElements().size() != 1) { throw new XMLException("There can be only one child node for root node: <request>"); } // minimum one request element is present in xml if (rootNode.getFirstChildElement("request") == null) { throw new XMLException("The child node of <rest-client> should be <request>"); } Element requestNode = rootNode.getFirstChildElement("request"); return getRequestBean(requestNode); }
Example #12
Source File: ModalDocument.java From caja with Apache License 2.0 | 5 votes |
/** * Copy constructor (<code>Mode</code>-aware). * @param doc */ public ModalDocument(Document doc) { super(doc); if (doc instanceof Mode) { Mode modal = (Mode) doc; setMode(modal.getMode()); } }
Example #13
Source File: XmlUtils.java From gemfirexd-oss with Apache License 2.0 | 5 votes |
public static String getXmlDefinition(Document doc, String entityType, String entityName) { Node node = getNode(doc, entityType, entityName); if (node != null) { return node.toXML(); } else { return null; } }
Example #14
Source File: XmlUtils.java From gemfirexd-oss with Apache License 2.0 | 5 votes |
public static Node getNode(Document doc, String entityType, String entityName) { String query = createQueryStringByName(entityType, entityName); Nodes nodes = doc.query(query); if (nodes != null && nodes.size() > 0) { return nodes.get(0); } return null; }
Example #15
Source File: XMLOutputRenderer.java From ciscorouter with MIT License | 5 votes |
/** * Writes the data to the Output file */ @Override public void writeToFile() throws IOException { Document doc = new Document(root); FileWriter fw = new FileWriter(file, false); fw.write(doc.toXML()); fw.flush(); fw.close(); }
Example #16
Source File: DashboardTest.java From cloud-opensource-java with Apache License 2.0 | 5 votes |
@Test public void testBomCoordinatesInArtifactDetails() throws IOException, ParsingException { Document document = parseOutputFile("artifact_details.html"); Nodes bomCoordinatesNodes = document.query("//p[@class='bom-coordinates']"); Assert.assertEquals(1, bomCoordinatesNodes.size()); Assert.assertEquals( "BOM: com.google.cloud:libraries-bom:1.0.0", bomCoordinatesNodes.get(0).getValue()); }
Example #17
Source File: DashboardTest.java From cloud-opensource-java with Apache License 2.0 | 5 votes |
@Test public void testBomCoordinatesInUnstableArtifacts() throws IOException, ParsingException { Document document = parseOutputFile("unstable_artifacts.html"); Nodes bomCoordinatesNodes = document.query("//p[@class='bom-coordinates']"); Assert.assertEquals(1, bomCoordinatesNodes.size()); Assert.assertEquals( "BOM: com.google.cloud:libraries-bom:1.0.0", bomCoordinatesNodes.get(0).getValue()); }
Example #18
Source File: DashboardTest.java From cloud-opensource-java with Apache License 2.0 | 5 votes |
@Test public void testDependencyTrees() throws IOException, ParsingException { Document document = parseOutputFile("dependency_trees.html"); Nodes dependencyTreeParagraph = document.query("//p[@class='dependency-tree-node']"); Assert.assertEquals(53144, dependencyTreeParagraph.size()); Assert.assertEquals( "com.google.protobuf:protobuf-java:jar:3.6.1", dependencyTreeParagraph.get(0).getValue()); }
Example #19
Source File: DashboardTest.java From cloud-opensource-java with Apache License 2.0 | 5 votes |
@Test public void testBomCoordinatesInComponent() throws IOException, ParsingException { Document document = parseOutputFile("com.google.protobuf_protobuf-java-util_3.6.1.html"); Nodes bomCoordinatesNodes = document.query("//p[@class='bom-coordinates']"); Assert.assertEquals(1, bomCoordinatesNodes.size()); Assert.assertEquals( "BOM: com.google.cloud:libraries-bom:1.0.0", bomCoordinatesNodes.get(0).getValue()); }
Example #20
Source File: XMLCollectionUtil.java From rest-client with Apache License 2.0 | 5 votes |
public static void writeRequestCollectionXML(final List<Request> requests, final File f) throws IOException, XMLException { XmlPersistenceWrite xUtl = new XmlPersistenceWrite(); Element eRoot = new Element("request-collection"); eRoot.addAttribute(new Attribute("version", Versions.CURRENT)); for(Request req: requests) { Element e = xUtl.getRequestElement(req); eRoot.appendChild(e); } Document doc = new Document(eRoot); xUtl.writeXML(doc, f); }
Example #21
Source File: XMLCollectionUtil.java From rest-client with Apache License 2.0 | 5 votes |
public static List<Request> getRequestCollectionFromXMLFile(final File f) throws IOException, XMLException { XmlPersistenceRead xUtlRead = new XmlPersistenceRead(); List<Request> out = new ArrayList<>(); Document doc = xUtlRead.getDocumentFromFile(f); Element eRoot = doc.getRootElement(); if(!"request-collection".equals(eRoot.getLocalName())) { throw new XMLException("Expecting root element <request-collection>, but found: " + eRoot.getLocalName()); } final String version = eRoot.getAttributeValue("version"); try { Versions.versionValidCheck(version); } catch(Versions.VersionValidationException ex) { throw new XMLException(ex); } xUtlRead.setReadVersion(version); Elements eRequests = doc.getRootElement().getChildElements(); for(int i=0; i<eRequests.size(); i++) { Element eRequest = eRequests.get(i); Request req = xUtlRead.getRequestBean(eRequest); out.add(req); } return out; }
Example #22
Source File: PermissionUtils.java From wildfly-core with GNU Lesser General Public License v2.1 | 5 votes |
public static byte[] createPermissionsXml(Permission... permissions) { final Element permissionsElement = new Element("permissions"); permissionsElement.setNamespaceURI("http://xmlns.jcp.org/xml/ns/javaee"); permissionsElement.addAttribute(new Attribute("version", "7")); for (Permission permission : permissions) { final Element permissionElement = new Element("permission"); final Element classNameElement = new Element("class-name"); final Element nameElement = new Element("name"); classNameElement.appendChild(permission.getClass().getName()); nameElement.appendChild(permission.getName()); permissionElement.appendChild(classNameElement); permissionElement.appendChild(nameElement); final String actions = permission.getActions(); if (actions != null && ! actions.isEmpty()) { final Element actionsElement = new Element("actions"); actionsElement.appendChild(actions); permissionElement.appendChild(actionsElement); } permissionsElement.appendChild(permissionElement); } Document document = new Document(permissionsElement); try (ByteArrayOutputStream stream = new ByteArrayOutputStream()) { final NiceSerializer serializer = new NiceSerializer(stream); serializer.setIndent(4); serializer.setLineSeparator("\n"); serializer.write(document); serializer.flush(); return stream.toByteArray(); } catch (IOException e) { throw new IllegalStateException("Generating permissions.xml failed", e); } }
Example #23
Source File: XmlEntity.java From gemfirexd-oss with Apache License 2.0 | 5 votes |
/** * Use the CacheXmlGenerator to create XML from the entity associated with * the current cache. * * @param element Name of the XML element to search for. * @param attributes * Attributes of the element that should match, for example "name" or * "id" and the value they should equal. * * @return XML string representation of the entity. */ private final String loadXmlDefinition(final String element, final Map<String, String> attributes) { final Cache cache = CacheFactory.getAnyInstance(); Document document = null; try { final StringWriter stringWriter = new StringWriter(); final PrintWriter printWriter = new PrintWriter(stringWriter); CacheXmlGenerator.generate(cache, printWriter, false, false, false); printWriter.close(); // Remove the DOCTYPE line when getting the string to prevent // errors when trying to locate the DTD. String xml = stringWriter.toString().replaceFirst("<!DOCTYPE.*>", ""); document = new Builder(false).build(xml, null); } catch (ValidityException vex) { cache.getLogger().error("Could not parse XML when creating XMLEntity", vex); } catch (ParsingException pex) { cache.getLogger().error("Could not parse XML when creating XMLEntity", pex); } catch (IOException ioex) { cache.getLogger().error("Could not parse XML when creating XMLEntity", ioex); } Nodes nodes = document.query(createQueryString(element, attributes)); if (nodes.size() != 0) { return nodes.get(0).toXML(); } cache.getLogger().warning("No XML definition could be found with name=" + element + " and attributes=" + attributes); return null; }
Example #24
Source File: SettingsManager.java From ciscorouter with MIT License | 5 votes |
/** * Sets the username and password for authenticating to the application * @param _username the username to save * @param _password the password to save */ public void setAuth(String _username, String _password) { String hashedPassword; String hashedUsername; try { hashedPassword = PasswordHash.createHash(_password); hashedUsername = PasswordHash.createHash(_username); File settingsFile = new File(System.getProperty("user.dir") + "/settings/settings.xml"); FileWriter fw = new FileWriter(settingsFile, false); Element root = new Element("Settings"); Element user = new Element("Username"); user.appendChild(hashedUsername); root.appendChild(user); Element pass = new Element("Password"); pass.appendChild(hashedPassword); root.appendChild(pass); Document doc = new Document(root); fw.write(doc.toXML()); fw.flush(); fw.close(); } catch (NoSuchAlgorithmException | InvalidKeySpecException | IOException ex) { Logger.getLogger(SettingsManager.class.getName()).log(Level.SEVERE, null, ex); } requiresAuth = true; username = _username; password = _password; }
Example #25
Source File: XomCreateXML.java From maven-framework-project with MIT License | 5 votes |
/** * 最簡單的例子 */ @Test public void test01() { Element root = new Element("root"); root.appendChild("Hello World!"); Document doc = new Document(root); String result = doc.toXML(); System.out.println(result); }
Example #26
Source File: XomCreateXML.java From maven-framework-project with MIT License | 5 votes |
/** * 格式化 */ @Test public void test03() { BigInteger low = BigInteger.ONE; BigInteger high = BigInteger.ONE; Element root = new Element("Fibonacci_Numbers"); for (int i = 1; i <= 10; i++) { Element fibonacci = new Element("fibonacci"); fibonacci.appendChild(low.toString()); root.appendChild(fibonacci); BigInteger temp = high; high = high.add(low); low = temp; } Document doc = new Document(root); try { Serializer serializer = new Serializer(System.out, "ISO-8859-1"); serializer.setIndent(4); serializer.setMaxLength(64); serializer.write(doc); } catch (IOException ex) { System.err.println(ex); } }
Example #27
Source File: XomCreateXML.java From maven-framework-project with MIT License | 5 votes |
/** * 屬性 */ @Test public void test04() { BigInteger low = BigInteger.ONE; BigInteger high = BigInteger.ONE; Element root = new Element("Fibonacci_Numbers"); for (int i = 1; i <= 10; i++) { Element fibonacci = new Element("fibonacci"); fibonacci.appendChild(low.toString()); Attribute index = new Attribute("index", String.valueOf(i)); fibonacci.addAttribute(index); root.appendChild(fibonacci); BigInteger temp = high; high = high.add(low); low = temp; } Document doc = new Document(root); try { Serializer serializer = new Serializer(System.out, "ISO-8859-1"); serializer.setIndent(4); serializer.setMaxLength(64); serializer.write(doc); } catch (IOException ex) { System.err.println(ex); } }
Example #28
Source File: XomCreateXML.java From maven-framework-project with MIT License | 5 votes |
/** * 聲明Document Type */ @Test public void test05() { BigInteger low = BigInteger.ONE; BigInteger high = BigInteger.ONE; Element root = new Element("Fibonacci_Numbers"); for (int i = 1; i <= 10; i++) { Element fibonacci = new Element("fibonacci"); fibonacci.appendChild(low.toString()); Attribute index = new Attribute("index", String.valueOf(i)); fibonacci.addAttribute(index); root.appendChild(fibonacci); BigInteger temp = high; high = high.add(low); low = temp; } Document doc = new Document(root); DocType doctype = new DocType("Fibonacci_Numbers", "fibonacci.dtd"); doc.insertChild(doctype, 0); try { Serializer serializer = new Serializer(System.out, "ISO-8859-1"); serializer.setIndent(4); serializer.setMaxLength(64); serializer.write(doc); } catch (IOException ex) { System.err.println(ex); } }
Example #29
Source File: XomCreateXML.java From maven-framework-project with MIT License | 5 votes |
/** * Create elements in namespaces */ @Test public void test07() throws Exception{ BigInteger low = BigInteger.ONE; BigInteger high = BigInteger.ONE; String namespace = "http://www.w3.org/1998/Math/MathML"; Element root = new Element("mathml:math", namespace); for (int i = 1; i <= 10; i++) { Element mrow = new Element("mathml:mrow", namespace); Element mi = new Element("mathml:mi", namespace); Element mo = new Element("mathml:mo", namespace); Element mn = new Element("mathml:mn", namespace); mrow.appendChild(mi); mrow.appendChild(mo); mrow.appendChild(mn); root.appendChild(mrow); mi.appendChild("f(" + i + ")"); mo.appendChild("="); mn.appendChild(low.toString()); BigInteger temp = high; high = high.add(low); low = temp; } Document doc = new Document(root); try { Serializer serializer = new Serializer(System.out, "ISO-8859-1"); serializer.setIndent(4); serializer.setMaxLength(64); serializer.write(doc); } catch (IOException ex) { System.err.println(ex); } }
Example #30
Source File: ResponseCommand.java From timbuctoo with GNU General Public License v3.0 | 5 votes |
@Override public void verify(CommandCall commandCall, Evaluator evaluator, ResultRecorder resultRecorder) { ValidationResult validationResult; if (!StringUtils.isBlank(verificationMethod)) { evaluator.setVariable("#nl_knaw_huygens_httpcommand_result", requestCommand.getActualResult()); evaluator.setVariable("#nl_knaw_huygens_httpcommand_expectation", expectation); validationResult = (ValidationResult) evaluator.evaluate( verificationMethod + "(#nl_knaw_huygens_httpcommand_expectation, #nl_knaw_huygens_httpcommand_result)" ); evaluator.setVariable("#nl_knaw_huygens_httpcommand_result", null); evaluator.setVariable("#nl_knaw_huygens_httpcommand_expectation", null); } else { validationResult = defaultValidator.validate(expectation, requestCommand.getActualResult()); } Element caption = null; if (addCaptions) { caption = new Element("div").addAttribute("class", "responseCaption").appendText("Response:"); } Element resultElement = replaceWithEmptyElement(commandCall.getElement(), name, namespace, caption); addClass(resultElement, "responseContent"); try { Builder builder = new Builder(); Document document = builder.build(new StringReader(validationResult.getMessage())); //new Element() creates a deepcopy not attached to the doc nu.xom.Element rootElement = new nu.xom.Element(document.getRootElement()); resultElement.appendChild(new Element(rootElement)); resultRecorder.record(validationResult.isSucceeded() ? Result.SUCCESS : Result.FAILURE); } catch (ParsingException | IOException e) { resultRecorder.record(Result.FAILURE); if (e instanceof ParsingException) { resultElement.appendText( "Error at line " + ((ParsingException) e).getLineNumber() + ", column: " + ((ParsingException) e).getColumnNumber()); resultElement.appendText(validationResult.getMessage()); } } }