Java Code Examples for org.openide.xml.XMLUtil#parse()

The following examples show how to use org.openide.xml.XMLUtil#parse() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: WebFreeFormActionProvider.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * Reads a generated script if it exists, else create a skeleton.
 * @param scriptPath e.g. {@link #FILE_SCRIPT_PATH} or {@link #GENERAL_SCRIPT_PATH}
 * @return script document.
 */
Document readCustomScript(String scriptPath) throws IOException, SAXException {

    Document script = null;
    FileObject scriptFile = helper.getProjectDirectory().getFileObject(scriptPath);
    if (scriptFile != null) {
        InputStream is = scriptFile.getInputStream();
        try {
            script = XMLUtil.parse(new InputSource(is), false, true, null, null);
        } finally {
            is.close();
        }
    }
    
    return script;
}
 
Example 2
Source File: GrailsPluginSupport.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private GrailsPlugin getPluginFromInputStream(InputStream inputStream, File path) throws Exception {
    final Document doc = XMLUtil.parse(new InputSource(inputStream), false, false, null, null);
    final Node root = doc.getFirstChild();
    final String name = root.getAttributes().getNamedItem("name").getTextContent(); //NOI18N
    String version = null;
    String description = null;
    if (root.getAttributes().getNamedItem("version") != null) { //NOI18N
        version = root.getAttributes().getNamedItem("version").getTextContent(); //NOI18N
    }
    if (doc.getElementsByTagName("title") != null // NOI18N
            && doc.getElementsByTagName("title").getLength() > 0) { //NOI18N
        description = doc.getElementsByTagName("title") // NOI18N
                .item(0).getTextContent(); //NOI18N
    }
    return new GrailsPlugin(name, version, description, path);
}
 
Example 3
Source File: GlobalSourceForBinaryImpl.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private String parseCNB(final ZipEntry projectXML) throws IOException {
    Document doc;
    InputStream is = nbSrcZip.getInputStream(projectXML);
    try {
        doc = XMLUtil.parse(new InputSource(is), false, true, null, null);
    } catch (SAXException e) {
        throw (IOException) new IOException(projectXML + ": " + e.toString()).initCause(e); // NOI18N
    } finally {
        is.close();
    }
    Element docel = doc.getDocumentElement();
    Element type = XMLUtil.findElement(docel, "type", "http://www.netbeans.org/ns/project/1"); // NOI18N
    String cnb = null;
    if (XMLUtil.findText(type).equals("org.netbeans.modules.apisupport.project")) { // NOI18N
        Element cfg = XMLUtil.findElement(docel, "configuration", "http://www.netbeans.org/ns/project/1"); // NOI18N
        Element data = XMLUtil.findElement(cfg, "data", null); // NOI18N
        if (data != null) {
            cnb = XMLUtil.findText(XMLUtil.findElement(data, "code-name-base", null)); // NOI18N
        }
    }
    return cnb;
}
 
Example 4
Source File: ParseTreeToXmlTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testParseTreeToXml() throws IOException, SAXException {
    final ANTLRInputStream in = new ANTLRInputStream(TEST_JSON);
    final JsonLexer lex = new JsonLexer(in, true);
    final CommonTokenStream tokens = new CommonTokenStream(lex);
    final JsonParser parser = new JsonParser(tokens);
    final JsonParser.JsonContext ctx = parser.json();
    final ParseTreeToXml visitor = new ParseTreeToXml(lex, parser);
    final Document doc = visitor.visit(ctx);
    final Document exp = XMLUtil.parse(
            new InputSource(new StringReader(TEST_JSON_RESULT)),
            false,
            false,
            null,
            null);
    assertEquals(
        ParseTreeToXml.stringify(exp),
        ParseTreeToXml.stringify(doc));
}
 
Example 5
Source File: ModuleDescription.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static void readModulesXml(FileObject modulesXML, List<ModuleDescription> moduleDescriptions) throws SAXException, IOException {
    if (modulesXML == null)
        return ;

    try (InputStream in = modulesXML.getInputStream()) {
        Document doc = XMLUtil.parse(new InputSource(in), false, true, null, null);
        NodeList modules = doc.getDocumentElement().getElementsByTagName("module");

        for (int i = 0; i < modules.getLength(); i++) {
            moduleDescriptions.add(parseModule((Element) modules.item(i)));
        }
    }
}
 
Example 6
Source File: JmeTestsWizardIterator.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private static void filterProjectXML(FileObject fo, ZipInputStream str, String name) throws IOException {
    try {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        FileUtil.copy(str, baos);
        Document doc = XMLUtil.parse(new InputSource(new ByteArrayInputStream(baos.toByteArray())), false, false, null, null);
        NodeList nl = doc.getDocumentElement().getElementsByTagName("name");
        if (nl != null) {
            for (int i = 0; i < nl.getLength(); i++) {
                Element el = (Element) nl.item(i);
                if (el.getParentNode() != null && "data".equals(el.getParentNode().getNodeName())) {
                    NodeList nl2 = el.getChildNodes();
                    if (nl2.getLength() > 0) {
                        nl2.item(0).setNodeValue(name);
                    }
                    break;
                }
            }
        }
        OutputStream out = fo.getOutputStream();
        try {
            XMLUtil.write(doc, out, "UTF-8");
        } finally {
            out.close();
        }
    } catch (Exception ex) {
        Exceptions.printStackTrace(ex);
        writeFile(str, fo);
    }

}
 
Example 7
Source File: apptypeWizardIterator.java    From visualvm with GNU General Public License v2.0 5 votes vote down vote up
private static void filterProjectXML(FileObject fo, ZipInputStream str, String name) throws IOException {
    try {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        FileUtil.copy(str, baos);
        Document doc = XMLUtil.parse(new InputSource(new ByteArrayInputStream(baos.toByteArray())), false, false, null, null);
        NodeList nl = doc.getDocumentElement().getElementsByTagName("name");
        if (nl != null) {
            for (int i = 0; i < nl.getLength(); i++) {
                Element el = (Element) nl.item(i);
                if (el.getParentNode() != null && "data".equals(el.getParentNode().getNodeName())) {
                    NodeList nl2 = el.getChildNodes();
                    if (nl2.getLength() > 0) {
                        nl2.item(0).setNodeValue(name);
                    }
                    break;
                }
            }
        }
        OutputStream out = fo.getOutputStream();
        try {
            XMLUtil.write(doc, out, "UTF-8");
        } finally {
            out.close();
        }
    } catch (Exception ex) {
        Exceptions.printStackTrace(ex);
        writeFile(str, fo);
    }

}
 
Example 8
Source File: ImportWorldForgeAction.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private void replaceMeshMatName(FileObject file) {
    InputStream stream = null;
    try {
        stream = file.getInputStream();
        Document doc = XMLUtil.parse(new InputSource(stream), false, false, null, null);
        stream.close();
        Element elem = doc.getDocumentElement();
        if (elem == null) {
            throw new IllegalStateException("Cannot find root mesh element");
        }
        Element submeshes = XmlHelper.findChildElement(elem, "submeshes");
        if (submeshes == null) {
            throw new IllegalStateException("Cannot find submeshes element");
        }
        Element submesh = XmlHelper.findChildElement(submeshes, "submesh");
        boolean changed = false;
        while (submesh != null) {
            String matName = submesh.getAttribute("material");
            String newName = removePastUnderScore(matName);
            if (!matName.equals(newName)) {
                Logger.getLogger(ImportWorldForgeAction.class.getName()).log(Level.INFO, "Change material name for {0}", file);
                submesh.setAttribute("material", newName);
                submesh = XmlHelper.findNextSiblingElement(submesh);
                changed = true;
            }
        }
        if (changed) {
            OutputStream out = file.getOutputStream();
            XMLUtil.write(doc, out, "UTF-8");
            out.close();
        }

    } catch (Exception ex) {
        Exceptions.printStackTrace(ex);
    } finally {
    }
}
 
Example 9
Source File: WorkspaceParser.java    From netbeans with Apache License 2.0 5 votes vote down vote up
void parseJSFLibraryRegistryV2() throws IOException {
    if (!workspace.getUserJSFLibraries().exists()) {
        return;
    }
    Document xml;
    try {
        xml = XMLUtil.parse(new InputSource(Utilities.toURI(workspace.getUserJSFLibraries()).toString()), false, true, XMLUtil.defaultErrorHandler(), null);
    } catch (SAXException e) {
        IOException ioe = (IOException) new IOException(workspace.getUserJSFLibraries() + ": " + e.toString()).initCause(e); // NOI18N
        throw ioe;
    }
    
    Element root = xml.getDocumentElement();
    if (!"JSFLibraryRegistry".equals(root.getLocalName()) || // NOI18N
        !JSF_LIB_NS.equals(root.getNamespaceURI())) {
        return;
    }
    for (Element el : XMLUtil.findSubElements(root)) {
        String libraryName = el.getAttribute("Name"); // NOI18N
        List<String> jars = new ArrayList<String>();
        for (Element file : XMLUtil.findSubElements(el)) {
            String path = file.getAttribute("SourceLocation"); // NOI18N
            if (!"false".equals(file.getAttribute("RelativeToWorkspace"))) { // NOI18N
                path = new File(workspace.getDirectory(), path).getPath();
            }
            jars.add(path);
        }
        // TODO: in Ganymede Javadoc/sources customization does not seem to be persisted. eclipse defect??
        workspace.addUserLibrary(libraryName, jars, null, null);
    }
}
 
Example 10
Source File: ProjectParser.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public static Facets readProjectFacets(File projectDir, Set<String> natures) throws IOException {
    if (!natures.contains("org.eclipse.wst.common.project.facet.core.nature")) { // NOI18N
        return null;
    }
    File f = new File(projectDir, ".settings/org.eclipse.wst.common.project.facet.core.xml"); // NOI18N
    if (!f.exists()) {
        return null;
    }
    Document doc;
    try {
        doc = XMLUtil.parse(new InputSource(Utilities.toURI(f).toString()), false, true, XMLUtil.defaultErrorHandler(), null);
    } catch (SAXException e) {
        IOException ioe = (IOException) new IOException(f + ": " + e.toString()).initCause(e); // NOI18N
        throw ioe;
    }
    Element root = doc.getDocumentElement();
    if (!"faceted-project".equals(root.getLocalName())) { // NOI18N
        return null;
    }
    
    List<Facets.Facet> facets = new ArrayList<Facets.Facet>();
    List<Element> elements = XMLUtil.findSubElements(root);
    for (Element element : elements) {
        if (!"installed".equals(element.getNodeName())) { // NOI18N
            continue;
        }
        String facet = element.getAttribute("facet"); // NOI18N
        String version = element.getAttribute("version"); // NOI18N
        if (facet != null && version != null) {
            facets.add(new Facets.Facet(facet, version));
        }
    }
    return new Facets(facets);
}
 
Example 11
Source File: XMLHintPreferences.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public static HintPreferencesProviderImpl from(@NonNull URI settings) {
    Reference<HintPreferencesProviderImpl> ref = uri2Cache.get(settings);
    HintPreferencesProviderImpl cachedResult = ref != null ? ref.get() : null;
    
    if (cachedResult != null) return cachedResult;
    
    Document doc = null;
    File file = Utilities.toFile(settings); //XXX: non-file:// scheme
    
    if (file.canRead()) {
        try(InputStream in = new BufferedInputStream(new FileInputStream(file))) {
            doc = XMLUtil.parse(new InputSource(in), false, false, null, EntityCatalog.getDefault());
        } catch (SAXException | IOException ex) {
            LOG.log(Level.FINE, null, ex);
        }
    }
    
    if (doc == null) {
        doc = XMLUtil.createDocument("configuration", null, "-//NetBeans//DTD Tool Configuration 1.0//EN", "http://www.netbeans.org/dtds/ToolConfiguration-1_0.dtd");
    }
    
    synchronized (uri2Cache) {
        ref = uri2Cache.get(settings);
        cachedResult = ref != null ? ref.get() : null;

        if (cachedResult != null) return cachedResult;
        
        uri2Cache.put(settings, new CleaneableSoftReference(cachedResult = new HintPreferencesProviderImpl(settings, doc), settings));
    }
    
    return cachedResult;
}
 
Example 12
Source File: GroovyJavaDemoWizardIterator.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static void filterProjectXML(FileObject fo, ZipInputStream str, String name) throws IOException {
    try {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        FileUtil.copy(str, baos);
        Document doc = XMLUtil.parse(new InputSource(new ByteArrayInputStream(baos.toByteArray())), false, false, null, null);
        NodeList nl = doc.getDocumentElement().getElementsByTagName("name");
        if (nl != null) {
            for (int i = 0; i < nl.getLength(); i++) {
                Element el = (Element) nl.item(i);
                if (el.getParentNode() != null && "data".equals(el.getParentNode().getNodeName())) {
                    NodeList nl2 = el.getChildNodes();
                    if (nl2.getLength() > 0) {
                        nl2.item(0).setNodeValue(name);
                    }
                    break;
                }
            }
        }
        OutputStream out = fo.getOutputStream();
        try {
            XMLUtil.write(doc, out, "UTF-8");
        } finally {
            out.close();
        }
    } catch (Exception ex) {
        Exceptions.printStackTrace(ex);
        writeFile(str, fo);
    }

}
 
Example 13
Source File: PHPSamplesWizardIterator.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static void filterProjectXML(FileObject fo, ZipInputStream str, String name) throws IOException {
    try {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        FileUtil.copy(str, baos);
        Document doc = XMLUtil.parse(new InputSource(new ByteArrayInputStream(baos.toByteArray())), false, false, null, null);
        NodeList nl = doc.getDocumentElement().getElementsByTagName("name");
        if (nl != null) {
            for (int i = 0; i < nl.getLength(); i++) {
                Element el = (Element) nl.item(i);
                if (el.getParentNode() != null && "data".equals(el.getParentNode().getNodeName())) {
                    NodeList nl2 = el.getChildNodes();
                    if (nl2.getLength() > 0) {
                        nl2.item(0).setNodeValue(name);
                    }
                    break;
                }
            }
        }
        OutputStream out = fo.getOutputStream();
        try {
            XMLUtil.write(doc, out, "UTF-8");
        } finally {
            out.close();
        }
    } catch (Exception ex) {
        Exceptions.printStackTrace(ex);
        writeFile(str, fo);
    }

}
 
Example 14
Source File: TestUtil.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Get a particular element in a test XML document.
 * Pass in a well-formed XML document and an element name to search for.
 * Must be exactly one such.
 */
public static Element createElementInDocument(String xml, String elementName, String elementNamespace) throws Exception {
    Document doc = XMLUtil.parse(new InputSource(new StringReader(xml)), false, true, null, null);
    NodeList nl = doc.getElementsByTagNameNS(elementNamespace, elementName);
    if (nl.getLength() != 1) {
        throw new IllegalArgumentException("Zero or more than one <" + elementName + ">s in \"" + xml + "\"");
    }
    return (Element)nl.item(0);
}
 
Example 15
Source File: ModuleList.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Try to find which files are part of a module's binary build (i.e. slated for NBM).
 * Tries to scan update tracking for the file, but also always adds in the module JAR
 * as a fallback (since this is the most important file for various purposes).
 * Note that update_tracking/*.xml is added as well as files it lists.
 */
private static Set<File> findBinaryNBMFiles(File cluster, String cnb, File jar) throws IOException {
    Set<File> files = new HashSet<File>();
    files.add(jar);
    File tracking = new File(new File(cluster, "update_tracking"), cnb.replace('.', '-') + ".xml"); // NOI18N
    if (tracking.isFile()) {
        files.add(tracking);
        Document doc;
        try {
            xmlFilesParsed++;
            timeSpentInXmlParsing -= System.currentTimeMillis();
            doc = XMLUtil.parse(new InputSource(Utilities.toURI(tracking).toString()), false, false, null, null);
            timeSpentInXmlParsing += System.currentTimeMillis();
        } catch (SAXException e) {
            throw (IOException) new IOException(e.toString()).initCause(e);
        }
        for (Element moduleVersion : XMLUtil.findSubElements(doc.getDocumentElement())) {
            if (moduleVersion.getTagName().equals("module_version") && moduleVersion.getAttribute("last").equals("true")) { // NOI18N
                for (Element fileEl : XMLUtil.findSubElements(moduleVersion)) {
                    if (fileEl.getTagName().equals("file")) { // NOI18N
                        String name = fileEl.getAttribute("name"); // NOI18N
                        File f = new File(cluster, name.replace('/', File.separatorChar));
                        if (f.isFile()) {
                            files.add(f);
                        }
                    }
                }
            }
        }
    }
    return files;
}
 
Example 16
Source File: DatabaseConnectionConvertorTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private void testWriteXml(String password, boolean savePassword,
        String goldenFileName) throws Exception {
    
    DatabaseConnection conn = new DatabaseConnection("org.bar.BarDriver", 
            "bar_driver", "jdbc:bar:localhost", "schema", "user", password,
            savePassword);
    
    DatabaseConnectionConvertor.create(conn);
    
    FileObject fo = Util.getConnectionsFolder().getChildren()[0];
    
    ErrorHandlerImpl errHandler = new ErrorHandlerImpl();
    Document doc = null;
    InputStream input = fo.getInputStream();
    try {
        doc = XMLUtil.parse(new InputSource(input), true, true, errHandler, EntityCatalog.getDefault());
    } finally {
        input.close();
    }
    
    assertFalse("DatabaseConnectionConvertor generates invalid XML acc to the DTD!", errHandler.error);
    
    Document goldenDoc = null;
    input = getClass().getResourceAsStream(goldenFileName);

    errHandler = new ErrorHandlerImpl();
    try {
        goldenDoc = XMLUtil.parse(new InputSource(input), true, true, errHandler, EntityCatalog.getDefault());
    } finally {
        input.close();
    }
    
    assertTrue(DOMCompare.compareDocuments(doc, goldenDoc));
    assertFalse("DatabaseConnectionConvertor generates invalid XML acc to the DTD!", errHandler.error);
}
 
Example 17
Source File: GoalsPanel.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static @CheckForNull Document loadPluginXml(File jar) {
    if (!jar.isFile() || !jar.getName().endsWith(".jar")) {
        return null;
    }
    LOG.log(Level.FINER, "parsing plugin.xml from {0}", jar);
        try {
        return XMLUtil.parse(new InputSource("jar:" + Utilities.toURI(jar) + "!/META-INF/maven/plugin.xml"), false, false, XMLUtil.defaultErrorHandler(), null);
    } catch (Exception x) {
        LOG.log(Level.FINE, "could not parse " + jar, x.toString());
        return null;
    }
}
 
Example 18
Source File: ModuleList.java    From netbeans with Apache License 2.0 4 votes vote down vote up
/**
 * Scans cluster on disk and fills <tt>entries</tt> with found module entries.
 * @param cluster Path to cluster dir
 * @param nbDestDir <tt>netbeans.dest.dir</tt> folder for NB.org modules, may be <tt>null</tt>
 * @param entries Map to be filled with module entries found in cluster
 * @param registerEntry Whether register entries in known entries in ModuleList
 * @param ci Cluster info, passed when scanning external cluster, may be <tt>null</tt>
 * @throws java.io.IOException
 */
public static ModuleList scanCluster(File cluster, @NullAllowed File nbDestDir, boolean registerEntry, ClusterInfo ci) throws IOException {
    Map<String, ModuleEntry> entries = new HashMap<String, ModuleEntry>();
    for (String moduleDir : MODULE_DIRS) {
        File dir = new File(cluster, moduleDir.replace('/', File.separatorChar));
        if (!dir.isDirectory()) {
            continue;
        }
        File[] jars = dir.listFiles();
        if (jars == null) {
            throw new IOException("Cannot examine dir " + dir); // NOI18N
        }
        scanJars(dir, ci, nbDestDir, cluster, entries, registerEntry, jars);
    }
    File configs = new File(new File(cluster, "config"), "Modules"); // NOI18N
    File[] xmls = configs.listFiles();
    if (xmls != null) {
        XPathExpression xpe = null;
        for (File xml : xmls) {
            String n = xml.getName();
            if (!n.endsWith(".xml")) { // NOI18N
                continue;
            }
            n = n.substring(0, n.length() - 4).replace('-', '.');
            if (entries.get(n) != null) {
                continue;
            }

            String res;
            Document doc;
            try {
                doc = XMLUtil.parse(new InputSource(Utilities.toURI(xml).toString()), false, false, null, EntityCatalog.getDefault());
                if (xpe == null) {
                    xpe = XPathFactory.newInstance().newXPath().compile("module/param[@name='jar']/text()");
                }
                res = xpe.evaluate(doc);
                File jar = new File(cluster, res);
                if (jar.exists()) {
                    scanJars(cluster, ci, nbDestDir, cluster, entries, registerEntry, jar);
                }
            } catch (Exception ex) {
                throw (IOException) new IOException(ex.toString()).initCause(ex);
            }
        }
    }
    LOG.log(Level.FINER, "scanCluster: " + cluster + " succeeded.");    // see ModuleListTest#testConcurrentScanning
    return new ModuleList(entries, nbDestDir);
}
 
Example 19
Source File: AuxiliaryConfigImplTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private static String loadXML(FileObject f) throws Exception {
    Document doc = XMLUtil.parse(new InputSource(f.getInputStream()), false, true, null, null);
    return AuxiliaryConfigImpl.elementToString(doc.getDocumentElement()).replaceAll("\n\\s*", "");
}
 
Example 20
Source File: TestUtil.java    From netbeans with Apache License 2.0 2 votes vote down vote up
/**
 * Create a context for completing some XML.
 * The XML text must be a well-formed document.
 * It must contain exactly one element name, attribute name,
 * attribute value, or text node ending in the string <samp>HERE</samp>.
 * The context will be that node (Element, Attribute, or Text) with
 * the suffix stripped off and the prefix set to the text preceding that suffix.
 */
public static HintContext createCompletion(String xml) throws Exception {
    Document doc = XMLUtil.parse(new InputSource(new StringReader(xml)), false, true, null, null);
    return findCompletion(doc.getDocumentElement(), doc);
}