Java Examples for org.w3c.dom.Document

The following java examples will help you to understand the usage of org.w3c.dom.Document. These source code samples are taken from different open source projects.

Example 1
Project: Sgk-Saglik-Provizyon-App-master  File: XmlParser.java View source code
public org.w3c.dom.Document getDocument(String xml) {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = null;
    try {
        db = dbf.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    }
    InputSource is = new InputSource();
    is.setCharacterStream(new StringReader(xml));
    org.w3c.dom.Document doc;
    try {
        doc = db.parse(is);
        this.parsedDocument = doc;
        return doc;
    } catch (SAXException e) {
        e.printStackTrace();
        return null;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}
Example 2
Project: geotools-2.7.x-master  File: GMLGeometryCollectionTypeBinding2Test.java View source code
public void testEncode() throws Exception {
    Document dom = encode(GML2MockData.multiGeometry(), GML.MultiGeometry);
    assertEquals(3, getElementsByQName(dom, GML.geometryMember).getLength());
    assertNotNull(getElementByQName(dom, GML.Point));
    assertNotNull(getElementByQName(dom, GML.LineString));
    assertNotNull(getElementByQName(dom, GML.Polygon));
}
Example 3
Project: geotools-master  File: GMLGeometryCollectionTypeBinding2Test.java View source code
public void testEncode() throws Exception {
    Document dom = encode(GML2MockData.multiGeometry(), GML.MultiGeometry);
    assertEquals(3, getElementsByQName(dom, GML.geometryMember).getLength());
    assertNotNull(getElementByQName(dom, GML.Point));
    assertNotNull(getElementByQName(dom, GML.LineString));
    assertNotNull(getElementByQName(dom, GML.Polygon));
}
Example 4
Project: geotools-old-master  File: GMLGeometryCollectionTypeBinding2Test.java View source code
public void testEncode() throws Exception {
    Document dom = encode(GML2MockData.multiGeometry(), GML.MultiGeometry);
    assertEquals(3, getElementsByQName(dom, GML.geometryMember).getLength());
    assertNotNull(getElementByQName(dom, GML.Point));
    assertNotNull(getElementByQName(dom, GML.LineString));
    assertNotNull(getElementByQName(dom, GML.Polygon));
}
Example 5
Project: geotools_trunk-master  File: GMLGeometryCollectionTypeBinding2Test.java View source code
public void testEncode() throws Exception {
    Document dom = encode(GML2MockData.multiGeometry(), GML.MultiGeometry);
    assertEquals(3, getElementsByQName(dom, GML.geometryMember).getLength());
    assertNotNull(getElementByQName(dom, GML.Point));
    assertNotNull(getElementByQName(dom, GML.LineString));
    assertNotNull(getElementByQName(dom, GML.Polygon));
}
Example 6
Project: xmlsmartdoc-master  File: GoldenportService.java View source code
/**
     * Implementation of a operation eval.
     *
     * @param source
     * @exception RemoteException
     * @return org.w3c.dom.Document
     */
public org.w3c.dom.Document eval(String source) throws RemoteException {
    try {
        URL url = UURL.getURLFromFileOrURLName(source);
        File file = UURL.getActiveFile(url);
        DocumentBuilder builder = rGetDocumentBuilder();
        Document doc = builder.parse(file);
        PortConfig config = getPortConfig_();
        PortEngine engine = new PortEngine(config, rGetContext());
        PortContext context = new PortContext();
        context.setEngine(engine);
        context.setBaseFile(file);
        return (engine.eval(doc, context));
    } catch (GoldenportException e) {
        throw (new RemoteException("TODO", e));
    } catch (SAXException e) {
        throw (new RemoteException("TODO", e));
    } catch (IOException e) {
        throw (new RemoteException("TODO", e));
    } finally {
    }
}
Example 7
Project: jdom-master  File: TestJAXPDOMAdapter.java View source code
private void timeDoc() throws JDOMException {
    long time = System.nanoTime();
    long hash = 0L;
    final int cnt = 1000;
    for (int i = 0; i < cnt; i++) {
        Document doc = new JAXPDOMAdapter().createDocument();
        hash += doc.hashCode();
    }
    time = System.nanoTime() - time;
    System.out.printf("JAXPDOMAdapter Speed %.3f %d\n", (time / 1000000.0) / cnt, hash & 0x01);
}
Example 8
Project: geoserver-2.0.x-master  File: LockFeatureTest.java View source code
public void testLock() throws Exception {
    String xml = "<wfs:LockFeature xmlns:sf=\"http://cite.opengeospatial.org/gmlsf\" xmlns:wfs=\"http://www.opengis.net/wfs\" expiry=\"5\" handle=\"LockFeature-tc1\" " + " lockAction=\"ALL\" " + " service=\"WFS\" " + " version=\"1.1.0\">" + "<wfs:Lock handle=\"lock-1\" typeName=\"sf:PrimitiveGeoFeature\"/>" + "</wfs:LockFeature>";
    Document dom = postAsDOM("wfs", xml);
    assertEquals("wfs:LockFeatureResponse", dom.getDocumentElement().getNodeName());
    assertEquals(5, dom.getElementsByTagNameNS(OGC.NAMESPACE, "FeatureId").getLength());
}
Example 9
Project: geoserver-master  File: GetDomainTest.java View source code
@Test
public void testGetDomain() throws Exception {
    Document dom = getAsDOM("csw?service=csw&version=2.0.2&request=GetDomain&propertyName=dc:title");
    print(dom);
    assertXpathEvaluatesTo("dc:title", "/csw:GetDomainResponse/csw:DomainValues/csw:PropertyName", dom);
    assertXpathEvaluatesTo("29", "count(//csw:Value)", dom);
    assertXpathExists("//csw:Value[.='AggregateGeoFeature']", dom);
    assertXpathExists("//csw:Value[.='BasicPolygons']", dom);
    assertXpathExists("//csw:Value[.='Bridges']", dom);
}
Example 10
Project: geoserver-old-master  File: LockFeatureTest.java View source code
public void testLock() throws Exception {
    String xml = "<wfs:LockFeature xmlns:sf=\"http://cite.opengeospatial.org/gmlsf\" xmlns:wfs=\"http://www.opengis.net/wfs\" expiry=\"5\" handle=\"LockFeature-tc1\" " + " lockAction=\"ALL\" " + " service=\"WFS\" " + " version=\"1.1.0\">" + "<wfs:Lock handle=\"lock-1\" typeName=\"sf:PrimitiveGeoFeature\"/>" + "</wfs:LockFeature>";
    Document dom = postAsDOM("wfs", xml);
    assertEquals("wfs:LockFeatureResponse", dom.getDocumentElement().getNodeName());
    assertEquals(5, dom.getElementsByTagNameNS(OGC.NAMESPACE, "FeatureId").getLength());
}
Example 11
Project: geoserver_trunk-master  File: LockFeatureTest.java View source code
public void testLock() throws Exception {
    String xml = "<wfs:LockFeature xmlns:sf=\"http://cite.opengeospatial.org/gmlsf\" xmlns:wfs=\"http://www.opengis.net/wfs\" expiry=\"5\" handle=\"LockFeature-tc1\" " + " lockAction=\"ALL\" " + " service=\"WFS\" " + " version=\"1.1.0\">" + "<wfs:Lock handle=\"lock-1\" typeName=\"sf:PrimitiveGeoFeature\"/>" + "</wfs:LockFeature>";
    Document dom = postAsDOM("wfs", xml);
    assertEquals("wfs:LockFeatureResponse", dom.getDocumentElement().getNodeName());
    assertEquals(5, dom.getElementsByTagNameNS(OGC.NAMESPACE, "FeatureId").getLength());
}
Example 12
Project: wonder-master  File: Parsing.java View source code
public static void main(String[] args) {
    ERXML.Doc doc = ERXML.doc("<person><first-name>Mike</first-name><last-name>Schrag</last-name><addresses><address location=\"home\"><address>100 Main St</address><city>Richmond</city></address></addresses></person>");
    System.out.println(doc);
    org.w3c.dom.Document w3cDoc = doc.w3c();
    ERXML.Doc doc2 = ERXML.doc(w3cDoc);
    System.out.println(doc2);
}
Example 13
Project: xiss-master  File: Parsing.java View source code
public static void main(String[] args) {
    XML.Doc doc = XML.doc("<person><first-name>Mike</first-name><last-name>Schrag</last-name><addresses><address location=\"home\"><address>100 Main St</address><city>Richmond</city></address></addresses></person>");
    System.out.println(doc);
    org.w3c.dom.Document w3cDoc = doc.w3c();
    XML.Doc doc2 = XML.doc(w3cDoc);
    System.out.println(doc2);
}
Example 14
Project: spring-integration-master  File: ParserTestUtil.java View source code
static org.w3c.dom.Document loadXMLFrom(java.io.InputStream is) throws org.xml.sax.SAXException, java.io.IOException {
    javax.xml.parsers.DocumentBuilderFactory factory = javax.xml.parsers.DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    javax.xml.parsers.DocumentBuilder builder = null;
    try {
        builder = factory.newDocumentBuilder();
    } catch (javax.xml.parsers.ParserConfigurationException ex) {
    }
    org.w3c.dom.Document doc = builder.parse(is);
    is.close();
    return doc;
}
Example 15
Project: FireflowEngine20-master  File: VariablePayloadType.java View source code
protected Object nullSafeGetInternal(ResultSet rs, String[] names, Object owner, LobHandler lobHandler) throws SQLException {
    String s = lobHandler.getClobAsString(rs, names[0]);
    //�置文件,Headers必须在第五个字段//rs.getString(VariableProperty.HEADERS.name());
    String headerXml = rs.getString(5);
    //DataType必须在第六个字段//rs.getString(VariableProperty.DATA_TYPE.name());
    String dataType = rs.getString(6);
    //String uri = "http://jcp.org/en/jsr/detail?id=270";
    String uri = NameSpaces.JAVA.getUri();
    if (dataType != null && dataType.startsWith("{" + uri + "}")) {
        //java类型
        XStream xstream = new XStream();
        return xstream.fromXML(s);
    } else {
        //xml类型
        Properties headers = VariableHeaderType.xmlString2Map(headerXml);
        String className = (String) headers.get(Variable.HEADER_KEY_CLASS_NAME);
        String encoding = (String) headers.get(Variable.HEADER_KEY_ENCODING);
        if (StringUtils.isEmpty(encoding)) {
            encoding = Utils.findXmlCharset(s);
        }
        try {
            ByteArrayInputStream in = new ByteArrayInputStream(s.getBytes(encoding));
            SAXReader reader = new SAXReader();
            reader.setEncoding(encoding);
            Document dom4jDoc = reader.read(in);
            if (StringUtils.isEmpty(className) || className.trim().equals("org.w3c.dom.Document")) {
                DOMWriter domWriter = new DOMWriter();
                org.w3c.dom.Document dom = domWriter.write(dom4jDoc);
                return dom;
            } else {
                return dom4jDoc;
            }
        } catch (Exception e) {
            throw new SQLException(e.getMessage());
        }
    }
}
Example 16
Project: cxf-master  File: DOM4JProvider.java View source code
public org.dom4j.Document readFrom(Class<org.dom4j.Document> cls, Type type, Annotation[] anns, MediaType mt, MultivaluedMap<String, String> headers, InputStream is) throws IOException, WebApplicationException {
    MessageBodyReader<org.w3c.dom.Document> reader = providers.getMessageBodyReader(DOM_DOC_CLS, DOM_DOC_CLS, anns, mt);
    if (reader == null) {
        throw ExceptionUtils.toNotSupportedException(null, null);
    }
    org.w3c.dom.Document domDoc = reader.readFrom(DOM_DOC_CLS, DOM_DOC_CLS, anns, mt, headers, is);
    return new org.dom4j.io.DOMReader().read(domDoc);
}
Example 17
Project: projectforge-webapp-master  File: XmlHelper.java View source code
public static Element fromString(final String str) {
    if (StringUtils.isBlank(str) == true) {
        return null;
    }
    try {
        final Document document = DocumentHelper.parseText(str);
        return document.getRootElement();
    } catch (final DocumentException ex) {
        log.error("Exception encountered " + ex.getMessage());
    }
    return null;
}
Example 18
Project: XOM-master  File: DOMConverterTest.java View source code
protected void setUp() throws ParserConfigurationException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    builder = factory.newDocumentBuilder();
    impl = builder.getDOMImplementation();
    DocType type = new DocType("test");
    Element root = new Element("test");
    xomDocument = new Document(root);
    xomDocument.insertChild(type, 0);
    xomDocument.insertChild(new ProcessingInstruction("xml-stylesheet", "href=\"file.css\" type=\"text/css\""), 1);
    xomDocument.insertChild(new Comment(" test "), 2);
    xomDocument.appendChild(new Comment("epilog"));
    root.addNamespaceDeclaration("xlink", "http://www.w3.org/TR/1999/xlink");
    root.appendChild("Hello dear\r\n");
    Element em = new Element("em");
    root.appendChild(em);
    em.addAttribute(new Attribute("id", "p1"));
    em.addNamespaceDeclaration("none", "http://www.example.com");
    em.appendChild("very important");
    Element span = new Element("span");
    root.appendChild(span);
    span.addAttribute(new Attribute("xlink:type", "http://www.w3.org/TR/1999/xlink", "simple"));
    span.appendChild("here's the link");
    root.appendChild("\r\n");
    Element empty = new Element("empty");
    root.appendChild(empty);
    empty.addAttribute(new Attribute("xom:temp", "http://xom.nu/", "Just to see if this can handle namespaced attributes"));
    root.appendChild("\r\n");
    Element svg = new Element("svg:svg", "http://www.w3.org/TR/2000/svg");
    root.appendChild(svg);
    Element text = new Element("svg:text", "http://www.w3.org/TR/2000/svg");
    svg.appendChild(text);
    text.appendChild("text in a namespace");
    root.appendChild("\r\n");
    svg = new Element("svg", "http://www.w3.org/TR/2000/svg");
    root.appendChild(svg);
    text = new Element("text", "http://www.w3.org/TR/2000/svg");
    svg.appendChild(text);
    text.appendChild("text in a namespace");
    Reader reader = new StringReader(source);
    InputSource inso = new InputSource(reader);
    try {
        domDocument = builder.parse(inso);
    } catch (Exception ex) {
        throw new RuntimeException("Oops!");
    }
}
Example 19
Project: MEditor-master  File: DCUtils.java View source code
/**
     * Elements from dc.
     * 
     * @param dc
     *        the dc
     * @param elementName
     *        the element name
     * @return the list
     */
private static List<String> elementsFromDC(org.w3c.dom.Document dc, String elementName) {
    List<String> elements = new ArrayList<String>();
    Element documentElement = dc.getDocumentElement();
    NodeList childNodes = documentElement.getChildNodes();
    for (int i = 0; i < childNodes.getLength(); i++) {
        Node item = childNodes.item(i);
        if (item.getNodeType() == Node.ELEMENT_NODE) {
            if (item.getLocalName().equals(elementName)) {
                elements.add(item.getTextContent().trim());
            }
        }
    }
    return elements;
}
Example 20
Project: 101simplejava-master  File: Cut.java View source code
public static void cutSalaries(Document doc, String xpath) throws TransformerException {
    // Get the matching elements
    NodeList nodelist = XPathAPI.selectNodeList(doc, xpath);
    // Process the elements in the nodelist
    for (int i = 0; i < nodelist.getLength(); i++) {
        // Get element
        Element elem = (Element) nodelist.item(i);
        // Transform content of element
        double before = Double.parseDouble(elem.getTextContent());
        double after = before / 2;
        elem.setTextContent(Double.toString(after));
    }
}
Example 21
Project: acs-master  File: DumpXML.java View source code
/**
	 * @param args
	 */
public static void main(String[] args) throws Throwable {
    if (args.length != 1) {
        System.err.println("Usage: java " + DumpXML.class.getName() + " <xml file>");
        System.exit(1);
    }
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    // XercesJ 2.9.1 rejects this, it supports it by default
    //factory.setXIncludeAware(true);
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document xmldoc = builder.parse(new InputSource(new FileReader(args[0])));
    Source src = new DOMSource(xmldoc);
    Result dest = new StreamResult(System.out);
    TransformerFactory tranFactory = TransformerFactory.newInstance();
    Transformer transformer = tranFactory.newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.transform(src, dest);
}
Example 22
Project: aliada-tool-master  File: XmlParser.java View source code
/**
     * XML Parser.
     * @param stream The input
     * @return Document
     * @throws Exception The Exception
     * @see
     * @since 1.0
     */
public Document parseXML(final InputStream stream) throws Exception {
    DocumentBuilderFactory objDocumentBuilderFactory = null;
    DocumentBuilder objDocumentBuilder = null;
    Document doc = null;
    try {
        objDocumentBuilderFactory = DocumentBuilderFactory.newInstance();
        objDocumentBuilder = objDocumentBuilderFactory.newDocumentBuilder();
        doc = objDocumentBuilder.parse(stream);
    } catch (Exception ex) {
        throw ex;
    }
    return doc;
}
Example 23
Project: android-codegenerator-library-master  File: XMLPackageExtractor.java View source code
@Override
public String extractPackageFromManifestStream(InputStream inputStream) throws ParserConfigurationException, SAXException, IOException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse(inputStream);
    Element manifest = (Element) doc.getElementsByTagName("manifest").item(0);
    return manifest.getAttribute("package");
}
Example 24
Project: android-maven-plugin-master  File: XmlHelper.java View source code
public static Element getOrCreateElement(Document doc, Element manifestElement, String elementName) {
    NodeList nodeList = manifestElement.getElementsByTagName(elementName);
    Element element = null;
    if (nodeList.getLength() == 0) {
        element = doc.createElement(elementName);
        manifestElement.appendChild(element);
    } else {
        element = (Element) nodeList.item(0);
    }
    return element;
}
Example 25
Project: AndroidJAXBLib-master  File: DocUtils.java View source code
public static String getStringFromDoc(org.w3c.dom.Document doc) {
    try {
        DOMSource domSource = new DOMSource(doc);
        StringWriter writer = new StringWriter();
        StreamResult result = new StreamResult(writer);
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = tf.newTransformer();
        transformer.transform(domSource, result);
        writer.flush();
        return writer.toString();
    } catch (TransformerException ex) {
        ex.printStackTrace();
        return null;
    }
}
Example 26
Project: apigee-deploy-maven-plugin-master  File: PackageConfigurerTest.java View source code
public void testConfigurePackage() throws Exception {
    File configFile = new File(getClass().getClassLoader().getResource("configTest/config.json").toURI());
    PackageConfigurer.configurePackage("test", configFile);
    File policyFile = new File(getClass().getClassLoader().getResource("configTest/target/apiproxy/policies/QuotaPolicy.xml").toURI());
    Document xmlDocument = fileReader.getXMLDocument(policyFile);
    javax.xml.xpath.XPathFactory factory = javax.xml.xpath.XPathFactory.newInstance();
    javax.xml.xpath.XPath xpath = factory.newXPath();
    assertEquals("2", xpath.evaluate("/Quota/Interval", xmlDocument));
}
Example 27
Project: claudia-master  File: ddddd.java View source code
/**
	 * @param args
	 */
public static void main(String[] args) {
    // TODO Auto-generated method stub
    String responseXml = "./src/test/resources/job-00009.xml";
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = null;
    try {
        db = dbf.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    }
    Document doc = null;
    try {
        doc = db.parse(responseXml);
    } catch (SAXException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    System.out.println(PaasUtils.tooString(doc));
    NodeList tasks = doc.getElementsByTagName("status");
    if (tasks.getLength() != 0 && ((Element) tasks.item(0)).getAttribute("status") != null) {
        {
            System.out.println(((Element) tasks.item(0)).getNodeName() + "  " + ((Element) tasks.item(0)).getFirstChild().getNodeValue());
        }
    }
}
Example 28
Project: coding2017-master  File: XmlUtil.java View source code
public static Document getDocument(String fileName) {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    try {
        DocumentBuilder builder = factory.newDocumentBuilder();
        //读当�文件路径下的
        Document doc = builder.parse(fileName);
        //去掉document的空格
        doc.normalize();
        return doc;
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    } catch (SAXException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}
Example 29
Project: Crawer-master  File: ParseXML.java View source code
public static String ParsingXML(String in) throws Exception {
    //校验
    if (in == null || "".equals(in))
        return "";
    //获�顶级element
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    org.w3c.dom.Document document = builder.parse(new ByteArrayInputStream(in.getBytes()));
    return "";
}
Example 30
Project: crawljax-master  File: ScriptComparator.java View source code
@Override
public String normalize(String dom) {
    Document orgDoc;
    try {
        orgDoc = DomUtils.asDocument(dom);
        orgDoc = DomUtils.removeScriptTags(orgDoc);
        return DomUtils.getDocumentToString(orgDoc);
    } catch (IOException e) {
        LOGGER.warn("Could not perform DOM comparison", e);
        return dom;
    }
}
Example 31
Project: default-workspace-generator-master  File: WidgetItem.java View source code
@Override
public Element toXML(Document doc) throws ParserConfigurationException {
    Element appwidget = doc.createElement("appwidget");
    appwidget.setAttribute(PACKAGE_NAME, getItemPackage());
    appwidget.setAttribute(CLASS_NAME, getItemLaunchable());
    appwidget.setAttribute(LAUNCHER_SCREEN, String.valueOf(getHomeScreenNumber()));
    appwidget.setAttribute(X, "");
    appwidget.setAttribute(Y, "");
    appwidget.setAttribute(SPAN_X, "");
    appwidget.setAttribute(SPAN_Y, "");
    return appwidget;
}
Example 32
Project: Inside_Android_Testing-master  File: TestUtil.java View source code
public static String asString(Document doc) {
    try {
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        StringWriter writer = new StringWriter();
        transformer.transform(new DOMSource(doc), new StreamResult(writer));
        return writer.toString();
    } catch (TransformerException e) {
        throw new RuntimeException(e);
    }
}
Example 33
Project: jentrata-master  File: AbstractXPathPredicate.java View source code
@Override
public boolean matches(Exchange exchange) {
    try {
        Document body = exchange.getIn().getBody(Document.class);
        if (matches(body, expression)) {
            return true;
        } else {
            exchange.getIn().setHeader(EbmsConstants.VALIDATION_ERROR_DESC, getValidationError());
        }
    } catch (Exception ex) {
        exchange.getIn().setHeader(EbmsConstants.VALIDATION_ERROR_DESC, name + " validation failed:" + ex);
    }
    return false;
}
Example 34
Project: jetstream-master  File: SpringStringSerializer.java View source code
public void serialize(Element containingElement, Object object) throws MarshalException {
    Document d = containingElement.getOwnerDocument();
    String value = object + "";
    String name = containingElement.getNodeName();
    if (object == null || name.equals("list") || name.equals("set") || name.equals("entry")) {
        Element element = d.createElement(object == null ? "null" : "value");
        containingElement.appendChild(element);
        if (object != null) {
            element.appendChild(d.createTextNode(value));
        }
    } else {
        containingElement.setAttribute("value", value);
    }
}
Example 35
Project: jphp-master  File: XmlExtension.java View source code
@Override
public void onRegister(CompileScope scope) {
    registerWrapperClass(scope, Node.class, WrapDomNode.class);
    registerWrapperClass(scope, Element.class, WrapDomElement.class);
    registerWrapperClass(scope, NodeList.class, WrapDomNodeList.class);
    registerWrapperClass(scope, Document.class, WrapDomDocument.class);
    registerClass(scope, WrapXmlProcessor.class);
}
Example 36
Project: JSqlIde-master  File: DefaultsNode.java View source code
public Node getNode(Document doc) {
    DocumentImpl impl = (DocumentImpl) doc;
    ElementImpl element = new ElementImpl(impl, getNodeName());
    if (defaultSource != null)
        element.appendChild(defaultSource.getNode(doc));
    if (defaultDestination != null)
        element.appendChild(defaultDestination.getNode(doc));
    return element;
}
Example 37
Project: juxy-master  File: UTestDOMUtil.java View source code
public void testGetInnerTextComplexDOM() throws SAXException {
    Document doc = DOMUtil.parse("" + "<root>a complex\n" + "<em>text</em> with a HTML like list:" + "<ol>" + "   <li>item1</li>" + "   <li>item2</li>" + "</ol>" + "</root>");
    assertEquals("a complex text with a HTML like list: item1 item2", StringUtil.normalizeAll(DOMUtil.innerText(doc)));
}
Example 38
Project: noodlesmaster-master  File: XmlUtil.java View source code
public static String getXPathItemText(Document doc, XPath xpath, String query) throws XPathExpressionException {
    if (doc == null || xpath == null || query == null) {
        return null;
    }
    Node node = (Node) xpath.evaluate(query, doc, XPathConstants.NODE);
    String text = null;
    if (node != null) {
        text = node.getNodeValue();
        if (text != null) {
            text = text.trim();
        }
    }
    return text;
}
Example 39
Project: org.eclipse.rap-master  File: EmployeeWriter.java View source code
public void save() {
    Document document = employees.getOwnerDocument();
    Element newEmployee = document.createElement(EntityConstants.EMPLOYEE);
    newEmployee.setAttribute(EntityConstants.ID, employee.getId());
    newEmployee.setAttribute(EntityConstants.FIRST_NAME, employee.getFirstName());
    newEmployee.setAttribute(EntityConstants.LAST_NAME, employee.getLastName());
    employees.appendChild(newEmployee);
}
Example 40
Project: pair-java-master  File: HtmlParserUtil.java View source code
public static Document getHtmlDocumentModel(String htmlContent) {
    try {
        TagNode tagNode = new HtmlCleaner().clean(htmlContent);
        Document doc;
        try {
            doc = new DomSerializer(new CleanerProperties()).createDOM(tagNode);
        } catch (ParserConfigurationException e) {
            throw new RuntimeException(e);
        }
        return doc;
    } catch (RuntimeException rte) {
        return null;
    }
}
Example 41
Project: platypus-master  File: Source2XmlDom.java View source code
public static Document transform(String source) throws SAXException, IOException, ParserConfigurationException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    try {
        factory.setFeature("http://apache.org/xml/features/dom/defer-node-expansion", false);
    } catch (ParserConfigurationException ex) {
    }
    DocumentBuilder builder = factory.newDocumentBuilder();
    return builder.parse(new InputSource(new StringReader(source)));
}
Example 42
Project: Resteasy-master  File: XXEBasicResource.java View source code
@Consumes("application/xml")
@POST
public String doPost(Document doc) {
    Node node = doc.getDocumentElement();
    logger.info("name: " + node.getNodeName());
    NodeList children = doc.getDocumentElement().getChildNodes();
    node = children.item(0);
    logger.info("name: " + node.getNodeName());
    children = node.getChildNodes();
    node = children.item(0);
    logger.info("name: " + node.getNodeName());
    children = node.getChildNodes();
    logger.info(node.getNodeValue());
    return node.getNodeValue();
}
Example 43
Project: scaleDOM-master  File: MinimalOutputCallback.java View source code
@Override
public void nodeTraversed(final Document doc, final Node node, final int level) {
    if (!(node instanceof Element)) {
        return;
    }
    if (level < maxLevelForDetailedOutput) {
        if (!lastNodeWasDetailed) {
            System.out.println();
            lastNodeWasDetailed = true;
        }
        System.out.println(level + "-" + node.getNodeName());
    } else {
        if (!lastNodeWasDetailed) {
            System.out.print('-');
        }
        System.out.print(level);
        lastNodeWasDetailed = false;
    }
}
Example 44
Project: Scute-master  File: XmlUtils.java View source code
// xmlns:foaf="http://xmlns.com/foaf/0.1/"
//	Document doc = editorPane.getDocument();
//	String text = doc.getText(0, doc.getLength());
public static org.w3c.dom.Document toXMLDocument(String text) {
    try {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        dbf.setValidating(false);
        DocumentBuilder db = dbf.newDocumentBuilder();
        return db.parse(text);
    } catch (Exception exception) {
        Log.exception(exception);
    }
    return null;
}
Example 45
Project: siu-master  File: RequestParser.java View source code
public HouseBookExtractionRequest parseRequest(byte[] data) {
    try {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        DocumentBuilder documentBuilder = dbf.newDocumentBuilder();
        InputSource is = new InputSource(new StringReader(new String(data, "UTF-8")));
        Document doc = documentBuilder.parse(is);
        return XmlTypes.elementToBean(doc.getDocumentElement(), HouseBookExtractionRequest.class);
    } catch (Exception e) {
        logger.log(Level.SEVERE, e.getMessage(), e);
        return null;
    }
}
Example 46
Project: tcx2nikeplus-master  File: Upload.java View source code
public static void main(String[] args) {
    String nikePlusEmail = args[0];
    String nikePlusPassword = args[1];
    File tcxFile = new File(args[2]);
    File gpxFile = (args.length > 3) ? new File(args[3]) : null;
    try {
        DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document runXML = documentBuilder.parse(tcxFile);
        Document gpxXML = (gpxFile == null) ? null : documentBuilder.parse(gpxFile);
        NikeActivityData nikeActivityData = new NikeActivityData(runXML, gpxXML);
        NikePlus.fullSync(nikePlusEmail, nikePlusPassword.toCharArray(), nikeActivityData);
    } catch (Throwable t) {
        t.printStackTrace();
    }
}
Example 47
Project: TestingStuff-master  File: XMLUtil.java View source code
public static Document toDocument(InputStream inputStream) {
    try {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document document = db.parse(inputStream);
        return document;
    } catch (ParserConfigurationException e) {
        XMLUtil.log("ParserConfigurationException", e);
    } catch (SAXException e) {
        XMLUtil.log("SAXException", e);
    } catch (IOException e) {
        XMLUtil.log("IOException", e);
    }
    return null;
}
Example 48
Project: totallylazy-master  File: XPathLookupsTest.java View source code
@Test
public void supportsLookups() throws Exception {
    Map<String, String> data = new HashMap<String, String>() {

        {
            put("Dan", "Jorge");
        }
    };
    XPathLookups.setLookup("name", Maps.functions.getFrom(data));
    Document document = document("<user>Dan</user>");
    assertThat(xpath().evaluate("tl:lookup('name', //user)", document), equalTo("Jorge"));
}
Example 49
Project: Ak47-master  File: XmlUtil.java View source code
/**
     * document(w3c.dom.Document) to string(XML Text)
     * 
     * 
     * @param document
     * @return
     * @throws TransformerException
     * @throws UnsupportedEncodingException
     */
public static String document2String(Document document) throws TransformerException, UnsupportedEncodingException {
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    DOMSource source = new DOMSource(document);
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    StreamResult result = new StreamResult(bos);
    transformer.transform(source, result);
    return bos.toString(Ak47Constants.DEFAULT_ENCODING);
}
Example 50
Project: batik-master  File: DoubleString.java View source code
public TestReport runImpl() throws Exception {
    // Get a DOMImplementation
    DOMImplementation domImpl = GenericDOMImplementation.getDOMImplementation();
    // Create an instance of org.w3c.dom.Document
    Document document = domImpl.createDocument(null, "svg", null);
    SVGGraphics2D g = new SVGGraphics2D(document);
    Rectangle2D r = new Rectangle2D.Float(0.5f, 0.5f, 2.33f, 2.33f);
    g.fill(r);
    return reportSuccess();
}
Example 51
Project: jbosstools-arquillian-master  File: AddDependencies.java View source code
/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.eclipse.m2e.core.ui.internal.editing.PomEdits.Operation#process
	 * (org.w3c.dom.Document)
	 */
public void process(Document document) {
    if (dependencies == null || dependencies.size() <= 0) {
        return;
    }
    Element root = document.getDocumentElement();
    Element dependenciesEl = getChild(root, PomEdits.DEPENDENCIES);
    for (Dependency dependency : dependencies) {
        String version = ArquillianUtility.getDependencyVersion(mavenProject, dependency.getGroupId(), dependency.getArtifactId());
        if (version == null) {
            addOrUpdateDependency(dependenciesEl, dependency.getGroupId(), dependency.getArtifactId(), dependency.getVersion(), dependency.getType(), dependency.getScope(), dependency.getClassifier());
        }
    }
}
Example 52
Project: m2e-core-master  File: RemoveDependencyOperation.java View source code
/* (non-Javadoc)
   * @see org.eclipse.m2e.core.ui.internal.editing.PomEdits.Operation#process(org.w3c.dom.Document)
   */
public void process(Document document) {
    Element dependencyElement = PomHelper.findDependency(document, dependency);
    if (dependencyElement != null) {
        Element dependencies = findChild(document.getDocumentElement(), DEPENDENCIES);
        removeChild(dependencies, dependencyElement);
        // Remove dependencies element if it is empty
        removeIfNoChildElement(dependencies);
    }
}
Example 53
Project: skalli-master  File: DataMigrationMavenModule.java View source code
/* (non-Javadoc)
     * @see org.eclipse.skalli.model.ext.DataMigration#migrate(org.w3c.dom.Document)
     */
@Override
public void migrate(Document doc) throws MigrationException {
    //$NON-NLS-1$
    NodeList nodes = doc.getElementsByTagName("org.eclipse.skalli.model.ext.maven.MavenCoordinate");
    for (int i = 0; i < nodes.getLength(); i++) {
        //$NON-NLS-1$
        doc.renameNode(nodes.item(i), null, "org.eclipse.skalli.model.ext.maven.MavenModule");
    }
}
Example 54
Project: spring-ide-master  File: RepositoriesReferenceableElementLocator.java View source code
/*
	 * (non-Javadoc)
	 * @see org.springframework.ide.eclipse.beans.ui.editor.namespaces.DefaultReferenceableElementsLocator#getReferenceableElements(org.w3c.dom.Document, org.eclipse.core.resources.IFile)
	 */
@Override
public Map<String, Set<Node>> getReferenceableElements(Document document, IFile file) {
    Map<String, Set<Node>> result = super.getReferenceableElements(document, file);
    NodeList childNodes = document.getDocumentElement().getChildNodes();
    Node springDataElement = null;
    for (int i = 0; i < childNodes.getLength(); i++) {
        Node node = childNodes.item(i);
        if (SpringDataUtils.isSpringDataElement(node)) {
            springDataElement = node;
            break;
        }
    }
    if (file != null && file.exists()) {
        for (String name : SpringDataUtils.getRepositoryBeanIds(file.getProject())) {
            Set<Node> nodes = result.get(name);
            if (nodes == null) {
                nodes = new HashSet<Node>();
                result.put(name, nodes);
            }
            nodes.add(springDataElement);
        }
    }
    return result;
}
Example 55
Project: vex-master  File: DOMSynchronizationTest.java View source code
public void testRootElement() throws Exception {
    org.w3c.dom.Document domDocument = getDOM();
    VEXDocument vexDocument = new Document(domDocument);
    VEXElement rootElement = vexDocument.getRootElement();
    assertEquals("Root element is incorrect.", "chapter", rootElement.getName());
    assertEquals("Synchronization in elements incorrect.", rootElement.getName(), domDocument.getDocumentElement().getNodeName());
    assertEquals("Root element's dom incorrect.", rootElement.getElement(), domDocument.getDocumentElement());
}
Example 56
Project: ibatis-2-master  File: GenericProbe.java View source code
/**
   * Gets an object from a Map or bean
   *
   * @param object
   *          - the object to probe
   * @param name
   *          - the name of the property (or map entry)
   * @return The value of the property (or map entry)
   * @see com.ibatis.common.beans.BaseProbe#getObject(java.lang.Object, java.lang.String)
   */
public Object getObject(Object object, String name) {
    if (object instanceof org.w3c.dom.Document) {
        return DOM_PROBE.getObject(object, name);
    } else if (object instanceof List) {
        return BEAN_PROBE.getIndexedProperty(object, name);
    } else if (object instanceof Object[]) {
        return BEAN_PROBE.getIndexedProperty(object, name);
    } else if (object instanceof char[]) {
        return BEAN_PROBE.getIndexedProperty(object, name);
    } else if (object instanceof boolean[]) {
        return BEAN_PROBE.getIndexedProperty(object, name);
    } else if (object instanceof byte[]) {
        return BEAN_PROBE.getIndexedProperty(object, name);
    } else if (object instanceof double[]) {
        return BEAN_PROBE.getIndexedProperty(object, name);
    } else if (object instanceof float[]) {
        return BEAN_PROBE.getIndexedProperty(object, name);
    } else if (object instanceof int[]) {
        return BEAN_PROBE.getIndexedProperty(object, name);
    } else if (object instanceof long[]) {
        return BEAN_PROBE.getIndexedProperty(object, name);
    } else if (object instanceof short[]) {
        return BEAN_PROBE.getIndexedProperty(object, name);
    } else {
        return BEAN_PROBE.getObject(object, name);
    }
}
Example 57
Project: shtaobatis-master  File: GenericProbe.java View source code
/**
   * Gets an object from a Map or bean
   *
   * @param object - the object to probe
   * @param name   - the name of the property (or map entry)
   * @return The value of the property (or map entry)
   * @see com.ibatis.common.beans.BaseProbe#getObject(java.lang.Object, java.lang.String)
   */
public Object getObject(Object object, String name) {
    if (object instanceof org.w3c.dom.Document) {
        return DOM_PROBE.getObject(object, name);
    } else if (object instanceof List) {
        return BEAN_PROBE.getIndexedProperty(object, name);
    } else if (object instanceof Object[]) {
        return BEAN_PROBE.getIndexedProperty(object, name);
    } else if (object instanceof char[]) {
        return BEAN_PROBE.getIndexedProperty(object, name);
    } else if (object instanceof boolean[]) {
        return BEAN_PROBE.getIndexedProperty(object, name);
    } else if (object instanceof byte[]) {
        return BEAN_PROBE.getIndexedProperty(object, name);
    } else if (object instanceof double[]) {
        return BEAN_PROBE.getIndexedProperty(object, name);
    } else if (object instanceof float[]) {
        return BEAN_PROBE.getIndexedProperty(object, name);
    } else if (object instanceof int[]) {
        return BEAN_PROBE.getIndexedProperty(object, name);
    } else if (object instanceof long[]) {
        return BEAN_PROBE.getIndexedProperty(object, name);
    } else if (object instanceof short[]) {
        return BEAN_PROBE.getIndexedProperty(object, name);
    } else {
        return BEAN_PROBE.getObject(object, name);
    }
}
Example 58
Project: muikku-master  File: FieldElementsHandler.java View source code
private Element wrapWithObjectElement(org.w3c.dom.Document ownerDocument, Element[] contents, FieldMeta fieldMeta) {
    ObjectMapper objectMapper = new ObjectMapper();
    Element objectElement = ownerDocument.createElement("object");
    objectElement.setAttribute("type", fieldMeta.getType());
    Element paramTypeElement = ownerDocument.createElement("param");
    paramTypeElement.setAttribute("name", "type");
    paramTypeElement.setAttribute("value", "application/json");
    Element paramContentElement = ownerDocument.createElement("param");
    paramContentElement.setAttribute("name", "content");
    try {
        paramContentElement.setAttribute("value", objectMapper.writeValueAsString(fieldMeta));
    } catch (DOMExceptionIOException |  e) {
        e.printStackTrace();
    }
    objectElement.appendChild(paramTypeElement);
    objectElement.appendChild(paramContentElement);
    for (Element content : contents) {
        objectElement.appendChild(content);
    }
    return objectElement;
}
Example 59
Project: splunk-sdk-java-master  File: ModularInputTestCase.java View source code
/**
     * Open a resource from the Splunk SDK for Java project and parse it into an org.w3c.dom.Document object.
     *
     * @param path a path relative to the test directory of the SDK.
     * @return an org.w3c.dom.Document object containing the parsed XML.
     */
public Document resourceToXmlDocument(String path) {
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    documentBuilderFactory.setIgnoringElementContentWhitespace(true);
    DocumentBuilder documentBuilder = null;
    try {
        documentBuilder = documentBuilderFactory.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        throw new AssertionError("Parser configuration failed: " + e.toString());
    }
    InputStream resource = SDKTestCase.openResource(path);
    try {
        Document doc = documentBuilder.parse(resource);
        return doc;
    } catch (SAXException e) {
        throw new AssertionError("Could not parse XML file at " + path);
    } catch (IOException e) {
        throw new AssertionError("Could not read XML file at " + path);
    }
}
Example 60
Project: abdera-master  File: SecurityBase.java View source code
protected org.w3c.dom.Document fomToDom(Document doc, SecurityOptions options) {
    org.w3c.dom.Document dom = null;
    if (doc != null) {
        try {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            doc.writeTo(out);
            ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            dbf.setValidating(false);
            dbf.setNamespaceAware(true);
            DocumentBuilder db = dbf.newDocumentBuilder();
            dom = db.parse(in);
        } catch (Exception e) {
        }
    }
    return dom;
}
Example 61
Project: Consent2Share-master  File: PolicyValidationUtils.java View source code
public static boolean validate(final byte[] policy) {
    boolean isValid = false;
    try {
        final String policyString = new String(policy, DOMUtils.DEFAULT_ENCODING);
        final Document policyDoc = DOMUtils.bytesToDocument(policy);
        final Evaluatable policyObj = PolicyMarshaller.unmarshal(new ByteArrayInputStream(policy));
        Assert.notNull(policyString);
        Assert.notNull(policyObj);
        Assert.notNull(policyDoc);
        isValid = true;
    } catch (final Exception e) {
        LOGGER.debug(e.getMessage(), e);
    }
    return isValid;
}
Example 62
Project: cryptoapplet-master  File: DigestMethod.java View source code
/**
	 * @see es.mityc.firmaJava.libreria.xades.elementos.AbstractXMLElement#createElement(org.w3c.dom.Document)
	 */
@Override
protected Element createElement(Document doc) throws InvalidInfoNodeException {
    if (algorithm == null)
        throw new InvalidInfoNodeException("Información insuficiente para escribir elemento DigestMethod");
    Element res = doc.createElementNS(ConstantesXADES.SCHEMA_DSIG, namespaceXDsig + ":" + ConstantesXADES.DIGEST_METHOD);
    res.setAttributeNS(null, ConstantesXADES.ALGORITHM, algorithm);
    return res;
}
Example 63
Project: freelib-utils-master  File: FileUtilsTest.java View source code
/**
     * Sets up a directory structure used for testing.
     */
@BeforeClass
public static void setUpBeforeClass() {
    final SimpleDateFormat formatter = new SimpleDateFormat(FileUtils.DATE_FORMAT);
    final File tf0 = new File("src/test/resources/test_folder");
    final File tf1 = new File(tf0, "test_folder");
    final File tf1_1 = new File(tf1, "test_file1.txt");
    final File tf1_2 = new File(tf1, "test_file2.txt");
    final File tf2 = new File(tf0, "test_folder2");
    final File tf2_tf1 = new File(tf2, "test_folder");
    final File tf2_tf1_1 = new File(tf2_tf1, "test_file1.txt");
    final File tf2_1 = new File(tf2, "test_file1.txt");
    final File tf0_1 = new File(tf0, "test_file1.txt");
    final Element root = new Element("dir");
    root.addAttribute(new Attribute("path", tf0.getAbsolutePath()));
    root.addAttribute(new Attribute("modified", formatter.format(new Date(tf0.lastModified()))));
    root.addAttribute(new Attribute("permissions", "rw"));
    final Element tFolder1 = new Element("dir");
    tFolder1.addAttribute(new Attribute("path", tf1.getAbsolutePath()));
    tFolder1.addAttribute(new Attribute("modified", formatter.format(new Date(tf1.lastModified()))));
    tFolder1.addAttribute(new Attribute("permissions", "rw"));
    final Element tFolder1File1 = new Element("file");
    tFolder1File1.addAttribute(new Attribute("path", tf1_1.getAbsolutePath()));
    tFolder1File1.addAttribute(new Attribute("modified", formatter.format(new Date(tf1_1.lastModified()))));
    tFolder1File1.addAttribute(new Attribute("permissions", "rw"));
    final Element tFolder1File2 = new Element("file");
    tFolder1File2.addAttribute(new Attribute("path", tf1_2.getAbsolutePath()));
    tFolder1File2.addAttribute(new Attribute("modified", formatter.format(new Date(tf1_2.lastModified()))));
    tFolder1File2.addAttribute(new Attribute("permissions", "rw"));
    final Element tFolder2 = new Element("dir");
    tFolder2.addAttribute(new Attribute("path", tf2.getAbsolutePath()));
    tFolder2.addAttribute(new Attribute("modified", formatter.format(new Date(tf2.lastModified()))));
    tFolder2.addAttribute(new Attribute("permissions", "rw"));
    final Element tFolder2tFolder1 = new Element("dir");
    tFolder2tFolder1.addAttribute(new Attribute("path", tf2_tf1.getAbsolutePath()));
    tFolder2tFolder1.addAttribute(new Attribute("modified", formatter.format(new Date(tf2_tf1.lastModified()))));
    tFolder2tFolder1.addAttribute(new Attribute("permissions", "rw"));
    final Element tFolder2tFolder1File1 = new Element("file");
    final Date tf2_tf1_1_date = new Date(tf2_tf1_1.lastModified());
    tFolder2tFolder1File1.addAttribute(new Attribute("path", tf2_tf1_1.getAbsolutePath()));
    tFolder2tFolder1File1.addAttribute(new Attribute("modified", formatter.format(tf2_tf1_1_date)));
    tFolder2tFolder1File1.addAttribute(new Attribute("permissions", "rw"));
    final Element tFolder2File1 = new Element("file");
    tFolder2File1.addAttribute(new Attribute("path", tf2_1.getAbsolutePath()));
    tFolder2File1.addAttribute(new Attribute("modified", formatter.format(new Date(tf2_1.lastModified()))));
    tFolder2File1.addAttribute(new Attribute("permissions", "rw"));
    final Element tFolder0File1 = new Element("file");
    tFolder0File1.addAttribute(new Attribute("path", tf0_1.getAbsolutePath()));
    tFolder0File1.addAttribute(new Attribute("modified", formatter.format(new Date(tf0_1.lastModified()))));
    tFolder0File1.addAttribute(new Attribute("permissions", "rw"));
    EXPECTED = new Document(root);
    root.appendChild(tFolder1);
    tFolder1.appendChild(tFolder1File1);
    tFolder1.appendChild(tFolder1File2);
    tFolder2tFolder1.appendChild(tFolder2tFolder1File1);
    tFolder2.appendChild(tFolder2tFolder1);
    tFolder2.appendChild(tFolder2File1);
    root.appendChild(tFolder2);
    root.appendChild(tFolder0File1);
}
Example 64
Project: jeffaschenk-commons-master  File: XmlUtilities.java View source code
//---------------------------
// Public Methods
//---------------------------
/**
     * Returns a org.w3c.dom.Document given an input stream.
     *
     * @param inStream an input stream for an xml string/file/etc
     * @return a org.w3c.dom.Document
     */
public static Document getDocument(InputStream inStream) throws XmlException {
    Document doc = null;
    try {
        DocumentBuilder parser;
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        // Turn off the conversion validation and namespace-awareness
        // Namespace-awareness is turned off now so that we can process
        // XML that has namespacing, but no corresponding schema (such as
        // with Junipers 'junos' name
        factory.setNamespaceAware(true);
        factory.setValidating(false);
        factory.setIgnoringComments(false);
        parser = factory.newDocumentBuilder();
        doc = parser.parse(inStream);
    } catch (Exception e) {
        throw new XmlException("Could not convert stream to an xml document.", e);
    }
    return (doc);
}
Example 65
Project: seqware-master  File: XmlTools.java View source code
private static Document getDocument(String string) throws ParserConfigurationException, IOException, SAXException {
    Document document;
    if (string == null) {
        Logger logger = LoggerFactory.getLogger(XmlTools.class);
        logger.debug("String is :" + string);
        return null;
    }
    // UTF-8 Encoded strings occasionally have silly byte-order marks
    // Solution from http://mark.koli.ch/2009/02/resolving-orgxmlsaxsaxparseexception-content-is-not-allowed-in-prolog.html
    string = string.trim().replaceFirst("^([\\W]+)<", "<");
    document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new ByteArrayInputStream(string.getBytes()));
    return document;
}
Example 66
Project: WebWorks-master  File: PIMExtension.java View source code
/**
     * @see net.rim.device.api.web.WidgetExtension#loadFeature(java.lang.String, java.lang.String, org.w3c.dom.Document,
     *      net.rim.device.api.script.ScriptEngine)
     */
public void loadFeature(final String feature, final String version, final Document doc, final ScriptEngine scriptEngine) throws Exception {
    Object obj = null;
    if (feature.equals(CategoryNamespace.NAME)) {
        obj = new CategoryNamespace();
    } else if (feature.equals(RecurrenceConstructor.NAME)) {
        obj = new RecurrenceConstructor();
    } else if (feature.equals(ReminderConstructor.NAME)) {
        obj = new ReminderConstructor();
    } else if (feature.equals(AttendeeConstructor.NAME)) {
        obj = new AttendeeConstructor();
    } else if (feature.equals(AppointmentConstructor.NAME)) {
        obj = new AppointmentConstructor();
    } else if (feature.equals(AddressConstructor.NAME)) {
        obj = new AddressConstructor();
    } else if (feature.equals(ContactConstructor.NAME)) {
        obj = new ContactConstructor();
    } else if (feature.equals(MemoConstructor.NAME)) {
        obj = new MemoConstructor();
    } else if (feature.equals(TaskConstructor.NAME)) {
        obj = new TaskConstructor();
    }
    if (obj != null) {
        scriptEngine.addExtension(feature, obj);
    }
}
Example 67
Project: eXist-1.4.x-master  File: DocumentImpl.java View source code
/*
     * (non-Javadoc)
     * 
     * @see org.w3c.dom.Document#getImplementation()
     */
public DOMImplementation getImplementation() {
    return new DOMImplementation() {

        public Document createDocument(String namespaceURI, String qualifiedName, DocumentType doctype) throws DOMException {
            return null;
        }

        public DocumentType createDocumentType(String qualifiedName, String publicId, String systemId) throws DOMException {
            return null;
        }

        public Object getFeature(String feature, String version) {
            return null;
        }

        public boolean hasFeature(String feature, String version) {
            return "XML".equals(feature) && ("1.0".equals(version) || "2.0".equals(version));
        }
    };
}
Example 68
Project: aetheria-master  File: XMLfromURL.java View source code
/**
	 * Obtains an XML document (will be used for catalogs) from a URL.
	 * @param catalogURL
	 * @return
	 * @throws IOException
	 * @throws TransformerException
	 */
public static Document getXMLFromURL(URL catalogURL) throws IOException, TransformerException {
    if (catalogURL == null)
        throw new IOException("Null catalog URL passed");
    InputStream is = catalogURL.openStream();
    StreamSource s = new StreamSource(is, catalogURL.toString());
    Transformer t = TransformerFactory.newInstance().newTransformer();
    DOMResult r = new DOMResult();
    t.transform(s, r);
    return ((Document) r.getNode());
}
Example 69
Project: amoeba-master  File: XmlToSqlList.java View source code
public static List<String> executeXml2List(InputStream stream) {
    // ÉùÃ÷xmlÎļþ
    Document doc;
    List<String> tree = new ArrayList<String>();
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setIgnoringComments(true);
    dbf.setIgnoringElementContentWhitespace(true);
    try {
        DocumentBuilder db = dbf.newDocumentBuilder();
        doc = db.parse(stream);
        NodeList tagNodes = doc.getElementsByTagName("sql");
        for (int i = 0; i < tagNodes.getLength(); i++) {
            tree.add(tagNodes.item(i).getTextContent().trim());
        }
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    } catch (SAXException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return tree;
}
Example 70
Project: AndroidAsync-master  File: DocumentParser.java View source code
@Override
public Future<Document> parse(DataEmitter emitter) {
    return new ByteBufferListParser().parse(emitter).then(new TransformFuture<Document, ByteBufferList>() {

        @Override
        protected void transform(ByteBufferList result) throws Exception {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            setComplete(db.parse(new ByteBufferListInputStream(result)));
        }
    });
}
Example 71
Project: AndroidBinding-master  File: RegisterApplicationTask.java View source code
@Override
public void execute() throws BuildException {
    try {
        File file = new File(mDir, "AndroidManifest.xml");
        Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new File(mDir, "AndroidManifest.xml"));
        Element appNode = (Element) doc.getElementsByTagName("application").item(0);
        appNode.setAttribute("android:name", mAppClassName);
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        DOMSource source = new DOMSource(doc);
        StreamResult result = new StreamResult(file);
        transformer.transform(source, result);
        log("Manifest <application> modified");
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Example 72
Project: Aorm-Eclipse-Plugin-master  File: W3CDOM.java View source code
/**
     * @param args
     */
public static void main(String[] args) throws Exception {
    DocumentBuilderFactory fac = DocumentBuilderFactory.newInstance();
    fac.setIgnoringElementContentWhitespace(true);
    Document doc = fac.newDocumentBuilder().parse(new InputSource(new StringReader("<a><b a=\"d\">bb</b> dd</a>")));
    Element e = doc.getDocumentElement();
    System.out.println(e.getTextContent());
    DOMSource source = new DOMSource(e);
    TransformerFactory transFactory = TransformerFactory.newInstance();
    ByteArrayOutputStream oos = new ByteArrayOutputStream();
    Result result = new StreamResult(oos);
    // DOMResult result2 = new DOMResult();
    Transformer transformer = transFactory.newTransformer();
    transformer.transform(source, result);
    System.out.println(oos.toString());
}
Example 73
Project: ApprovalTests.Java-master  File: XMLUtilsTest.java View source code
public void testXML() throws Exception {
    // String xml = "<?xml version=\"1.0\" ?><QBXML><QBXMLMsgsRs><ItemQueryRs requestID=\"2\" statusCode=\"0\" statusSeverity=\"Info\" statusMessage=\"Status OK\">1</ItemQueryRs></QBXMLMsgsRs></QBXML>";
    String xml = "<?xml version=\"1.0\" ?>\n" + "<QBXML>\n" + "<QBXMLMsgsRs>\n" + "<HostQueryRs statusCode=\"0\" statusSeverity=\"Info\" statusMessage=\"Status OK\">\n" + "<HostRet>\n" + "<ProductName>superpro</ProductName>\n" + "<MajorVersion>16</MajorVersion>\n" + "<MinorVersion>0</MinorVersion>\n" + "<SupportedQBXMLVersion>1.0</SupportedQBXMLVersion>\n" + "<SupportedQBXMLVersion>1.1</SupportedQBXMLVersion>\n" + "<SupportedQBXMLVersion>2.0</SupportedQBXMLVersion>\n" + "<SupportedQBXMLVersion>2.1</SupportedQBXMLVersion>\n" + "<SupportedQBXMLVersion>3.0</SupportedQBXMLVersion>\n" + "<SupportedQBXMLVersion>4.0</SupportedQBXMLVersion>\n" + "<SupportedQBXMLVersion>4.1</SupportedQBXMLVersion>\n" + "<SupportedQBXMLVersion>5.0</SupportedQBXMLVersion>\n" + "</HostRet>\n" + "</HostQueryRs>\n" + "</QBXMLMsgsRs>\n" + "</QBXML>\n" + "";
    Document document = XMLUtils.parseXML(xml);
    assertEquals(true, document.hasChildNodes());
    //    assertNotNull(XmlExtractorUtil.traverseToTag("ItemQueryRs", document));
    assertNotNull(XmlExtractorUtil.traverseToTag("HostRet", document));
}
Example 74
Project: arondor-common-reflection-master  File: W3CXStream2ObjectDefinitionConverter.java View source code
@Override
public ObjectConfiguration parse(String xmlString) {
    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document rootDocument = builder.parse(new ByteArrayInputStream(xmlString.getBytes()));
        Element rootElement = rootDocument.getDocumentElement();
        LOG.debug("rootElement=" + rootElement.getNodeName());
        return parseObject(rootElement, null);
    } catch (ParserConfigurationException e) {
        throw new RuntimeException("Exception !", e);
    } catch (SAXException e) {
        throw new RuntimeException("Exception !", e);
    } catch (IOException e) {
        throw new RuntimeException("Exception !", e);
    }
}
Example 75
Project: BACKUP_FROM_SVN-master  File: DefaultXmlWriter.java View source code
public void write(Document doc, OutputStream outputStream) throws IOException {
    try {
        TransformerFactory factory = TransformerFactory.newInstance();
        try {
            factory.setAttribute("indent-number", 4);
        } catch (Exception e) {
            ;
        }
        Transformer transformer = factory.newTransformer();
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        //need to nest outputStreamWriter to get around JDK 5 bug.  See http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6296446
        transformer.transform(new DOMSource(doc), new StreamResult(new OutputStreamWriter(outputStream, "utf-8")));
    } catch (TransformerException e) {
        throw new IOException(e.getMessage());
    }
}
Example 76
Project: Blogs-master  File: PublicKeyXmlSignatureValidation.java View source code
/**
     * Validate the XMLSignature contained in the given Document using the public key
     * @param document
     * @return true if the signature pass validation, false otherwise
     * @throws MarshalException
     * @throws XMLSignatureException
     */
public boolean validate(Document document) throws MarshalException, XMLSignatureException {
    NodeList nodes = document.getElementsByTagName("Signature");
    if (nodes.getLength() == 0) {
        throw new XMLSignatureException("The document does not seem to contain an XmlSignature node.");
    }
    Node signatureNode = nodes.item(0);
    DOMValidateContext validateContext = new DOMValidateContext(publicKey, signatureNode);
    return super.validate(validateContext);
}
Example 77
Project: BusWebApp-master  File: AgencyListHandlerTest.java View source code
@Test
public void parseRouteListXmlTest() {
    Document xml = XmlHandler.getXml("test/resources/RouteList-sf-muni.xml");
    List<Route> routes = AgencyListHandler.parseRouteListXml(xml, new Agency("sf-muni", "Carlifornia-Northen"));
    int numOfNX = 0;
    for (Route r : routes) {
        if (r.getTag().equals("NX")) {
            numOfNX++;
        }
    }
    assertTrue(numOfNX == 1);
    xml = XmlHandler.getXml("test/resources/RouteList-Error-Invalid-agency.xml");
    routes = AgencyListHandler.parseRouteListXml(xml, new Agency("sf-muni", "Carlifornia-Northen"));
    assertTrue(routes.size() == 0);
}
Example 78
Project: camel-example-cxf-proxy-master  File: EnrichBean.java View source code
public Document enrich(Document doc) {
    Node node = doc.getElementsByTagName("incidentId").item(0);
    Node prio = doc.getElementsByTagName("incidentPriority").item(0);
    if (prio == null) {
        throw new RuntimeException("priority is null");
    }
    Priority prioValue = Priority.fromValue(prio.getTextContent());
    String incident = node.getTextContent();
    if (prioValue.equals(Priority.BLOCKER)) {
        node.setTextContent("666");
    } else {
        System.out.println("priority was" + prioValue);
        // here we enrich the document by changing the incident id to
        // another value
        // you can of course do a lot more in your use-case
        node.setTextContent("456");
    }
    System.out.println("Incident was " + incident + ", changed to " + node.getTextContent());
    return doc;
}
Example 79
Project: camelinaction2-master  File: XmlOrderTest.java View source code
@Test
public void sendIncomingOrder() throws Exception {
    MockEndpoint mock = getMockEndpoint("mock:queue:order");
    mock.expectedMessageCount(1);
    // prepare a XML document from a String which is converted to a DOM
    String body = "<order customerId=\"4444\"><item>Camel in action</item></order>";
    Document xml = context.getTypeConverter().convertTo(Document.class, body);
    // store the order as a file which is picked up by the route
    template.sendBodyAndHeader("file://target/order", xml, Exchange.FILE_NAME, "order.xml");
    mock.assertIsSatisfied();
}
Example 80
Project: camunda-bpm-mockito-master  File: ReadXmlDocumentFromResourceTest.java View source code
@Test
public void parse_xml() {
    Document document = fromResource.apply(getResource("/MockProcess.bpmn"));
    Element root = document.getDocumentElement();
    final NodeList tasks = root.getElementsByTagNameNS("*", "serviceTask");
    assertThat(tasks.getLength()).isEqualTo(2);
    logger.info(tasks.toString());
    logger.info(tasks.item(1).toString());
}
Example 81
Project: cms-ce-master  File: XMLToolTest.java View source code
@Test
public void testSortChildElements() throws Exception {
    Document doc = XMLTool.createDocument("root");
    Element root = doc.getDocumentElement();
    Element elem1 = addChild(root, 1);
    Element elem2 = addChild(root, 3);
    Element elem3 = addChild(elem1, 4);
    Element elem4 = addChild(elem3, 1);
    Element elem5 = addChild(elem3, 7);
    //XMLTool.printDocument(doc);
    XMLTool.sortChildElements(root, "order", true, true);
    //XMLTool.printDocument(doc);
    assertEquals(0, XMLTool.getElementIndex(elem2));
    assertEquals(1, XMLTool.getElementIndex(elem1));
    assertEquals(0, XMLTool.getElementIndex(elem3));
    assertEquals(0, XMLTool.getElementIndex(elem5));
    assertEquals(1, XMLTool.getElementIndex(elem4));
}
Example 82
Project: codehaus-mojo-master  File: JlintXmlConfigReader.java View source code
public ArrayList<String> readConfiguration() {
    rules = new ArrayList<String>();
    try {
        String textVal = null;
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document dom = db.parse(configFileName);
        Element rootEl = dom.getDocumentElement();
        NodeList nl = rootEl.getElementsByTagName(Constants.XMLCONFIGFILE_RULE_NODE);
        if (nl != null && nl.getLength() > 0) {
            for (int i = 0; i < nl.getLength(); i++) {
                Element ruleEl = (Element) nl.item(i);
                textVal = ruleEl.getFirstChild().getNodeValue();
                // System.out.println(textVal);
                rules.add(textVal);
            }
        }
    // System.out.println("LOAD CONFIG ++++++++++++++++++++++++++++++++++++++++++");
    } catch (ParserConfigurationException pce) {
        pce.printStackTrace();
    } catch (SAXException se) {
        se.printStackTrace();
    } catch (IOException ioe) {
        ioe.printStackTrace();
    }
    return rules;
}
Example 83
Project: ComplexEventProcessingPlatform-master  File: AbstractXMLParser.java View source code
/**
	 * Returns a {@link Document} for a XML file from the given file path.
	 * @param filePath
	 */
protected static Document readXMLDocument(String filePath) {
    DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
    domFactory.setNamespaceAware(true);
    DocumentBuilder builder = null;
    try {
        builder = domFactory.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    }
    Document doc = null;
    try {
        doc = builder.parse(filePath);
    } catch (SAXException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return doc;
}
Example 84
Project: cooper-master  File: IBATIS30MapperConfigParse.java View source code
@Override
public void parse(Document doc) {
    Map<String, List<TableInfo>> tables = new HashMap<String, List<TableInfo>>();
    Element root = doc.getDocumentElement();
    String namespace = root.getAttribute("namespace");
    LogUtil.getInstance(IBATIS30MapperConfigParse.class).systemLog("namespace(JavaClassName):" + namespace);
    List<String> tagNames = new ArrayList<String>();
    tagNames.add("insert");
    tagNames.add("update");
    tagNames.add("delete");
    tagNames.add("select");
    for (String tagName : tagNames) {
        NodeList tags = doc.getElementsByTagName(tagName);
        for (int i = 0; i < tags.getLength(); i++) {
            Element tag = (Element) tags.item(i);
            String sql = tag.getTextContent();
            tables.put(namespace, SqlParseUtil.parserSql(sql));
        }
    }
    LogUtil.getInstance(IBATIS30MapperConfigParse.class).systemLog("tables:" + tables);
    ConfigParseMgr.getInstance().addTables(TableInfoItem.ClassNameType, tables);
}
Example 85
Project: css-analyser-master  File: Combinator.java View source code
@Override
public DOMNodeWrapperList getSelectedNodes(Document document) {
    DOMNodeWrapperList toReturn = new DOMNodeWrapperList();
    try {
        NodeList nodes = DOMHelper.queryDocument(document, getXPath());
        for (int i = 0; i < nodes.getLength(); i++) {
            toReturn.add(new DOMNodeWrapper(nodes.item(i), getRightHandSideSelector().getUnsupportedPseudoClasses()));
        }
    } catch (BadXPathExceptionUnsupportedSelectorToXPathException |  e) {
        e.printStackTrace();
    }
    return toReturn;
}
Example 86
Project: cyrille-leclerc-master  File: SerializationTest.java View source code
public void testSerialization() throws Exception {
    DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    Document document = documentBuilder.newDocument();
    Element root = (Element) document.appendChild(document.createElement("root"));
    Element child = (Element) root.appendChild(document.createElement("child"));
    Text text = (Text) child.appendChild(document.createTextNode("my text éèà €"));
    System.out.println(text);
    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    //"UTF-8";//"iso-8859-15"; //"UTF-8"; //"iso-8859-15";
    String encoding = "iso-8859-1";
    transformer.setOutputProperty(OutputKeys.ENCODING, encoding);
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    FileOutputStream out = new FileOutputStream("/tmp/test-encoding-" + encoding + ".xml");
    StreamResult streamResult = new StreamResult(System.out);
    transformer.transform(new DOMSource(document), streamResult);
}
Example 87
Project: delcyon-capo-master  File: RestartElementTest.java View source code
@Test
public void testProcessServerSideElement() throws Exception {
    RestartElement restartControlElement = new RestartElement();
    Document document = CapoApplication.getDocumentBuilder().newDocument();
    Element restartElement = document.createElementNS(CapoApplication.SERVER_NAMESPACE_URI, "server:restart");
    Group group = new Group("test", null, null, null);
//TODO figure out how to run restart w/o killing all tests        restartControlElement.init(restartElement, null, group, new ServerControllerResponse());
//        restartControlElement.processServerSideElement();
}
Example 88
Project: Disaster-Management-Using-Crowdsourcing-master  File: DocumentParser.java View source code
@Override
public Future<Document> parse(DataEmitter emitter) {
    return new ByteBufferListParser().parse(emitter).then(new TransformFuture<Document, ByteBufferList>() {

        @Override
        protected void transform(ByteBufferList result) throws Exception {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            setComplete(db.parse(new ByteBufferListInputStream(result)));
        }
    });
}
Example 89
Project: dltk.core-master  File: DbgpPackageProcessor.java View source code
public void processPacket(Document doc, DbgpPacketWaiter notifyWaiter, DbgpResponcePacketWaiter responseWaiter, DbgpPacketWaiter streamWaiter) {
    Element element = (Element) doc.getFirstChild();
    String tag = element.getTagName();
    // TODO: correct init tag handling without this hack
    if (tag.equals(INIT_TAG)) {
        responseWaiter.put(new DbgpResponsePacket(element, -1));
    } else if (tag.equals(RESPONSE_TAG)) {
        DbgpResponsePacket packet = DbgpXmlPacketParser.parseResponsePacket(element);
        responseWaiter.put(packet);
    } else if (tag.equals(STREAM_TAG)) {
        streamWaiter.put(DbgpXmlPacketParser.parseStreamPacket(element));
    } else if (tag.equals(NOTIFY_TAG)) {
        notifyWaiter.put(DbgpXmlPacketParser.parseNotifyPacket(element));
    }
}
Example 90
Project: docx4j-master  File: AstralCharacterHandling.java View source code
@Test
public void test() throws ParserConfigurationException {
    char[] chars = { 55357, 56459 };
    int codePoint = Character.codePointAt(chars, 0);
    // Convert it to a string
    String astral = new String(Character.toChars(codePoint));
    // Now show how it all falls apart 
    // Create a DOM doc containing astral char
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    documentBuilderFactory.setNamespaceAware(true);
    DocumentBuilder db = documentBuilderFactory.newDocumentBuilder();
    Document doc = db.newDocument();
    Element foo = doc.createElement("foo");
    doc.appendChild(foo);
    foo.setTextContent(astral);
    // this uses our configured serializer
    String actual = XmlUtils.w3CDomNodeToString(foo);
    // <foo>_  so codepoint of interest is at position 5.
    Assert.assertEquals(codePoint, actual.codePointAt(5));
}
Example 91
Project: dragome-examples-master  File: TestDom1.java View source code
public void build() {
    Document document = WebServiceLocator.getInstance().getDomHandler().getDocument();
    final Element div1 = document.getElementById("div1");
    div1.setAttribute("style", "position: relative;");
    String attribute = div1.getAttribute("class");
    EventTarget eventTarget = JsCast.castTo(div1, EventTarget.class);
    eventTarget.addEventListener("click", new EventListener() {

        public void handleEvent(Event event) {
            System.out.println(event.getType());
            if (event.getType().equals("click"))
                delta += 5;
            else if (event.getType().equals("mouseout"))
                delta -= 5;
            div1.setAttribute("style", "position: relative; left:" + delta + "px;top:" + delta + "px;");
        }
    }, false);
}
Example 92
Project: drools-guvnor-plugin-master  File: DocumentFactory.java View source code
public Document newDocument() {
    if (builder == null) {
        try {
            builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (FactoryConfigurationError e) {
            e.printStackTrace();
        }
    }
    return builder.newDocument();
}
Example 93
Project: droolsjbpm-master  File: DocumentFactory.java View source code
public Document newDocument() {
    if (builder == null) {
        try {
            builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (FactoryConfigurationError e) {
            e.printStackTrace();
        }
    }
    return builder.newDocument();
}
Example 94
Project: droolsjbpm-tools-master  File: DocumentFactory.java View source code
public Document newDocument() {
    if (builder == null) {
        try {
            builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (FactoryConfigurationError e) {
            e.printStackTrace();
        }
    }
    return builder.newDocument();
}
Example 95
Project: eagledns-master  File: ValidationError.java View source code
public final Node toXML(Document doc) {
    Element validationError = doc.createElement("validationError");
    if (this.fieldName != null) {
        validationError.appendChild(XMLUtils.createCDATAElement("fieldName", fieldName, doc));
    }
    if (this.validationErrorType != null) {
        validationError.appendChild(XMLUtils.createCDATAElement("validationErrorType", validationErrorType.toString(), doc));
    }
    if (this.messageKey != null) {
        validationError.appendChild(XMLUtils.createCDATAElement("messageKey", messageKey, doc));
    }
    return validationError;
}
Example 96
Project: eclipselink.runtime-master  File: TextNodeTestCases.java View source code
@Override
protected Object getControlObject() {
    ObjectFactory factory = new ObjectFactory();
    Document doc;
    try {
        doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
        Element elm = doc.createElementNS(null, "abcdef");
        elm.setTextContent("thetext");
        Object value = elm;
        JAXBElement obj = factory.createDoc(value);
        return obj;
    } catch (Exception e) {
        e.printStackTrace();
        fail("An exception was thrown.");
        return null;
    }
}
Example 97
Project: epublib-master  File: DOMUtilTest.java View source code
@Test
public void test_simple_foo() {
    // given
    String input = "<?xml version=\"1.0\"?><doc xmlns:a=\"foo\" xmlns:b=\"bar\" a:myattr=\"red\" b:myattr=\"green\"/>";
    try {
        Document document = EpubProcessorSupport.createDocumentBuilder().parse(new InputSource(new StringReader(input)));
        // when
        String actualResult = DOMUtil.getAttribute(document.getDocumentElement(), "foo", "myattr");
        // then
        assertEquals("red", actualResult);
    } catch (Exception e) {
        fail(e.getMessage());
    }
}
Example 98
Project: ExemplosDemoiselle-master  File: XmlSigUtil.java View source code
/**
	 * Revalida um objeto Document 
	 * @param documento
	 * @return Document
	 * @throws ParserConfigurationException 
	 * @throws IOException 
	 * @throws SAXException 
	 * @throws TransformerFactoryConfigurationError 
	 * @throws TransformerException 
	 * @throws TransformerConfigurationException 
	 */
public static Document revalidaDocument(Document documento) throws ParserConfigurationException, SAXException, IOException, TransformerConfigurationException, TransformerException, TransformerFactoryConfigurationError {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    Document doc = null;
    DocumentBuilder db;
    db = dbf.newDocumentBuilder();
    InputSource is = converterDoc(documento);
    if (is != null) {
        doc = db.parse(is);
    }
    return doc;
}
Example 99
Project: factura-electronica-master  File: CFDFactory.java View source code
protected static String getVersion(byte[] data) throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse(new ByteArrayInputStream(data));
    XPathFactory xfactory = XPathFactory.newInstance();
    XPath xpath = xfactory.newXPath();
    return (String) xpath.evaluate("/Comprobante/@version", doc);
}
Example 100
Project: fb-contrib-master  File: SG_Sample.java View source code
private String getRoot() {
    try {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document d = db.parse(new ByteArrayInputStream(s.getBytes()));
        return d.getDocumentElement().getNodeName();
    } catch (Exception e) {
        return "";
    }
}
Example 101
Project: fcrepo-before33-master  File: TestAPIMLite.java View source code
public void testGetNextPID() throws Exception {
    Document result;
    result = getXMLQueryResult("/management/getNextPID?xml=true");
    assertXpathEvaluatesTo("1", "count(/pidList/pid)", result);
    result = getXMLQueryResult("/management/getNextPID?numpids=10&namespace=demo&xml=true");
    assertXpathEvaluatesTo("10", "count(/pidList/pid)", result);
}