List of usage examples for org.w3c.dom Document getDocumentElement
public Element getDocumentElement();
From source file:Main.java
public static <T> Element marshal(JAXBElement<T> jaxbElement, Class<T> cls) { try {/*from w w w . jav a2s . c om*/ DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.newDocument(); JAXBContext jaxbContext = JAXBContext.newInstance(cls); Marshaller marshaller = jaxbContext.createMarshaller(); marshaller.marshal(jaxbElement, doc); return doc.getDocumentElement(); } catch (JAXBException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ParserConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; }
From source file:com.mirth.connect.server.util.SqlConfig.java
/** * This method loads the MyBatis SQL config file for the database in use, * then appends sqlMap entries from any installed plugins *///from ww w .j a va 2 s .c o m public static void init() { try { LogFactory.useLog4JLogging(); System.setProperty("derby.stream.error.method", "com.mirth.connect.server.Mirth.getNullOutputStream"); DatabaseSettings databaseSettings = ControllerFactory.getFactory().createConfigurationController() .getDatabaseSettings(); BufferedReader br = new BufferedReader(Resources.getResourceAsReader("SqlMapConfig.xml")); // parse the SqlMapConfig (ignoring the DTD) DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); Document document = factory.newDocumentBuilder().parse(new InputSource(br)); addPluginSqlMaps(databaseSettings.getDatabase(), new DonkeyElement(document.getDocumentElement()).getChildElement("mappers")); DocumentSerializer docSerializer = new DocumentSerializer(); Reader reader = new StringReader(docSerializer.toXML(document)); sqlSessionfactory = new SqlSessionFactoryBuilder().build(reader, databaseSettings.getProperties()); sqlSessionManager = SqlSessionManager.newInstance(sqlSessionfactory); } catch (Exception e) { throw new RuntimeException(e); } }
From source file:cz.incad.kramerius.virtualcollections.VirtualCollectionsManager.java
public static List<VirtualCollection> getVirtualCollectionsFromFedora(FedoraAccess fedoraAccess, ArrayList<String> languages) throws Exception { try {/*w w w .jav a2s.c om*/ IResourceIndex g = ResourceIndexService.getResourceIndexImpl(); Document doc = g.getVirtualCollections(); NodeList nodes = doc.getDocumentElement().getElementsByTagNameNS(SPARQL_NS, "result"); NodeList children; Node child; String name; String pid; boolean canLeave; ArrayList<String> langs = new ArrayList<String>(); if (languages == null || languages.isEmpty()) { String[] ls = KConfiguration.getInstance().getPropertyList("interface.languages"); for (int i = 0; i < ls.length; i++) { String lang = ls[++i]; langs.add(lang); } } else { langs = new ArrayList<String>(languages); } List<VirtualCollection> vcs = new ArrayList<VirtualCollection>(); for (int i = 0; i < nodes.getLength(); i++) { canLeave = false; name = null; pid = null; Node node = nodes.item(i); children = node.getChildNodes(); for (int j = 0; j < children.getLength(); j++) { child = children.item(j); if ("title".equals(child.getLocalName())) { name = child.getFirstChild().getNodeValue(); } else if ("object".equals(child.getLocalName())) { pid = ((Element) child).getAttribute("uri").replaceAll("info:fedora/", ""); } else if ("canLeave".equals(child.getLocalName())) { canLeave = Boolean.parseBoolean(child.getFirstChild().getNodeValue().replaceAll("\"", "") .substring(("canLeave:").length())); } } if (name != null && pid != null) { try { VirtualCollection vc = new VirtualCollection(name, pid, canLeave); for (String lang : langs) { String dsName = TEXT_DS_PREFIX + lang; String value = IOUtils.readAsString(fedoraAccess.getDataStream(pid, dsName), Charset.forName("UTF8"), true); vc.addDescription(lang, value); } vcs.add(vc); } catch (Exception vcex) { logger.log(Level.WARNING, "Could not get virtual collection for " + pid + ": " + vcex.toString()); } } } return vcs; } catch (Exception ex) { logger.log(Level.SEVERE, "Error getting virtual collections", ex); throw new Exception(ex); } }
From source file:Main.java
private static NodeList getNodeList(Document document, String expression) throws XPathExpressionException { XPath xpath = XPathFactory.newInstance().newXPath(); NodeList nodeList = (NodeList) xpath.evaluate(expression, document.getDocumentElement(), XPathConstants.NODESET); return nodeList; }
From source file:Main.java
/** * Convert XML from file path to a XML DOM document * * @param strXMLFilePath/*w w w . j a va2 s . co m*/ * XML file path * @return XML DOM document * @throws Exception * in error case */ public static Document xmlFileToDOMDocument(String strXMLFilePath) throws Exception { if (strXMLFilePath == null) { throw new RuntimeException("No XML path given (null)!"); } Document doc = null; try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); File xmlFile = new File(strXMLFilePath); doc = db.parse(xmlFile); doc.getDocumentElement().normalize(); } catch (Exception e) { // Logger.XMLEval.logState("Parsing of XML input failed: " + e.getMessage(), LogLevel.Error); throw e; } return doc; }
From source file:Main.java
/** * Parses a {@link Document} from an {@link InputStream} containing one. * This is quite usual start {@link PersistenceHandler #load(InputStream) * load()}-method of an {@link PersistenceHandler}-implementor. * /* w w w. ja v a 2 s. c o m*/ * @param inStream * {@link InputStream} from which to parse * @return {@link Document} parsed from the input-stream * @throws ParserConfigurationException * @throws SAXException * @throws IOException */ public static Document parseFromBytes(byte[] dataPres) throws ParserConfigurationException, SAXException, IOException { DocumentBuilder dBuilder = null; Document doc = null; dBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); // no external resources are tied with ByteArray-streams; // no need to worry about closing doc = dBuilder.parse(new ByteArrayInputStream(dataPres)); doc.getDocumentElement().normalize(); return doc; }
From source file:no.kantega.commons.util.XMLHelper.java
public static Element setChild(Document doc, Document parent, String name) { Element child = doc.getDocumentElement(); if (child == null) { child = doc.createElement(name); parent.appendChild(child);//from w ww .j a va 2 s.c o m } return child; }
From source file:Main.java
private static Document parseXml(String xmlPath) { Document doc = null; try {/*from w w w . jav a 2 s. c o m*/ File trainSchedule = new File(xmlPath); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); doc = builder.parse(trainSchedule); doc.getDocumentElement().normalize(); } catch (Exception ex) { ex.printStackTrace(); } if (doc == null) throw new ParserException("cannot parse: \"" + xmlPath + "\""); return doc; }
From source file:net.unicon.cas.support.wsfederation.WsFederationUtils.java
/** * parseTokenFromString converts a raw wresult and extracts it into an assertion. * * @param wresult the raw token returned by the IdP * @return an assertion//from w w w . j a va 2 s . com */ public static Assertion parseTokenFromString(final String wresult) { try (final InputStream in = new ByteArrayInputStream(wresult.getBytes("UTF-8"))) { final BasicParserPool parserPool = new BasicParserPool(); parserPool.setNamespaceAware(true); final Document document = parserPool.parse(in); final Element metadataRoot = document.getDocumentElement(); final UnmarshallerFactory unmarshallerFactory = Configuration.getUnmarshallerFactory(); final Unmarshaller unmarshaller = unmarshallerFactory.getUnmarshaller(metadataRoot); final RequestSecurityTokenResponseImpl rsToken = (RequestSecurityTokenResponseImpl) unmarshaller .unmarshall(metadataRoot); //Get our SAML token final List<RequestedSecurityToken> rst = rsToken.getRequestedSecurityToken(); final AssertionImpl assertion = (AssertionImpl) rst.get(0).getSecurityTokens().get(0); if (assertion == null) { LOGGER.debug("parseTokenFromString: assertion null"); } else { LOGGER.debug("parseTokenFromString: {}", assertion); } return assertion; } catch (final Exception ex) { LOGGER.warn(ex.getMessage()); return null; } }
From source file:DOMUtils.java
public static void compareNodes(Node expected, Node actual) throws Exception { if (expected.getNodeType() != actual.getNodeType()) { throw new Exception("Different types of nodes: " + expected + " " + actual); }//from ww w .j a v a 2 s. c o m if (expected instanceof Document) { Document expectedDoc = (Document) expected; Document actualDoc = (Document) actual; compareNodes(expectedDoc.getDocumentElement(), actualDoc.getDocumentElement()); } else if (expected instanceof Element) { Element expectedElement = (Element) expected; Element actualElement = (Element) actual; // compare element names if (!expectedElement.getLocalName().equals(actualElement.getLocalName())) { throw new Exception("Element names do not match: " + expectedElement.getLocalName() + " " + actualElement.getLocalName()); } // compare element ns String expectedNS = expectedElement.getNamespaceURI(); String actualNS = actualElement.getNamespaceURI(); if ((expectedNS == null && actualNS != null) || (expectedNS != null && !expectedNS.equals(actualNS))) { throw new Exception("Element namespaces names do not match: " + expectedNS + " " + actualNS); } String elementName = "{" + expectedElement.getNamespaceURI() + "}" + actualElement.getLocalName(); // compare attributes NamedNodeMap expectedAttrs = expectedElement.getAttributes(); NamedNodeMap actualAttrs = actualElement.getAttributes(); if (countNonNamespaceAttribures(expectedAttrs) != countNonNamespaceAttribures(actualAttrs)) { throw new Exception(elementName + ": Number of attributes do not match up: " + countNonNamespaceAttribures(expectedAttrs) + " " + countNonNamespaceAttribures(actualAttrs)); } for (int i = 0; i < expectedAttrs.getLength(); i++) { Attr expectedAttr = (Attr) expectedAttrs.item(i); if (expectedAttr.getName().startsWith("xmlns")) { continue; } Attr actualAttr = null; if (expectedAttr.getNamespaceURI() == null) { actualAttr = (Attr) actualAttrs.getNamedItem(expectedAttr.getName()); } else { actualAttr = (Attr) actualAttrs.getNamedItemNS(expectedAttr.getNamespaceURI(), expectedAttr.getLocalName()); } if (actualAttr == null) { throw new Exception(elementName + ": No attribute found:" + expectedAttr); } if (!expectedAttr.getValue().equals(actualAttr.getValue())) { throw new Exception(elementName + ": Attribute values do not match: " + expectedAttr.getValue() + " " + actualAttr.getValue()); } } // compare children NodeList expectedChildren = expectedElement.getChildNodes(); NodeList actualChildren = actualElement.getChildNodes(); if (expectedChildren.getLength() != actualChildren.getLength()) { throw new Exception(elementName + ": Number of children do not match up: " + expectedChildren.getLength() + " " + actualChildren.getLength()); } for (int i = 0; i < expectedChildren.getLength(); i++) { Node expectedChild = expectedChildren.item(i); Node actualChild = actualChildren.item(i); compareNodes(expectedChild, actualChild); } } else if (expected instanceof Text) { String expectedData = ((Text) expected).getData().trim(); String actualData = ((Text) actual).getData().trim(); if (!expectedData.equals(actualData)) { throw new Exception("Text does not match: " + expectedData + " " + actualData); } } }