Java Examples for javax.xml.parsers.DocumentBuilder

The following java examples will help you to understand the usage of javax.xml.parsers.DocumentBuilder. These source code samples are taken from different open source projects.

Example 1
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 2
Project: aliada-tool-master  File: XmlRecordToDocumentTranslator.java View source code
@Override
protected DocumentBuilder initialValue() {
    try {
        final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(false);
        return factory.newDocumentBuilder();
    } catch (final ParserConfigurationException exception) {
        throw new IllegalStateException(exception);
    }
}
Example 3
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 4
Project: coding2017-master  File: StrutsXmlReader.java View source code
public Map loadXml() throws ParserConfigurationException, SAXException, IOException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse(file);
    NodeList nl = doc.getElementsByTagName("action");
    for (int i = 0; i < nl.getLength(); i++) {
        Element book = (Element) nl.item(i);
        String name = book.getAttribute("name");
        String claz = book.getAttribute("class");
        Action act = new Action(name, claz);
        System.out.println(name);
        System.out.println(claz);
        NodeList bookNode = book.getChildNodes();
        HashMap<String, String> paraMap = new HashMap();
        for (int j = 0; j < bookNode.getLength(); j++) {
            Node bookCh = bookNode.item(j);
            if (bookCh.getNodeType() == Node.ELEMENT_NODE) {
                String valTag = bookCh.getTextContent();
                NamedNodeMap attrs = bookCh.getAttributes();
                String resultsValue = attrs.getNamedItem("name").getNodeValue();
                paraMap.put(resultsValue, valTag);
            }
            act.setParameters(paraMap);
        }
        actMap.put(act.getName(), act);
    }
    return actMap;
}
Example 5
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 6
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 7
Project: scaleDOM-master  File: TestBase.java View source code
protected static Document parseDocument(final File file, final String fileEncoding) throws Exception {
    // Create document builder factory
    final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    // Configure document builder factory
    dbf.setNamespaceAware(true);
    // dbf.setValidating(true);
    // Create document builder
    final DocumentBuilder db = dbf.newDocumentBuilder();
    // Parse document
    final Document doc = new MeasuredTask<Document>("Initial parsing") {

        @Override
        protected Document runTask() throws Exception {
            return db.parse(file);
        }
    }.run();
    return doc;
}
Example 8
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 9
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 10
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 11
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 12
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 13
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 14
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 15
Project: claudia-master  File: TCloudException.java View source code
public Document createErrorMessage() {
    try {
        DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder;
        docBuilder = dbfac.newDocumentBuilder();
        Document doc = docBuilder.newDocument();
        Element r = doc.createElement("ErrorSet");
        doc.appendChild(r);
        if (errorType == ErrorType.UNKNOWN_ELEMENTS) {
            Element unknown = doc.createElement("UnknownElements");
            r.appendChild(unknown);
            Element element = doc.createElement("element");
            unknown.appendChild(element);
            element.setAttribute("type", elementType);
            element.setAttribute("ref", uri);
        } else if (errorType == ErrorType.ELEMENT_NOT_FOUND) {
            Element elementNotFound = doc.createElement("ElementNotFound");
            r.appendChild(elementNotFound);
            Element element = doc.createElement("element");
            elementNotFound.appendChild(element);
            element.setAttribute("type", elementType);
            element.setAttribute("ref", uri);
        }
        return doc;
    } catch (IllegalArgumentException iae) {
        return null;
    } catch (ParserConfigurationException pe) {
        return null;
    }
}
Example 16
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 17
Project: ComplexEventProcessingPlatform-master  File: FileUtils.java View source code
/**
	 * returns Document from StreamResult 
	 */
public static Document createDocumentFromResult(StreamResult result) {
    Document document = null;
    String fileString = result.getWriter().toString();
    try {
        DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        StringReader reader = new StringReader(fileString);
        InputSource inputSource = new InputSource(reader);
        document = parser.parse(inputSource);
    } catch (SAXException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    }
    return document;
}
Example 18
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 19
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 20
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 21
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 22
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 23
Project: flyingsaucer-master  File: BorderRadiusNonRegressionTest.java View source code
private void testNoException(String htmlPath) throws Exception {
    URL htmlUrl = getClass().getResource(htmlPath);
    DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    builder.setEntityResolver(FSEntityResolver.instance());
    Document doc = builder.parse(htmlUrl.openStream());
    ITextRenderer renderer = new ITextRenderer();
    renderer.getSharedContext().setMedia("pdf");
    renderer.setDocument(doc, htmlUrl.toString());
    renderer.layout();
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    renderer.createPDF(bos);
}
Example 24
Project: HBuilder-opensource-master  File: InfoFactoryTest.java View source code
public void testInfoFactory() throws Exception {
    InfoFactory infoFactory = new InfoFactory(new AdditionalInfoAndIInfo(null, null));
    DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    Document document = documentBuilder.newDocument();
    Element root = document.createElement("root");
    IMemento memento = new XMLMemento(document, root);
    infoFactory.saveState(memento);
    assertNull(infoFactory.createElement(memento));
    ClassInfo info = new ClassInfo(null, null, null);
    infoFactory = new InfoFactory(new AdditionalInfoAndIInfo(null, info));
    infoFactory.saveState(memento);
    assertNull(infoFactory.createElement(memento));
}
Example 25
Project: helper-android-master  File: ScheduleParser.java View source code
public static ArrayList<Lesson> parseXmlSchedule(File xmlFile) {
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder;
    Document doc = null;
    try {
        dBuilder = dbFactory.newDocumentBuilder();
        doc = dBuilder.parse(xmlFile);
    } catch (Exception e) {
        e.printStackTrace();
    }
    doc.getDocumentElement().normalize();
    NodeList list = doc.getElementsByTagName("ROW");
    ArrayList<Lesson> lessons = new ArrayList<Lesson>();
    for (int i = 0; i < list.getLength(); i++) {
        Lesson lesson = new Lesson();
        Element element = (Element) list.item(i);
        NamedNodeMap attrs = element.getAttributes();
        for (int j = 0; j < attrs.getLength(); j++) {
            Node attribute = attrs.item(j);
            //In xml file attribute name group, but group it is keyword of sqlite
            if (attribute.getNodeName().equals("group")) {
                lesson.fields.put("s_group", attribute.getNodeValue());
                continue;
            }
            lesson.fields.put(attribute.getNodeName(), attribute.getNodeValue());
        }
        lessons.add(lesson);
    }
    return lessons;
}
Example 26
Project: http-helper-master  File: Xml2DocumentConverter.java View source code
@Override
protected Document doConstructObject(InputStream is, Charset charset) throws IOException {
    DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
    try {
        DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
        return docBuilder.parse(is, charset.toString());
    } catch (ParserConfigurationException ex) {
        throw new IllegalStateException(ex);
    } catch (SAXException ex) {
        throw new ClientProtocolException("Malformed XML document", ex);
    }
}
Example 27
Project: idea-php-symfony2-plugin-master  File: AbstractServiceParser.java View source code
@Nullable
protected NodeList parserer(InputStream file) {
    Document document;
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    try {
        DocumentBuilder documentBuilder = dbFactory.newDocumentBuilder();
        document = documentBuilder.parse(file);
    } catch (ParserConfigurationExceptionSAXException | IOException |  e) {
        return null;
    }
    if (document == null) {
        return null;
    }
    Object result;
    try {
        XPath xpath = XPathFactory.newInstance().newXPath();
        XPathExpression xPathExpr = xpath.compile(this.getXPathFilter());
        result = xPathExpr.evaluate(document, XPathConstants.NODESET);
    } catch (XPathExpressionException e) {
        return null;
    }
    return (NodeList) result;
}
Example 28
Project: incubator-cordova-android-master  File: ApplicationInfo.java View source code
private static void parseAndroidManifest(String path) {
    // System.out.println(path);
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    Document dom;
    try {
        DocumentBuilder db = dbf.newDocumentBuilder();
        dom = db.parse(path);
        // getting package information
        Element manifest = dom.getDocumentElement();
        String pakkage = manifest.getAttribute("package");
        // getting activity name
        String activity = ((Element) dom.getElementsByTagName("activity").item(0)).getAttribute("android:name");
        System.out.println(String.format("%s/.%s", pakkage, activity.replace(".", "")));
    } catch (ParserConfigurationException pce) {
        pce.printStackTrace();
    } catch (SAXException se) {
        se.printStackTrace();
    } catch (IOException ioe) {
        ioe.printStackTrace();
    }
}
Example 29
Project: ivanova_p01-master  File: TestTrax.java View source code
private static void process() throws TransformerException, SAXException, ParserConfigurationException, IOException {
    DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
    Document xmlDoc = docBuilder.parse(TestTrax.class.getResourceAsStream("/test.xml"));
    Source xmlSource = new DOMSource(xmlDoc);
    Source stylesheetSource = new StreamSource(TestTrax.class.getResourceAsStream("/test.xsl"));
    StringWriter resultWriter = new StringWriter();
    Result transformerResult = new StreamResult(resultWriter);
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer(stylesheetSource);
    transformer.transform(xmlSource, transformerResult);
    System.out.println(resultWriter.getBuffer().toString());
}
Example 30
Project: JavaInterview-master  File: DomParseTest.java View source code
public static void main(String[] args) throws Exception {
    String path = DomParseTest.class.getResource("").getPath();
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document document = builder.parse(new File(path + "/canlidate.xml"));
    NodeList list = document.getElementsByTagName("person");
    for (int i = 0; i < list.getLength(); i++) {
        Element element = (Element) list.item(i);
        String name = element.getElementsByTagName("name").item(0).getFirstChild().getNodeValue();
        String address = element.getElementsByTagName("address").item(0).getFirstChild().getNodeValue();
        String email = element.getElementsByTagName("email").item(0).getFirstChild().getNodeValue();
        System.out.println("person:[" + name + "," + address + "," + email + "]");
    }
}
Example 31
Project: lumify-master  File: YoutubeccReader.java View source code
public static VideoTranscript read(InputStream in) throws Exception {
    VideoTranscript videoTranscript = new VideoTranscript();
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document doc = db.parse(in);
    NodeList textElements = doc.getElementsByTagName("text");
    for (int i = 0; i < textElements.getLength(); i++) {
        Element textElement = (Element) textElements.item(i);
        double start = Double.parseDouble(textElement.getAttribute("start"));
        double duration = Double.parseDouble(textElement.getAttribute("dur"));
        String text = textElement.getTextContent().trim();
        VideoTranscript.Time time = new VideoTranscript.Time((long) (start * 1000), (long) ((start + duration) * 1000));
        videoTranscript.add(time, text);
    }
    return videoTranscript;
}
Example 32
Project: MadStore-master  File: Utils.java View source code
public static Document getDoc(String docFile) {
    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        DocumentBuilder builder = factory.newDocumentBuilder();
        InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(docFile);
        Document doc = builder.parse(inputStream);
        return doc;
    } catch (Exception e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}
Example 33
Project: OpenDataBridge-master  File: UnitTestWmsThumbnailHandler.java View source code
private Document createDoc(InputStream stream) {
    DocumentBuilderFactory fac = DocumentBuilderFactory.newInstance();
    fac.setValidating(false);
    fac.setNamespaceAware(false);
    try {
        DocumentBuilder builder = fac.newDocumentBuilder();
        return builder.parse(stream);
    } catch (ParserConfigurationException e) {
        fail(e.getMessage());
    } catch (SAXException e) {
        fail(e.getMessage());
    } catch (IOException e) {
        fail(e.getMessage());
    }
    return null;
}
Example 34
Project: openmrs-module-patientmatching-master  File: XMLTranslatorTest.java View source code
public static void main(String[] args) {
    File config = new File(args[0]);
    if (!config.exists()) {
        System.out.println("config file does not exist, exiting");
        System.exit(0);
    }
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    try {
        // Load the XML configuration file
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document doc = builder.parse(config);
        RecMatchConfig rmc = XMLTranslator.createRecMatchConfig(doc);
        String fname = config.getAbsolutePath();
        fname = fname.substring(0, fname.length() - 3);
        File newconfig = new File(fname + "test.xml");
        Document d = XMLTranslator.toXML(rmc);
        XMLTranslator.writeXMLDocToFile(d, newconfig);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Example 35
Project: ps-scripts-master  File: Subversion.java View source code
/**
	 * Returns the username of the last person modified the file
	 */
public String getFileOwner(String file) throws Exception {
    final String command = "svn ls --xml " + file;
    try {
        Process process = Runtime.getRuntime().exec(command);
        DocumentBuilderFactory documentFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = documentFactory.newDocumentBuilder();
        Document document = documentBuilder.parse(process.getInputStream());
        // get author tag
        NodeList authorNode = document.getDocumentElement().getElementsByTagName("author");
        if (authorNode.getLength() != 1) {
            return "";
        }
        Element authorElem = (Element) authorNode.item(0);
        return authorElem.getTextContent();
    } catch (Exception e) {
        return "";
    }
}
Example 36
Project: Pydev-master  File: InfoFactoryTest.java View source code
public void testInfoFactory() throws Exception {
    InfoFactory infoFactory = new InfoFactory(new AdditionalInfoAndIInfo(null, null));
    DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    Document document = documentBuilder.newDocument();
    Element root = document.createElement("root");
    IMemento memento = new XMLMemento(document, root);
    infoFactory.saveState(memento);
    assertNull(infoFactory.createElement(memento));
    ClassInfo info = new ClassInfo(null, null, null, null);
    infoFactory = new InfoFactory(new AdditionalInfoAndIInfo(null, info));
    infoFactory.saveState(memento);
    assertNull(infoFactory.createElement(memento));
}
Example 37
Project: remote-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 38
Project: s3repo-gradle-plugin-master  File: XmlUtils.java View source code
/** Parse the provided {@link File} as XML, decompressing it first if it has a .gz file extension. */
public static Document parseXmlFile(File file) throws IOException {
    InputStream in = toInputStream(file);
    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        DocumentBuilder builder = factory.newDocumentBuilder();
        return builder.parse(in);
    } catch (Exception e) {
        throw new RuntimeException("failed to parse", e);
    } finally {
        in.close();
    }
}
Example 39
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 40
Project: spaceout-master  File: SaveLister.java View source code
private ArrayList<String> buildList() {
    File saveFolder = new File(SAVE_FOLDER_LOCATION);
    File[] fileList = saveFolder.listFiles();
    String file;
    ArrayList<String> sList = new ArrayList<String>();
    for (int i = 0; i < fileList.length; i++) {
        file = fileList[i].getName();
        String saveName;
        if (file.endsWith(".xml")) {
            try {
                DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
                DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
                Document doc = dBuilder.parse(new File(fileList[i].getAbsolutePath()));
                doc.getDocumentElement().normalize();
                saveName = doc.getElementsByTagName("save").item(0).getAttributes().getNamedItem("name").getNodeValue();
                sList.add(saveName);
            } catch (Exception e) {
                System.out.println("FTTZZZ... (SaveLister)");
                e.printStackTrace();
            }
        }
    }
    return sList;
}
Example 41
Project: strolch-master  File: DomUtil.java View source code
public static DocumentBuilder createDocumentBuilder() {
    try {
        DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
        return docBuilder;
    } catch (ParserConfigurationException e) {
        String msg = "No Xml Parser could be loaded: {0}";
        msg = MessageFormat.format(msg, e.getMessage());
        throw new RuntimeException(msg, e);
    }
}
Example 42
Project: TadpoleGame-master  File: XMLUtil.java View source code
/**
     * Converts String containing XML code to Document
     * 
     * @param xmlString
     * @return <code>Document</code> interface
     */
public static Document stringToDocument(String xmlString) {
    if (xmlString == null)
        return null;
    DocumentBuilder documentBuilder = getDocumentBuilder();
    InputSource inputSource = new InputSource(new StringReader(xmlString));
    try {
        return documentBuilder.parse(inputSource);
    } catch (SAXException e) {
        e.printStackTrace();
        return null;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}
Example 43
Project: teamengine-master  File: BinaryPayloadParser.java View source code
public Document parse(URLConnection uc, Element instruction, PrintWriter logger) throws Exception {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    // Fortify Mod: prevent external entity injection
    dbf.setExpandEntityReferences(false);
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document doc = db.newDocument();
    Element root = doc.createElement("payload");
    // Fortify Mod: prevent external entity injection 
    TransformerFactory tf = TransformerFactory.newInstance();
    tf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
    Transformer t = tf.newTransformer();
    return doc;
}
Example 44
Project: Tempo-master  File: DocumentBuilderPool.java View source code
@Override
public Object makeObject() throws Exception {
    DocumentBuilder newDocumentBuilder = factory.newDocumentBuilder();
    newDocumentBuilder.setErrorHandler(new ErrorHandler() {

        public void error(SAXParseException exception) throws SAXException {
            if (LOG.isDebugEnabled())
                LOG.debug(exception.toString());
        }

        public void fatalError(SAXParseException exception) throws SAXException {
            if (LOG.isDebugEnabled())
                LOG.debug(exception.toString());
        }

        public void warning(SAXParseException exception) throws SAXException {
            if (LOG.isDebugEnabled())
                LOG.debug(exception.toString());
        }
    });
    return newDocumentBuilder;
}
Example 45
Project: tern.java-master  File: DefaultDOMProvider.java View source code
@Override
public Document getDocument(ITernFile file) {
    if (file == null) {
        return null;
    }
    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        return builder.parse(file.getContents());
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
Example 46
Project: wooki-master  File: FlyingSaucerPDFConvertor.java View source code
public InputStream performTransformation(Resource xmlDocument) {
    try {
        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document doc = builder.parse(xmlDocument.getInputStream());
        ITextRenderer renderer = new ITextRenderer();
        renderer.setDocument(doc, null);
        renderer.layout();
        final ByteArrayOutputStream os = new ByteArrayOutputStream();
        renderer.createPDF(os);
        os.close();
        return new ByteArrayInputStream(os.toByteArray());
    } catch (Exception ex) {
        throw new TapestryException("Error during PDF generation", ex);
    }
}
Example 47
Project: xmlresolver-master  File: XMLCatalogReaderTest.java View source code
/**
     * Test of readCatalog method, of class org.xmlresolver.readers.XMLCatalogReader.
     */
public void testReadCatalog() throws ParserConfigurationException, SAXException, IOException {
    System.out.println("readCatalog");
    String xml = "<catalog xmlns='urn:oasis:names:tc:entity:xmlns:xml:catalog'/>";
    ByteArrayInputStream stream = new ByteArrayInputStream(xml.getBytes());
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    DocumentBuilder builder = dbf.newDocumentBuilder();
    Document doc = builder.parse(stream);
    DOMSource source = new DOMSource(doc);
    XMLCatalogReader instance = new XMLCatalogReader();
    Element result = instance.readCatalog(source);
    assertNotNull(result);
}
Example 48
Project: zendserver-sdk-java-master  File: ServerUtils.java View source code
public static Document readXMLFile(String fileName) {
    File file = new File(fileName);
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    try {
        DocumentBuilder db = factory.newDocumentBuilder();
        return db.parse(file);
    } catch (SAXException e) {
        fail("Error during parsing configuration file: " + fileName);
    } catch (IOException e) {
        fail("Error during reading configuration file: " + fileName);
    } catch (ParserConfigurationException e) {
        fail("XML parser configuration error: " + fileName);
    }
    return null;
}
Example 49
Project: concierge-master  File: BundlesWithBootdelegationTest.java View source code
/** A class can be loaded via bootdelegation. */
private void checkOK(String bootDelegation) throws Exception {
    HashMap<String, String> launchArgs = new HashMap<String, String>();
    launchArgs.put("org.osgi.framework.bootdelegation", bootDelegation);
    startFrameworkClean(launchArgs);
    setupDefaultBundles();
    bundleUnderTest.start();
    assertBundleActive(bundleUnderTest);
    RunInClassLoader runner = new RunInClassLoader(bundleUnderTest);
    Object o = runner.getClass("javax.xml.parsers.DocumentBuilder");
    Assert.assertNotNull(o);
    stopFramework();
}
Example 50
Project: webtools.javaee-master  File: GeneralXmlDocumentReader.java View source code
protected javax.xml.parsers.DocumentBuilder createNewDOMParser() {
    try {
        javax.xml.parsers.DocumentBuilderFactory dbf = javax.xml.parsers.DocumentBuilderFactory.newInstance();
        setFeatures(dbf);
        return dbf.newDocumentBuilder();
    } catch (Exception ie) {
        handleException(J2EEXMLResourceHandler.getString(XMLParseResourceHandler.failed_instantiating_EXC_, (new Object[] { "Failed to instantiate parser" })), ie);
    }
    return null;
}
Example 51
Project: android_libcore-master  File: Support_Xml.java View source code
public static Document domOf(String xml) throws Exception {
    // DocumentBuilderTest assumes we're using DocumentBuilder to do this parsing!
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setCoalescing(true);
    dbf.setExpandEntityReferences(true);
    ByteArrayInputStream stream = new ByteArrayInputStream(xml.getBytes());
    DocumentBuilder builder = dbf.newDocumentBuilder();
    return builder.parse(stream);
}
Example 52
Project: rtgov-master  File: SerializeInformationTransformerTest.java View source code
@Test
public void testSerializeDOM() {
    SerializeInformationTransformer transformer = new SerializeInformationTransformer();
    String info = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><hello/>";
    org.w3c.dom.Document doc = null;
    try {
        javax.xml.parsers.DocumentBuilderFactory factory = javax.xml.parsers.DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        javax.xml.parsers.DocumentBuilder builder = factory.newDocumentBuilder();
        java.io.InputStream is = new java.io.ByteArrayInputStream(info.getBytes());
        doc = builder.parse(is);
        is.close();
    } catch (Exception e) {
        fail("Failed to build dom: " + e);
    }
    String result = transformer.transform(doc.getDocumentElement());
    if (result == null) {
        fail("Result is null");
    }
    if (!result.equals(info)) {
        fail("Result mismatch: " + info + " but got " + result);
    }
}
Example 53
Project: a-cma-master  File: ActionRegistry.java View source code
private static void initialize() {
    entries = new HashSet<Entry>();
    try {
        Log.config("Loading actions.xml for action configuration.");
        DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
        Document doc = docBuilder.parse(new File("./data/actions.xml"));
        NodeList actions = doc.getElementsByTagName("action");
        for (int i = 0; i < actions.getLength(); i++) {
            Node action = actions.item(i);
            String className = action.getAttributes().getNamedItem("class").getTextContent();
            Class<?> actionClass = Class.forName("edu.atilim.acma.transition.actions." + className);
            for (Class<?> innerClass : actionClass.getClasses()) {
                if (ActionChecker.class.isAssignableFrom(innerClass)) {
                    ActionChecker checker = (ActionChecker) innerClass.newInstance();
                    entries.add(new Entry(className, checker));
                }
            }
        }
        Log.config("Found %d action configurers. Action manager is ready.", entries.size());
    } catch (Exception e) {
        System.out.println("Could not initialize transition manager. Details:");
        e.printStackTrace();
    }
}
Example 54
Project: airavata-master  File: LDAPUserStoreTest.java View source code
public void testConfigure() throws Exception {
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
    Document doc = dBuilder.parse(this.getClass().getClassLoader().getResourceAsStream("ldap-authenticator.xml"));
    doc.getDocumentElement().normalize();
    NodeList configurations = doc.getElementsByTagName("specificConfigurations");
    UserStore userStore = new LDAPUserStore();
    userStore.configure(configurations.item(0));
    assertTrue(userStore.authenticate("amilaj", "secret"));
}
Example 55
Project: Ak47-master  File: XmlUtil.java View source code
/**
     * string(XML Text) to document(w3c.dom.Document)
     * 
     * @param string
     * @return
     * @throws ParserConfigurationException
     * @throws SAXException
     * @throws IOException
     */
public static Document string2Document(String string) throws ParserConfigurationException, SAXException, IOException {
    DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
    builderFactory.setNamespaceAware(true);
    InputStream is = new ByteArrayInputStream(string.getBytes(Ak47Constants.DEFAULT_ENCODING));
    DocumentBuilder docBuilder = builderFactory.newDocumentBuilder();
    Document document = docBuilder.parse(is);
    return document;
}
Example 56
Project: ambari-master  File: XmlUtils.java View source code
public static boolean isValidXml(String input) {
    boolean result = true;
    try {
        if (StringUtils.isBlank(input)) {
            result = false;
        } else {
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            // skip dtd references
            dbFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
            dBuilder.parse(new ByteArrayInputStream(input.getBytes("UTF-8")));
        }
    } catch (Exception e) {
        result = false;
    }
    return result;
}
Example 57
Project: Amber-IDE-master  File: XML.java View source code
public static String formatXML(String xml) {
    try {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        InputSource is = new InputSource(new StringReader(xml));
        Document document = db.parse(is);
        OutputFormat format = new OutputFormat(document);
        format.setLineWidth(65);
        format.setIndenting(true);
        format.setIndent(2);
        Writer out = new StringWriter();
        XMLSerializer serializer = new XMLSerializer(out, format);
        serializer.serialize(document);
        return out.toString();
    } catch (Exception e) {
        return xml;
    }
}
Example 58
Project: android-libcore64-master  File: Support_Xml.java View source code
public static Document domOf(String xml) throws Exception {
    // DocumentBuilderTest assumes we're using DocumentBuilder to do this parsing!
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setCoalescing(true);
    dbf.setExpandEntityReferences(true);
    ByteArrayInputStream stream = new ByteArrayInputStream(xml.getBytes());
    DocumentBuilder builder = dbf.newDocumentBuilder();
    return builder.parse(stream);
}
Example 59
Project: android-native-shoppingcart-master  File: ReadXMLFile.java View source code
public void loadPhrescoConstansts(InputStream inputStream) throws TestException {
    try {
        // File fXmlFile = new File(inputStream);
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(inputStream);
        NodeList nList = doc.getElementsByTagName("phresco");
        System.out.println("--------Node list-->" + nList.getLength());
        for (int temp = 0; temp < nList.getLength(); temp++) {
            Node nNode = nList.item(temp);
            if (nNode.getNodeType() == Node.ELEMENT_NODE) {
                eElement = (Element) nNode;
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Example 60
Project: android-platform-tools-base-master  File: Main.java View source code
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    TextView tv = (TextView) findViewById(R.id.dateText);
    String message;
    try {
        // load untouched xml file.
        InputStream inputStream = null;
        try {
            inputStream = getClass().getResourceAsStream("/com/android/tests/other/some.xml");
            if (inputStream == null) {
                message = "Cannot load some.xml";
            } else {
                DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
                DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
                Document doc = dBuilder.parse(inputStream);
                String value = doc.getDocumentElement().getAttribute("value");
                message = StringProvider.getString(Integer.parseInt(value));
            }
        } finally {
            if (inputStream != null) {
                inputStream.close();
            }
        }
        String appName = AppStringProvider.getProperty("app.name");
        String appString = AppStringProvider.getProperty("app.string");
        tv.setText(appName + '-' + appString + '_' + message);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
Example 61
Project: android-playlistr-master  File: XMLParse.java View source code
public static Document getDomElement(String xml) {
    Document doc = null;
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    try {
        DocumentBuilder db = dbf.newDocumentBuilder();
        InputSource is = new InputSource();
        is.setCharacterStream(new StringReader(xml));
        doc = db.parse(is);
    } catch (ParserConfigurationException e) {
        Log.e("Error: ", e.getMessage());
        return null;
    } catch (SAXException e) {
        Log.e("Error: ", e.getMessage());
        return null;
    } catch (IOException e) {
        Log.e("Error: ", e.getMessage());
        return null;
    }
    // return DOM
    return doc;
}
Example 62
Project: AndroidFileBroadcast-master  File: XMLDOMParser.java View source code
//Returns the entire XML document
public Document getDocument(InputStream inputStream) {
    Document document = null;
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    try {
        DocumentBuilder db = factory.newDocumentBuilder();
        InputSource inputSource = new InputSource(inputStream);
        document = db.parse(inputSource);
    } catch (ParserConfigurationException e) {
        Log.e("Error: ", e.getMessage());
        return null;
    } catch (SAXException e) {
        Log.e("Error: ", e.getMessage());
        return null;
    } catch (IOException e) {
        Log.e("Error: ", e.getMessage());
        return null;
    }
    return document;
}
Example 63
Project: Android_App_OpenSource-master  File: XMLUtil.java View source code
/**
	 * Converts String containing XML code to Document
	 * 
	 * @param xmlString
	 * @return <code>Document</code> interface
	 */
public static Document stringToDocument(String xmlString) {
    if (xmlString == null)
        return null;
    DocumentBuilder documentBuilder = getDocumentBuilder();
    InputSource inputSource = new InputSource(new StringReader(xmlString));
    try {
        return documentBuilder.parse(inputSource);
    } catch (SAXException e) {
        e.printStackTrace();
        return null;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}
Example 64
Project: android_platform_libcore-master  File: Support_Xml.java View source code
public static Document domOf(String xml) throws Exception {
    // DocumentBuilderTest assumes we're using DocumentBuilder to do this parsing!
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setCoalescing(true);
    dbf.setExpandEntityReferences(true);
    ByteArrayInputStream stream = new ByteArrayInputStream(xml.getBytes());
    DocumentBuilder builder = dbf.newDocumentBuilder();
    return builder.parse(stream);
}
Example 65
Project: apache_ant-master  File: DOMUtilTest.java View source code
@Test
public void testListChildNodes() throws SAXException, IOException {
    DocumentBuilder db = JAXPUtils.getDocumentBuilder();
    InputStream is = this.getClass().getClassLoader().getResourceAsStream("taskdefs/optional/junit/matches.xml");
    Document doc = db.parse(is);
    NodeList nl = DOMUtil.listChildNodes(doc.getDocumentElement(), new FooNodeFilter(), true);
    assertEquals("expecting 3", 3, nl.getLength());
}
Example 66
Project: apps-for-android-master  File: UpdateChecker.java View source code
@SuppressWarnings("finally")
public int getLatestVersionCode() {
    int version = 0;
    try {
        URLConnection cn;
        URL url = new URL("http://apps-for-android.googlecode.com/svn/trunk/CLiCkin2DaBeaT/AndroidManifest.xml");
        cn = url.openConnection();
        cn.connect();
        InputStream stream = cn.getInputStream();
        DocumentBuilder docBuild = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document manifestDoc = docBuild.parse(stream);
        NodeList manifestNodeList = manifestDoc.getElementsByTagName("manifest");
        String versionStr = manifestNodeList.item(0).getAttributes().getNamedItem("android:versionCode").getNodeValue();
        version = Integer.parseInt(versionStr);
        NodeList clcNodeList = manifestDoc.getElementsByTagName("clc");
        marketId = clcNodeList.item(0).getAttributes().getNamedItem("marketId").getNodeValue();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (SAXException e) {
        e.printStackTrace();
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    } catch (FactoryConfigurationError e) {
        e.printStackTrace();
    } finally {
        return version;
    }
}
Example 67
Project: ari-toolkit-master  File: TmNoticeXmlParser.java View source code
public TmNotice parse(String noticeXml) throws IOException, TmNoticeXmlParseException {
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    try {
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        Document document = documentBuilder.parse(new ByteArrayInputStream(noticeXml.getBytes()));
        XMLDocument xmlDocument = new XMLDocument(document.getDocumentElement());
        TmNotice tmNotice = new TmNotice();
        tmNotice.setId(xmlDocument.getNodeValue("/notice/id/text()"));
        String notBeforeDateTime = xmlDocument.getNodeValue("/notice/notBefore/text()");
        tmNotice.setNotBeforeDateTime(EPPDateFormatter.fromXSDateTime(notBeforeDateTime));
        String notAfterDateTime = xmlDocument.getNodeValue("/notice/notAfter/text()");
        tmNotice.setNotAfterDateTime(EPPDateFormatter.fromXSDateTime(notAfterDateTime));
        tmNotice.setLabel(xmlDocument.getNodeValue("/notice/label/text()"));
        TmClaimXmlParser claimXmlParser = new TmClaimXmlParser();
        NodeList elements = xmlDocument.getElements("/notice/claim");
        if (elements != null) {
            for (int i = 0; i < elements.getLength(); i++) {
                tmNotice.addClaim(claimXmlParser.parse(elements.item(i)));
            }
        }
        return tmNotice;
    } catch (ParserConfigurationException e) {
        throw new TmNoticeXmlParseException(e);
    } catch (SAXException e) {
        throw new TmNoticeXmlParseException(e);
    } catch (XPathExpressionException e) {
        throw new TmNoticeXmlParseException(e);
    }
}
Example 68
Project: arinc_838-master  File: CrcCalculatorTestCommon.java View source code
public static Map<BigInteger, byte[]> getExpectedCrcs(String crcType) throws Exception {
    Map<BigInteger, byte[]> result = new HashMap<BigInteger, byte[]>();
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document dom = db.parse("src/test/resources/crc_test_files/CRC_Expected_Values.xml");
    NodeList nl = dom.getElementsByTagName("test_file");
    for (int i = 0; i < nl.getLength(); i++) {
        Element el = (Element) nl.item(i);
        String crc = el.getAttribute(crcType).substring(2);
        result.put(new BigInteger(crc, 16), getBytes(el.getAttribute("name")));
    }
    return result;
}
Example 69
Project: ARTPart-master  File: Support_Xml.java View source code
public static Document domOf(String xml) throws Exception {
    // DocumentBuilderTest assumes we're using DocumentBuilder to do this parsing!
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setCoalescing(true);
    dbf.setExpandEntityReferences(true);
    ByteArrayInputStream stream = new ByteArrayInputStream(xml.getBytes());
    DocumentBuilder builder = dbf.newDocumentBuilder();
    return builder.parse(stream);
}
Example 70
Project: Aspose_for_Apache_POI-master  File: XMLMailMerge.java View source code
public static void main(String[] args) throws Exception {
    String dataPath = "src/asposefeatures/mailmerge/mailmergefromxmldatasource/data/";
    // Use DocumentBuilder from the javax.xml.parsers package and Document class from the org.w3c.dom package to read
    // the XML data file and store it in memory.
    DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    // Parse the XML data.
    org.w3c.dom.Document xmlData = db.parse(dataPath + "Customers.xml");
    // Open a template document.
    Document doc = new Document(dataPath + "mergeDoc.doc");
    // Note that this class also works with a single repeatable region (and any nested regions).
    // To merge multiple regions at the same time from a single XML data source, use the XmlMailMergeDataSet class.
    // e.g doc.getMailMerge().executeWithRegions(new XmlMailMergeDataSet(xmlData));
    doc.getMailMerge().execute(new XmlMailMergeDataTable(xmlData, "customer"));
    // Save the output document.
    doc.save(dataPath + "AsposeMailMerge.doc");
    System.out.println("Process Completed Successfully.");
}
Example 71
Project: Aspose_Java_for_Docx4j-master  File: XMLMailMerge.java View source code
public static void main(String[] args) throws Exception {
    String dataPath = "src/asposefeatures/mailmerge/mailmergefromxmldatasource/data/";
    // Use DocumentBuilder from the javax.xml.parsers package and Document class from the org.w3c.dom package to read
    // the XML data file and store it in memory.
    DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    // Parse the XML data.
    org.w3c.dom.Document xmlData = db.parse(dataPath + "Customers.xml");
    // Open a template document.
    Document doc = new Document(dataPath + "mergeDoc.doc");
    // Note that this class also works with a single repeatable region (and any nested regions).
    // To merge multiple regions at the same time from a single XML data source, use the XmlMailMergeDataSet class.
    // e.g doc.getMailMerge().executeWithRegions(new XmlMailMergeDataSet(xmlData));
    doc.getMailMerge().execute(new XmlMailMergeDataTable(xmlData, "customer"));
    // Save the output document.
    doc.save(dataPath + "AsposeMailMerge.doc");
}
Example 72
Project: Aspose_Words_for_Apache_POI-master  File: XMLMailMerge.java View source code
public static void main(String[] args) throws Exception {
    String dataPath = "src/asposefeatures/mailmerge/mailmergefromxmldatasource/data/";
    // Use DocumentBuilder from the javax.xml.parsers package and Document class from the org.w3c.dom package to read
    // the XML data file and store it in memory.
    DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    // Parse the XML data.
    org.w3c.dom.Document xmlData = db.parse(dataPath + "Customers.xml");
    // Open a template document.
    Document doc = new Document(dataPath + "mergeDoc.doc");
    // Note that this class also works with a single repeatable region (and any nested regions).
    // To merge multiple regions at the same time from a single XML data source, use the XmlMailMergeDataSet class.
    // e.g doc.getMailMerge().executeWithRegions(new XmlMailMergeDataSet(xmlData));
    doc.getMailMerge().execute(new XmlMailMergeDataTable(xmlData, "customer"));
    // Save the output document.
    doc.save(dataPath + "AsposeMailMerge.doc");
    System.out.println("Process Completed Successfully.");
}
Example 73
Project: Aspose_Words_Java-master  File: XMLMailMerge.java View source code
public static void main(String[] args) throws Exception {
    // The path to the documents directory.
    String dataDir = Utils.getDataDir(XMLMailMerge.class);
    // Use DocumentBuilder from the javax.xml.parsers package and Document class from the org.w3c.dom package to read
    // the XML data file and store it in memory.
    DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    // Parse the XML data.
    org.w3c.dom.Document xmlData = db.parse(dataDir + "Customers.xml");
    // Open a template document.
    Document doc = new Document(dataDir + "mergeDoc.doc");
    // Note that this class also works with a single repeatable region (and any nested regions).
    // To merge multiple regions at the same time from a single XML data source, use the XmlMailMergeDataSet class.
    // e.g doc.getMailMerge().executeWithRegions(new XmlMailMergeDataSet(xmlData));
    doc.getMailMerge().execute(new XmlMailMergeDataTable(xmlData, "customer"));
    // Save the output document.
    doc.save(dataDir + "AsposeMailMerge.doc");
}
Example 74
Project: async-rest-client-master  File: XML.java View source code
/**
     * Parse an InputStream as DOM.
     */
public static Document fromInputStream(InputStream in, String encoding) {
    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        DocumentBuilder builder = factory.newDocumentBuilder();
        InputSource is = new InputSource(in);
        is.setEncoding(encoding);
        return builder.parse(is);
    } catch (ParserConfigurationExceptionSAXException | IOException |  e) {
        throw new RuntimeException(e);
    }
}
Example 75
Project: atlas-lb-master  File: SchemaValidator.java View source code
public Object readFrom(Class<Object> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream inputStream) throws IOException, WebApplicationException {
    if (httpHeaders.get("HTTP_VERB") == null)
        return null;
    DocumentBuilderFactory factory;
    DocumentBuilder builder;
    Document document;
    document = new DocumentImpl();
    final String W3C_XML_SCHEMA = "http://www.w3.org/2001/XMLSchema";
    try {
        factory = DocumentBuilderFactory.newInstance();
        factory.setValidating(false);
        factory.setNamespaceAware(true);
        SchemaFactory schemaFactory = SchemaFactory.newInstance(W3C_XML_SCHEMA);
        factory.setSchema(schemaFactory.newSchema(new Source[] { new StreamSource("com/rackspace.cloud/service/loadbalancing/xsd/LoadBalancerApi.xsd") }));
        builder = factory.newDocumentBuilder();
        builder.setErrorHandler(new SimpleErrorHandler());
        document = builder.parse(new InputSource("contacts.xml"));
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    } catch (SAXException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return document.getDocumentElement();
}
Example 76
Project: azzyzt_jee_tools-master  File: AzzyztProperties.java View source code
public static AzzyztProperties fromXml(String xml) throws Exception {
    try {
        AzzyztProperties result = new AzzyztProperties();
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        InputSource is = new InputSource();
        is.setCharacterStream(new StringReader(xml));
        Document doc = db.parse(is);
        XPathFactory xPathFactory = XPathFactory.newInstance();
        XPath xpath = xPathFactory.newXPath();
        String expr = "/azzyzted_project/azzyzt_version";
        NodeList nodes = (NodeList) xpath.evaluate(expr, doc, XPathConstants.NODESET);
        if (nodes.getLength() == 1) {
            String azzyztVersion = nodes.item(0).getTextContent();
            result.setVersion(azzyztVersion);
            return result;
        }
    } catch (Exception e) {
    }
    throw new Exception("Can't parse AzzyztProperties from string\n\"" + xml + "\"");
}
Example 77
Project: betsy-master  File: TimeoutIOOperations.java View source code
/**
     *
     * Proofs if some process failed.
     *
     * @param directory The directory of the result files.
     * @return Returns false, if one or more tests failed.
     */
public static boolean testsAreCorrect(String directory) {
    String directoryName = Objects.requireNonNull(Objects.requireNonNull(directory, "The category can't be null."), "The testDirectory can't be null.") + "/reports";
    List<Path> files = FileTasks.findAllInFolder(Paths.get(directoryName), "TESTS-TestSuites.xml");
    for (Path path : files) {
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document document = builder.parse(path.toFile());
            document.getDocumentElement();
            NodeList testCases = document.getElementsByTagName("testsuite");
            int countFailures = 0;
            for (int i = 0; i < testCases.getLength(); i++) {
                Node testcase = testCases.item(i);
                NamedNodeMap attributes = testcase.getAttributes();
                Node failures = attributes.getNamedItem("failures");
                int value = Integer.parseInt(failures.getNodeValue());
                countFailures = countFailures + value;
            }
            if (countFailures > 0) {
                return false;
            }
        } catch (IOException e) {
            LOGGER.info("Couldn't read the file: " + path.getFileName());
        } catch (ParserConfigurationExceptionSAXException |  e) {
            LOGGER.info("Couldn't parse the file: " + path.getFileName());
        }
    }
    return true;
}
Example 78
Project: bi-platform-v2-master  File: XmlW3CHelper.java View source code
public static final Document getDomFromString(final String str) {
    DocumentBuilderFactory dbf;
    DocumentBuilder db;
    Document doc;
    if (str == null) {
        //$NON-NLS-1$
        throw new IllegalArgumentException("The source string can not be null");
    }
    try {
        // Check and open XML document
        dbf = DocumentBuilderFactory.newInstance();
        db = dbf.newDocumentBuilder();
        doc = db.parse(new InputSource(new java.io.StringReader(str)));
        return doc;
    } catch (Exception e) {
        Logger.error(XmlW3CHelper.class.getName(), Messages.getInstance().getErrorString("XmlHelper.ERROR_0008_GET_DOM_FROM_STRING_ERROR", e.getMessage()), e);
    }
    return null;
}
Example 79
Project: BingAds-Java-SDK-master  File: FakeApiTest.java View source code
@Override
public List<StringHeader> get() {
    String ns = "https://bingads.microsoft.com/CampaignManagement/v9";
    StringHeader trackingIdHeader;
    try {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = dbf.newDocumentBuilder();
        Document doc = builder.newDocument();
        Element customElement = doc.createElement("TrackingId");
        customElement.appendChild(doc.createTextNode("track123"));
        trackingIdHeader = new StringHeader(new QName(ns, "TrackingId"), customElement.getTextContent());
    } catch (ParserConfigurationException ex) {
        Logger.getLogger(BulkServiceTest.class.getName()).log(Level.SEVERE, null, ex);
        return null;
    } catch (DOMException ex) {
        Logger.getLogger(BulkServiceTest.class.getName()).log(Level.SEVERE, null, ex);
        return null;
    }
    List<StringHeader> headers = new ArrayList<StringHeader>();
    headers.add(trackingIdHeader);
    return headers;
}
Example 80
Project: bonita-web-master  File: XMLExpressionsUtilTest.java View source code
@Test
public void should_parseExpression_do_not_modify_dependencies() throws Exception {
    //given
    XMLExpressionsUtil xmlExpressionsUtil = new XMLExpressionsUtil();
    String expressionParentNodeName = "script";
    String expressionTagName = "input-parameter";
    String fileName = "formsWithExpressionDependencies.xml";
    File xmlFile = new File(getClass().getClassLoader().getResource(fileName).toURI());
    if (!xmlFile.exists()) {
        throw new IllegalStateException("Recource File missing:" + fileName);
    }
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
    Document doc = dBuilder.parse(xmlFile);
    Node expressionParentNode = null;
    NodeList nodeList = doc.getElementsByTagName(expressionTagName);
    for (int i = 0; i < nodeList.getLength(); i++) {
        if (nodeList.item(i).getAttributes().getNamedItem("name").getNodeValue().equals(expressionParentNodeName)) {
            expressionParentNode = nodeList.item(i);
        }
    }
    assertNotNull("Cannot retrieve the Expression Node with name: " + expressionParentNodeName, expressionParentNode);
    //when
    Expression generatedExpression = xmlExpressionsUtil.parseExpression(expressionParentNodeName, expressionParentNode);
    //then 
    assertEquals("script:<pattern-expression>", generatedExpression.getName());
    assertEquals(generatedExpression.getDependencies().get(0).getName(), "myId");
}
Example 81
Project: bourgogne-master  File: Config.java View source code
void read(File config) throws ParserConfigurationException, SAXException, IOException, ParseException, XPathExpressionException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    DocumentBuilder builder;
    Document doc = null;
    XPathExpression expr = null;
    builder = factory.newDocumentBuilder();
    doc = builder.parse(config);
    // Create a XPathFactory
    XPathFactory xFactory = XPathFactory.newInstance();
    // Create a XPathObject
    XPath xpath = xFactory.newXPath();
    // Run the query and get values
    id = Integer.parseInt((String) xpath.compile("//config/id/text()").evaluate(doc, XPathConstants.STRING));
    name = (String) xpath.compile("//config/name/text()").evaluate(doc, XPathConstants.STRING);
    format = (String) xpath.compile("//config/format/text()").evaluate(doc, XPathConstants.STRING);
    URI = (String) xpath.compile("//config/URI/text()").evaluate(doc, XPathConstants.STRING);
}
Example 82
Project: bpelunit-master  File: ToolUtil.java View source code
public static Node parseSendBlockWithException(XMLTestSuite suite, String sendXML) throws ParserConfigurationException, SAXException, IOException {
    if ("".equals(sendXML))
        return null;
    Map<Object, Object> namespaceMap = new HashMap<Object, Object>();
    // Add dummy element.
    suite.newCursor().getAllNamespaces(namespaceMap);
    StringBuffer dummyElement = new StringBuffer();
    dummyElement.append("<dummy ");
    for (Object prefix : namespaceMap.keySet()) {
        dummyElement.append("xmlns:" + prefix + "=\"" + namespaceMap.get(prefix) + "\" ");
    }
    dummyElement.append(">");
    dummyElement.append(sendXML);
    dummyElement.append("</dummy>");
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document document = builder.parse(new InputSource(new StringReader(dummyElement.toString())));
    // dummy node
    assert document.getFirstChild() != null;
    // root node
    assert document.getFirstChild().getFirstChild() != null;
    return document.getFirstChild().getFirstChild();
}
Example 83
Project: buck-master  File: XmlDomParser.java View source code
public static Document parse(InputSource xml, boolean namespaceAware) throws IOException, SAXException {
    DocumentBuilder docBuilder;
    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        if (namespaceAware) {
            factory.setNamespaceAware(namespaceAware);
        }
        docBuilder = factory.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        throw new RuntimeException(e);
    }
    return docBuilder.parse(xml);
}
Example 84
Project: buckminster-master  File: JNLPResource.java View source code
public void parseJNLP(URL jnlp) throws JNLPException {
    try {
        URLConnection conn = jnlp.openConnection();
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        ByteArrayOutputStream jnlpBuffer = new ByteArrayOutputStream();
        Utils.streamCopy(conn.getInputStream(), jnlpBuffer);
        jnlpBuffer.close();
        m_document = builder.parse(new ByteArrayInputStream(jnlpBuffer.toByteArray()));
        m_lastModified = new Date(conn.getLastModified());
        m_content = jnlpBuffer.toString();
    } catch (Exception e) {
        throw new JNLPException(Messages.getString("can_not_read_materialization_wizard_resource"), Messages.getString("try_again_and_if_the_problem_persists_please_report_the_problem"), BootstrapConstants.ERROR_CODE_JNLP_SAX_EXCEPTION, e);
    }
}
Example 85
Project: bus-n-train-master  File: XmlUtil.java View source code
public static Document unmarshall(String xmlStr) throws XmlUtilException {
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    try {
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        InputSource inputSource = new InputSource();
        inputSource.setCharacterStream(new StringReader(xmlStr));
        return documentBuilder.parse(inputSource);
    } catch (ParserConfigurationException e) {
        Log.e(TAG, e.getMessage(), e);
        throw new XmlUtilException(ERROR_CODE.PARSE_ERROR);
    } catch (SAXException e) {
        Log.e(TAG, e.getMessage(), e);
        throw new XmlUtilException(ERROR_CODE.SAX_ERROR);
    } catch (IOException e) {
        Log.e(TAG, e.getMessage(), e);
        throw new XmlUtilException(ERROR_CODE.IO_ERROR);
    }
}
Example 86
Project: camel-master  File: StockQuoteResponseProcessor.java View source code
public void process(Exchange exchange) throws Exception {
    LOG.info("Crafting standard response in StockQuoteResponseProcessor");
    InputStream is = getClass().getResourceAsStream("/stockquote-response.xml");
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document doc = db.parse(is);
    if (exchange.getIn().getHeader("setin") != null && exchange.getIn().getHeader("setin").equals("true")) {
        exchange.getIn().setBody(doc);
    } else {
        exchange.getOut().setBody(doc);
    }
}
Example 87
Project: cas-master  File: SamlCompliantLogoutMessageCreatorTests.java View source code
@Test
public void verifyMessageBuilding() throws Exception {
    final WebApplicationService service = mock(WebApplicationService.class);
    when(service.getOriginalUrl()).thenReturn(RegisteredServiceTestUtils.CONST_TEST_URL);
    final URL logoutUrl = new URL(service.getOriginalUrl());
    final DefaultLogoutRequest request = new DefaultLogoutRequest("TICKET-ID", service, logoutUrl);
    final String msg = builder.create(request);
    final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    final DocumentBuilder builder = factory.newDocumentBuilder();
    final InputStream is = new ByteArrayInputStream(msg.getBytes());
    final Document document = builder.parse(is);
    final NodeList list = document.getDocumentElement().getElementsByTagName("samlp:SessionIndex");
    assertEquals(list.getLength(), 1);
    assertEquals(list.item(0).getTextContent(), request.getTicketId());
}
Example 88
Project: Cattles-master  File: XMLOperationSchedulingFramework.java View source code
private void init() {
    // TODO Auto-generated method stub
    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        this.xmlDocument = builder.parse(Constant.SCHEDULING_FRAMEWORK_CONF_PATH);
        xmlDocument.normalize();
        logger.info("initialize successfully!");
    } catch (FileNotFoundException e) {
        System.out.println(e.getMessage());
    } catch (ParserConfigurationException e) {
        System.out.println(e.getMessage());
    } catch (SAXException e) {
        System.out.println(e.getMessage());
    } catch (IOException e) {
        System.out.println(e.getMessage());
    }
}
Example 89
Project: ChemSpot-master  File: XMLCollectionReader.java View source code
protected Document getNextDocument() throws CollectionException, IOException {
    if (currentDocument >= numDocuments)
        throw new CollectionException();
    File file = files.get(currentDocument++);
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder;
    try {
        builder = factory.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        throw new IOException(e);
    }
    Document document;
    try {
        document = builder.parse(file);
    } catch (SAXException e) {
        throw new IOException(e);
    }
    return document;
}
Example 90
Project: chiba-core-sandbox-idega-master  File: SessionSerializerTest.java View source code
/**
     * Sets up the test.
     *
     * @throws Exception in any error occurred during setup.
     */
protected void setUp() throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    factory.setValidating(false);
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document form = builder.parse(getClass().getResourceAsStream("session.xhtml"));
    String path = getClass().getResource("session.xhtml").getPath();
    this.baseURI = "file://" + path.substring(0, path.lastIndexOf("session.xhtml"));
    this.processor = new ChibaBean();
    this.processor.setBaseURI(baseURI);
    this.processor.setXMLContainer(form);
    this.processor.init();
}
Example 91
Project: ci.maven-master  File: PluginConfigXmlIT.java View source code
@Test
public void testXmlElements() throws Exception {
    File in = new File(CONFIG_XML);
    FileInputStream input = new FileInputStream(in);
    // get input XML Document 
    DocumentBuilderFactory inputBuilderFactory = DocumentBuilderFactory.newInstance();
    inputBuilderFactory.setIgnoringComments(true);
    inputBuilderFactory.setCoalescing(true);
    inputBuilderFactory.setIgnoringElementContentWhitespace(true);
    inputBuilderFactory.setValidating(false);
    DocumentBuilder inputBuilder = inputBuilderFactory.newDocumentBuilder();
    Document inputDoc = inputBuilder.parse(input);
    // parse input XML Document
    XPath xPath = XPathFactory.newInstance().newXPath();
    String expression = "/liberty-plugin-config/applicationFilename";
    NodeList nodes = (NodeList) xPath.compile(expression).evaluate(inputDoc, XPathConstants.NODESET);
    Assert.assertEquals("Number of <applicationFilename/> element ==>", 0, nodes.getLength());
}
Example 92
Project: CISEN-master  File: BaseXMLParser.java View source code
private Document toDocument(String xmlString) throws Exception {
    if (xmlString == null || xmlString.isEmpty()) {
        throw new IllegalArgumentException("xml cannot be empty.");
    }
    DocumentBuilderFactory documentFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder documentBuilder = documentFactory.newDocumentBuilder();
    InputStream is = new ByteArrayInputStream(xmlString.getBytes());
    return documentBuilder.parse(is);
}
Example 93
Project: clearnlp-master  File: DBPediaOntologyExtractor.java View source code
public void extract(InputStream in, PrintStream out) throws Exception {
    DocumentBuilderFactory dFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = dFactory.newDocumentBuilder();
    Document doc = builder.parse(in);
    NodeList classes = doc.getElementsByTagName(OWL_CLASS);
    int i, j, len, size = classes.getLength();
    String rdfAbout, rdfResource;
    Element owlClass, subClass;
    NodeList subClasses;
    StringBuilder sb = new StringBuilder();
    for (i = 0; i < size; i++) {
        sb.setLength(0);
        ;
        owlClass = (Element) classes.item(i);
        subClasses = owlClass.getElementsByTagName(RDFS_SUBCLASS_OF);
        len = subClasses.getLength();
        rdfAbout = extractType(XmlUtils.getTrimmedAttribute(owlClass, RDF_ABOUT));
        sb.append(extractType(rdfAbout));
        for (j = 0; j < len; j++) {
            subClass = (Element) subClasses.item(j);
            rdfResource = XmlUtils.getTrimmedAttribute(subClass, RDF_RESOURCE);
            if (rdfResource.startsWith(DBPEDIA_ORG_ONTOLOGY)) {
                sb.append(StringConst.TAB);
                sb.append(extractType(rdfResource));
            }
        }
        if (rdfAbout.equals("Mayor"))
            sb.append("\tPolitician");
        out.println(sb.toString());
    }
    out.close();
}
Example 94
Project: clearpool-master  File: XMLUtil.java View source code
public static Document createDocument(String path) throws Exception {
    Reader reader = getResourceAsReader(path);
    InputSource inputSource = new InputSource(reader);
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setValidating(true);
    factory.setNamespaceAware(true);
    factory.setAttribute(XMLUtil.SCHEMA_LANGUAGE_ATTRIBUTE, XMLUtil.XSD_SCHEMA_LANGUAGE);
    DocumentBuilder builder = factory.newDocumentBuilder();
    builder.setEntityResolver(new XMLEntityResolver());
    builder.setErrorHandler(new XMLErrorHandler());
    return builder.parse(inputSource);
}
Example 95
Project: cmestemp22-master  File: DocumentCreatorFake.java View source code
/**
     * Returns a dummy document.
     * 
     * @param inFileName
     *            the name of the file
     * @return an xml document.
     * @throws Exception
     *             Thrown when cannot create the xml document.
     */
public Document execute(final String inFileName) throws Exception {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document xmlDoc = db.newDocument();
    xmlDoc.createElement("Title");
    xmlDoc.setNodeValue("theme title");
    xmlDoc.createElement("Description");
    xmlDoc.setNodeValue("theme description");
    xmlDoc.createElement("AuthorName");
    xmlDoc.setNodeValue("author name");
    xmlDoc.createElement("AuthorEmail");
    xmlDoc.setNodeValue("author email");
    return xmlDoc;
}
Example 96
Project: collect-master  File: ResponseMessageParser.java View source code
public String parseXMLMessage() {
    String message = null;
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder;
    try {
        builder = dbFactory.newDocumentBuilder();
        Document doc = null;
        try {
            String httpEntityString = EntityUtils.toString(httpEntity);
            doc = builder.parse(new ByteArrayInputStream(httpEntityString.getBytes()));
            doc.getDocumentElement().normalize();
            if (doc.getElementsByTagName(MESSAGE_XML_TAG).item(0) != null) {
                message = doc.getElementsByTagName(MESSAGE_XML_TAG).item(0).getTextContent();
            } else {
                isValid = false;
            }
            return message;
        } catch (SAXExceptionIOException |  e) {
            Timber.e(e, "Error parsing XML message due to %s ", e.getMessage());
            isValid = false;
        }
        return message;
    } catch (ParserConfigurationException e) {
        Timber.e(e, "Error parsing XML message due to %s ", e.getMessage());
        isValid = false;
    }
    return message;
}
Example 97
Project: com.idega.xformsmanager-master  File: ComponentsGeneratorImpl.java View source code
public Document generateHtmlRepresentation(Document xform) {
    try {
        DocumentBuilder documentBuilder = XmlUtil.getDocumentBuilder();
        Document generatedDocument = documentBuilder.newDocument();
        FluxAdapter adapter = new FluxAdapter();
        adapter.setXForms(xform);
        adapter.init();
        UIGenerator gen = getHtmlRepresentationGenerator();
        synchronized (gen) {
            gen.setInput(xform);
            gen.setOutput(generatedDocument);
            gen.generate();
        }
        return generatedDocument;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
Example 98
Project: Consent2Share-master  File: SpiritPepUtil.java View source code
/**
	 * @param xml
	 *            - The xml-file to be parsed
	 * @return an element-array
	 * @throws ParserConfigurationException
	 * @throws FileNotFoundException
	 * @throws SAXException
	 * @throws IOException
	 */
public static Element[] parse(File xml) throws ParserConfigurationException, FileNotFoundException, SAXException, IOException {
    if (xml == null) {
        logger.warn("parse: no addAttrib-Xml passed -> makes this test a bit useless");
        return null;
    }
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    dbf.setIgnoringElementContentWhitespace(true);
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document doc = db.parse(new FileInputStream(xml));
    logger.debug("parse: \n" + _documentToString(doc));
    Element[] els = new Element[] { doc.getDocumentElement() };
    return els;
}
Example 99
Project: consulo-master  File: mxXmlUtils.java View source code
/**
   * Returns a new document for the given XML string.
   *
   * @param xml String that represents the XML data.
   * @return Returns a new XML document.
   */
public static Document parseXml(String xml) {
    try {
        DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
        return docBuilder.parse(new InputSource(new StringReader(xml)));
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
Example 100
Project: CopyTo-master  File: FormParser.java View source code
public Collection<Form> parse(InputStream is) {
    InputSource source = new InputSource(is);
    try {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setValidating(false);
        DocumentBuilder db = dbf.newDocumentBuilder();
        db.setEntityResolver(new EntityResolver() {

            public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
                return new InputSource(new StringReader(""));
            }
        });
        Document document = db.parse(source);
        NodeList nodes = (NodeList) formPath.evaluate(document.getDocumentElement(), XPathConstants.NODESET);
        Collection<Form> forms = new ArrayList<Form>(nodes.getLength());
        for (int i = 0; i < nodes.getLength(); ++i) {
            Node node = nodes.item(i);
            forms.add(new Form(node));
        }
        return forms;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return Collections.emptyList();
}
Example 101
Project: cosmo-master  File: DomWriterTest.java View source code
@Test
public void testWriteNode() throws ParserConfigurationException, XMLStreamException, IOException {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = dbf.newDocumentBuilder();
    Document doc = builder.newDocument();
    // create the root element node
    Element element = doc.createElementNS("http://apple.com/ns/ical/", "E:calendar-color");
    element.setAttribute("xmlns:E", "http://apple.com/ns/ical/");
    element.appendChild(doc.createTextNode("#711A76FF"));
    //The element above gets translated into an invalid element
    //Apple PROPFIND request is broken
    //<E:calendar-color xmlns:E="http://apple.com/ns/ical/" xmlns:E="http://apple.com/ns/ical/">#711A76FF</E:calendar-color>             
    Assert.assertEquals("<E:calendar-color xmlns:E=\"http://apple.com/ns/ical/\">#711A76FF</E:calendar-color>", DomWriter.write(element));
}