org.openide.xml.XMLUtil Java Examples

The following examples show how to use org.openide.xml.XMLUtil. 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: FreeformProjectGenerator.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private static void putBuildXMLSourceFile(AntProjectHelper helper, String antPath) {
    Element data = Util.getPrimaryConfigurationData(helper);
    Document doc = data.getOwnerDocument();
    Element viewEl = XMLUtil.findElement(data, "view", FreeformProjectType.NS_GENERAL); // NOI18N
    if (viewEl == null) {
        viewEl = doc.createElementNS(FreeformProjectType.NS_GENERAL, "view"); // NOI18N
        XMLUtil.appendChildElement(data, viewEl, rootElementsOrder);
    }
    Element itemsEl = XMLUtil.findElement(viewEl, "items", FreeformProjectType.NS_GENERAL); // NOI18N
    if (itemsEl == null) {
        itemsEl = doc.createElementNS(FreeformProjectType.NS_GENERAL, "items"); // NOI18N
        XMLUtil.appendChildElement(viewEl, itemsEl, viewElementsOrder);
    }
    Element fileEl = doc.createElementNS(FreeformProjectType.NS_GENERAL, "source-file"); // NOI18N
    Element el = doc.createElementNS(FreeformProjectType.NS_GENERAL, "location"); // NOI18N
    el.appendChild(doc.createTextNode(antPath)); // NOI18N
    fileEl.appendChild(el);
    XMLUtil.appendChildElement(itemsEl, fileEl, viewItemElementsOrder);
    Util.putPrimaryConfigurationData(helper, data);
}
 
Example #2
Source File: SceneSerializer.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private static synchronized void writeToFile(final Document document, final FileObject file) {
    try {
        FileSystem fs = file.getFileSystem();
        fs.runAtomicAction(new FileSystem.AtomicAction() {

            @Override
            public void run() throws IOException {
                final FileLock lock = file.lock();
                try {
                    OutputStream fos = file.getOutputStream(lock);
                    try {
                        XMLUtil.write(document, fos, "UTF-8"); // NOI18N
                    } finally {
                        fos.close();
                    }
                } finally {
                    lock.releaseLock();
                }
            }
        });
    } catch (IOException ex) {
        Exceptions.printStackTrace(ex);
    }
}
 
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: ElementJavadoc.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private StringBuilder getFieldHeader(VariableElement fdoc) {
    StringBuilder sb = new StringBuilder();
    sb.append("<pre>"); //NOI18N
    fdoc.getAnnotationMirrors().forEach((annotationDesc) -> {
        appendAnnotation(sb, annotationDesc, true);
    });
    fdoc.getModifiers().forEach((modifier) -> {
        sb.append(modifier).append(' '); //NOI18N
    });
    appendType(sb, fdoc.asType(), false, false, false);
    sb.append(" <b>").append(fdoc.getSimpleName()).append("</b>"); //NOI18N
    String val = null;
    try {
        val = XMLUtil.toAttributeValue(fdoc.getConstantValue().toString());
    } catch (Exception ex) {}
    if (val != null && val.length() > 0)
        sb.append(" = ").append(val); //NOI18N
    sb.append("</pre>"); //NOI18N
    return sb;
}
 
Example #5
Source File: ParseUtils.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/** Parsing just for detecting the version  SAX parser used
*/
public static String getVersion(InputSource is, org.xml.sax.helpers.DefaultHandler versionHandler, 
        EntityResolver ddResolver) throws IOException, SAXException {
    XMLReader reader = XMLUtil.createXMLReader(false);
    reader.setContentHandler(versionHandler);
    reader.setEntityResolver(ddResolver);
    try {
        reader.parse(is);
    } catch (SAXException ex) {
        String message = ex.getMessage();
        if (message != null && message.startsWith(EXCEPTION_PREFIX)) {
            return message.substring(EXCEPTION_PREFIX.length());
        } else {
            throw new SAXException(NbBundle.getMessage(ParseUtils.class, "MSG_cannotParse"), ex);
        }
    }
    throw new SAXException(NbBundle.getMessage(ParseUtils.class, "MSG_cannotFindRoot"));
}
 
Example #6
Source File: ParseUtils.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/** Parsing just for detecting the version  SAX parser used
 */
public static String getVersion(java.io.InputStream is, org.xml.sax.helpers.DefaultHandler versionHandler,
    EntityResolver ddResolver) throws java.io.IOException, SAXException {

    XMLReader reader = XMLUtil.createXMLReader(false);
    reader.setContentHandler(versionHandler);
    reader.setEntityResolver(ddResolver);
    try {
        reader.parse(new InputSource(is));
    } catch (SAXException ex) {
        is.close();
        String message = ex.getMessage();
        if (message != null && message.startsWith(EXCEPTION_PREFIX)) {
            String versionStr = message.substring(EXCEPTION_PREFIX.length());
            if ("".equals(versionStr) || "null".equals(versionStr)) { // NOI18N
                return null;
            } else {
                return versionStr;
            }
        } else {
            throw new SAXException(NbBundle.getMessage(ParseUtils.class, "MSG_cannotParse"), ex);
        }
    }
    is.close();
    throw new SAXException(NbBundle.getMessage(ParseUtils.class, "MSG_cannotFindRoot"));
}
 
Example #7
Source File: JavaActionsTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testCreateProfileTargetFromScratch() throws Exception {
    Document doc = XMLUtil.createDocument("project", null, null, null);
    Element genTarget = ja.createProfileTargetFromScratch("profile", doc);
    doc.getDocumentElement().appendChild(genTarget);
    String expectedXml =
        "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
        "<project>\n" +
        "    <target name=\"-profile-check\">\n" +
        "        <startprofiler freeform=\"true\"/>\n" +
        "    </target>\n" +
        "    <target depends=\"-profile-check\" if=\"profiler.configured\" name=\"profile\">\n" +
        "        <path id=\"cp\">\n" +
        "            <!---->\n" +
        "        </path>\n" +
        "        <!---->\n" +
        "        <java classname=\"some.main.Class\" fork=\"true\">\n" +
        "            <classpath refid=\"cp\"/>\n" +
        "            <jvmarg line=\"${agent.jvmargs}\"/>\n" +
        "        </java>\n" +
        "    </target>\n" +
        "</project>\n";
    assertEquals(expectedXml, xmlToString(doc.getDocumentElement()));
}
 
Example #8
Source File: ClassPathSupportCallbackImpl.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private Map<String, String> createEarIncludesMap(String webLibraryElementName) {
    Map<String, String> earIncludesMap = new LinkedHashMap<String, String>();
    if (webLibraryElementName != null) {
        Element data = helper.getPrimaryConfigurationData(true);
        final String ns = EarProjectType.PROJECT_CONFIGURATION_NAMESPACE;
        Element webModuleLibs = (Element) data.getElementsByTagNameNS(ns, webLibraryElementName).item(0);
        if(webModuleLibs != null) {
            NodeList ch = webModuleLibs.getChildNodes();
            for (int i = 0; i < ch.getLength(); i++) {
                if (ch.item(i).getNodeType() == Node.ELEMENT_NODE) {
                    Element library = (Element) ch.item(i);
                    Node webFile = library.getElementsByTagNameNS(ns, TAG_FILE).item(0);
                    NodeList pathInEarElements = library.getElementsByTagNameNS(ns, TAG_PATH_IN_EAR);
                    earIncludesMap.put(XMLUtil.findText(webFile), pathInEarElements.getLength() > 0 ?
                        XMLUtil.findText(pathInEarElements.item(0)) : null);
                }
            }
        }
    }
    return earIncludesMap;
}
 
Example #9
Source File: BootCPNodeFactory.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public String getHtmlDisplayName() {
    final Pair<String, JavaPlatform> platHolder = pp.getPlatform();
    if (platHolder == null) {
        return null;
    }
    final JavaPlatform jp = platHolder.second();
    if (jp == null || !jp.isValid()) {
        String displayName = this.getDisplayName();
        try {
            displayName = XMLUtil.toElementContent(displayName);
        } catch (CharConversionException ex) {
            // OK, no annotation in this case
            return null;
        }
        return "<font color=\"#A40000\">" + displayName + "</font>"; //NOI18N
    } else {
        return null;
    }
}
 
Example #10
Source File: SQLEditorSupport.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
protected String messageToolTip() {
    if (isConsole()) {
        DatabaseConnection dc = getDatabaseConnection();
        if (dc != null) {
            try {
                return String.format(
                        "<html>%s<br>%s<br>JDBC-URL: %s</html>",
                        XMLUtil.toAttributeValue(
                        getDataObject().getPrimaryFile().getName()),
                        XMLUtil.toAttributeValue(dc.getDisplayName()),
                        XMLUtil.toAttributeValue(dc.getDatabaseURL()));
            } catch (CharConversionException ex) {
                LOGGER.log(Level.WARNING, "", ex);
        return getDataObject().getPrimaryFile().getName();
            }
    } else {
            return getDataObject().getPrimaryFile().getName();
        }
    } else {
        return super.messageToolTip();
    }
}
 
Example #11
Source File: JavaActions.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * Check to see if a given Ant target uses a given task once (and only once).
 * @param target an Ant <code>&lt;target&gt;</code> element
 * @param taskName the (unqualified) name of an Ant task
 * @return a task element with that name, or null if there is none or more than one
 */
Element targetUsesTaskExactlyOnce(Element target, String taskName) {
    // XXX should maybe also look for any other usage of the task in the same script in case there is none in the mentioned target
    Element foundTask = null;
    for (Element task : XMLUtil.findSubElements(target)) {
        if (task.getLocalName().equals(taskName)) {
            if (foundTask != null) {
                // Duplicate.
                return null;
            } else {
                foundTask = task;
            }
        }
    }
    return foundTask;
}
 
Example #12
Source File: EarProjectGeneratorTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testProjectNameIsSet() throws Exception { // #73930
    File prjDirF = new File(getWorkDir(), "EARProject");
    EarProjectGenerator.createProject(prjDirF, "test-project",
            Profile.JAVA_EE_5, TestUtil.SERVER_URL, "1.5", null);
    // test also build
    final File buildXML = new File(prjDirF, "build.xml");
    String projectName = ProjectManager.mutex().readAccess(new Mutex.ExceptionAction<String>() {
        public String run() throws Exception {
            Document doc = XMLUtil.parse(new InputSource(buildXML.toURI().toString()),
                    false, true, null, null);
            Element project = doc.getDocumentElement();
            return project.getAttribute("name");
        }
    });
    assertEquals("project name is set in the build.xml", "test-project", projectName);
}
 
Example #13
Source File: JavaActions.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * Find output classes given a compilation unit from project.xml.
 */
private String findClassesOutputDir(Element compilationUnitEl) {
    // Look for an appropriate <built-to>.
    for (Element builtTo : XMLUtil.findSubElements(compilationUnitEl)) {
        if (builtTo.getLocalName().equals("built-to")) { // NOI18N
            String rawtext = XMLUtil.findText(builtTo);
            // Check that it is not an archive.
            String evaltext = evaluator.evaluate(rawtext);
            if (evaltext != null) {
                File dest = helper.resolveFile(evaltext);
                URL destU;
                try {
                    destU = Utilities.toURI(dest).toURL();
                } catch (MalformedURLException e) {
                    throw new AssertionError(e);
                }
                if (!FileUtil.isArchiveFile(destU)) {
                    // OK, dir, take it.
                    return rawtext;
                }
            }
        }
    }
    return null;
}
 
Example #14
Source File: JavaActions.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * Write a script with a new or modified document.
 * @param scriptPath e.g. {@link #FILE_SCRIPT_PATH} or {@link #GENERAL_SCRIPT_PATH}
 */
void writeCustomScript(Document doc, String scriptPath) throws IOException {
    FileObject script = helper.getProjectDirectory().getFileObject(scriptPath);
    if (script == null) {
        script = FileUtil.createData(helper.getProjectDirectory(), scriptPath);
    }
    FileLock lock = script.lock();
    try {
        OutputStream os = script.getOutputStream(lock);
        try {
            XMLUtil.write(doc, os, "UTF-8"); // NOI18N
        } finally {
            os.close();
        }
    } finally {
        lock.releaseLock();
    }
}
 
Example #15
Source File: Classpaths.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private List<URL> createExecuteClasspath(List<String> packageRoots, Element compilationUnitEl) {
    for (Element e : XMLUtil.findSubElements(compilationUnitEl)) {
        if (e.getLocalName().equals("classpath") && e.getAttribute("mode").equals("execute")) { // NOI18N
            return createClasspath(e, new RemoveSources(helper, sfbqImpl));
        }
    }
    // None specified; assume it is same as compile classpath plus (cf. #49113) <built-to> dirs/JARs
    // if there are any (else include the source dir(s) as a fallback for the I18N wizard to work).
    Set<URL> urls = new LinkedHashSet<>();
    urls.addAll(createCompileClasspath(compilationUnitEl));
    final Project prj = FileOwnerQuery.getOwner(helper.getProjectDirectory());
    if (prj != null) {
        for (URL src : createSourcePath(packageRoots)) {
            urls.addAll(sfbqImpl.findBinaryRoots(src));
        }
    }
    return new ArrayList<>(urls);
}
 
Example #16
Source File: SourceForBinaryQueryImpl.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * Find a list of URLs of binaries which will be produced from a compilation unit.
 * Result may be empty.
 */
private List<URL> findBinaries(Element compilationUnitEl) {
    List<URL> binaries = new ArrayList<URL>();
    for (Element builtToEl : XMLUtil.findSubElements(compilationUnitEl)) {
        if (!builtToEl.getLocalName().equals("built-to")) { // NOI18N
            continue;
        }
        String text = XMLUtil.findText(builtToEl);
        String textEval = evaluator.evaluate(text);
        if (textEval == null) {
            continue;
        }
        File buildProduct = helper.resolveFile(textEval);
        URL buildProductURL = FileUtil.urlForArchiveOrDir(buildProduct);
        binaries.add(buildProductURL);
    }
    return binaries;
}
 
Example #17
Source File: BreadCrumbsNodeImpl.java    From netbeans with Apache License 2.0 6 votes vote down vote up
static String escape(String s) {
    if (s != null) {
        //unescape unicode sequences first (would be better if Pretty would not print them, but that might be more difficult):
        Matcher matcher = UNICODE_SEQUENCE.matcher(s);
        
        if (matcher.find()) {
            StringBuilder result = new StringBuilder();
            int lastReplaceEnd = 0;
            do {
                result.append(s.substring(lastReplaceEnd, matcher.start()));
                int ch = Integer.parseInt(matcher.group(1), 16);
                result.append((char) ch);
                lastReplaceEnd = matcher.end();
            } while (matcher.find());
            result.append(s.substring(lastReplaceEnd));
            s = result.toString();
        }
        try {
            return XMLUtil.toAttributeValue(s);
        } catch (CharConversionException ex) {
        }
    }
    return null;
}
 
Example #18
Source File: ViewTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@RandomlyFails // NB-Core-Build #1012
public void testViewItemChanges() throws Exception {
    FileObject top = FileUtil.toFileObject(copyFolder(FileUtil.toFile(egdirFO.getFileObject("extsrcroot"))));
    FreeformProject extsrcroot_ = (FreeformProject) ProjectManager.getDefault().findProject(top.getFileObject("proj"));
    Node root = extsrcroot_.getLookup().lookup(LogicalViewProvider.class).createLogicalView();
    Children ch = root.getChildren();
    Node[] kids = ch.getNodes(true);
    assertEquals("two child nodes", 2, kids.length);
    assertEquals("correct code name #1", "../src", kids[0].getName());
    assertEquals("correct code name #2", "nbproject/project.xml", kids[1].getName());
    TestNL l = new TestNL();
    root.addNodeListener(l);
    Element data = extsrcroot_.getPrimaryConfigurationData();
    Element view = XMLUtil.findElement(data, "view", FreeformProjectType.NS_GENERAL);
    assertNotNull("have <view>", view);
    Element items = XMLUtil.findElement(view, "items", FreeformProjectType.NS_GENERAL);
    assertNotNull("have <items>", items);
    Element sourceFolder = XMLUtil.findElement(items, "source-folder", FreeformProjectType.NS_GENERAL);
    assertNotNull("have <source-folder>", sourceFolder);
    Element location = XMLUtil.findElement(sourceFolder, "location", FreeformProjectType.NS_GENERAL);
    assertNotNull("have <location>", location);
    NodeList nl = location.getChildNodes();
    assertEquals("one child", 1, nl.getLength());
    location.removeChild(nl.item(0));
    location.appendChild(location.getOwnerDocument().createTextNode("../src2"));
    Element sourceFile =  XMLUtil.findElement(items, "source-file", FreeformProjectType.NS_GENERAL);
    assertNotNull("have <source-file>", sourceFile);
    items.removeChild(sourceFile);
    extsrcroot_.putPrimaryConfigurationData(data);
    // children keys are updated asynchronously. give them a time
    Thread.sleep(500);
    assertFalse("got some changes in children", l.probeChanges().isEmpty());
    kids = ch.getNodes(true);
    assertEquals("one child node", 1, kids.length);
    assertEquals("correct code name #1", "../src2", kids[0].getName());
    assertEquals("correct display name #1", "External Sources", kids[0].getDisplayName());
    assertEquals("correct cookie #1",
            DataObject.find(top.getFileObject("src2")),
            kids[0].getLookup().lookup(DataObject.class));
}
 
Example #19
Source File: ProjectInfoImpl.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Get the text from the named element of the primary configuration node.
 *
 * @param elementName name of the element that contains the property value
 * @return the property value, or '???' if not found
 */
protected String getElementTextFromConfiguration(final String elementName) {
    return ProjectManager.mutex().readAccess(new Mutex.Action<String>() {
        @Override
        public String run() {
            Element data = getPrimaryConfigurationData();
            Element element = XMLUtil.findElement(data, elementName, null);
            String name = element == null ? null : XMLUtil.findText(element);
            if (name == null) {
                name = UNKNOWN;
            }
            return name;
        }
    });
}
 
Example #20
Source File: PersistenceManager.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/** Returns a XML parser. The same parser can be returned assuming that config files
 * are parser sequentially.
 *
 * @return XML parser with set content handler, errror handler
 * and entity resolver.
 */
public XMLReader getXMLParser (DefaultHandler h) throws SAXException {
    if (parser == null) {
        // get non validating, not namespace aware parser
        parser = XMLUtil.createXMLReader();
        parser.setEntityResolver(new EntityResolver () {
            /** Implementation of entity resolver. Points to the local DTD
             * for our public ID */
            public InputSource resolveEntity (String publicId, String systemId)
            throws SAXException {
                if (ModeParser.INSTANCE_DTD_ID_1_0.equals(publicId)
                || ModeParser.INSTANCE_DTD_ID_1_1.equals(publicId)
                || ModeParser.INSTANCE_DTD_ID_1_2.equals(publicId)
                || ModeParser.INSTANCE_DTD_ID_2_0.equals(publicId)
                || ModeParser.INSTANCE_DTD_ID_2_1.equals(publicId)
                || ModeParser.INSTANCE_DTD_ID_2_2.equals(publicId)
                || ModeParser.INSTANCE_DTD_ID_2_3.equals(publicId)
                || GroupParser.INSTANCE_DTD_ID_2_0.equals(publicId)
                || TCGroupParser.INSTANCE_DTD_ID_2_0.equals(publicId)
                || TCRefParser.INSTANCE_DTD_ID_1_0.equals(publicId)
                || TCRefParser.INSTANCE_DTD_ID_2_0.equals(publicId)
                || TCRefParser.INSTANCE_DTD_ID_2_1.equals(publicId)
                || TCRefParser.INSTANCE_DTD_ID_2_2.equals(publicId)
                || WindowManagerParser.INSTANCE_DTD_ID_1_0.equals(publicId)
                || WindowManagerParser.INSTANCE_DTD_ID_1_1.equals(publicId)
                || WindowManagerParser.INSTANCE_DTD_ID_2_0.equals(publicId)
                || WindowManagerParser.INSTANCE_DTD_ID_2_1.equals(publicId)) {
                    InputStream is = new ByteArrayInputStream(new byte[0]);
                    return new InputSource(is);
                }
                return null; // i.e. follow advice of systemID
            }
        });
    }
    parser.setContentHandler(h);
    parser.setErrorHandler(h);
    return parser;
}
 
Example #21
Source File: ProjectXMLManager.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/** Utility method for finding friend. */
public static String[] findFriends(final Element confData) {
    Element friendsEl = findFriendsElement(confData);
    if (friendsEl != null) {
        Set<String> friends = new TreeSet<String>();
        for (Element friendEl : XMLUtil.findSubElements(friendsEl)) {
            if (FRIEND.equals(friendEl.getTagName())) {
                friends.add(XMLUtil.findText(friendEl));
            }
        }
        return friends.toArray(new String[friends.size()]);
    }
    return null;
}
 
Example #22
Source File: XMLMIMEComponent.java    From netbeans with Apache License 2.0 5 votes vote down vote up
protected XMLReader createXMLReader() {
    XMLReader parser = null;
    
    try {
        parser = XMLUtil.createXMLReader(false, true);           
        try {
            parser.setProperty("http://xml.org/sax/properties/lexical-handler", this);  //NOI18N
        } catch (SAXException sex) {
            Logger.getLogger(XMLMIMEComponent.class.getName()).fine(NbBundle.getMessage(XMLMIMEComponent.class, "W-003"));  //NOI18N
        }
    } catch (SAXException ex) {
        Logger.getLogger(XMLMIMEComponent.class.getName()).log(Level.WARNING, null, ex);
    }
    return parser;
}
 
Example #23
Source File: JavaActions.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Try to find the compilation unit containing a source root.
 * @param sources a source root in the project (as a virtual Ant name)
 * @return the compilation unit owning it, or null if not found
 */
private Element findCompilationUnit(String sources) {
    for (Element compilationUnitEl : compilationUnits()) {
        for (Element packageRoot : XMLUtil.findSubElements(compilationUnitEl)) {
            if (packageRoot.getLocalName().equals("package-root")) { // NOI18N
                if (XMLUtil.findText(packageRoot).equals(sources)) {
                    return compilationUnitEl;
                }
            }
        }
    }
    return null;
}
 
Example #24
Source File: JavaActions.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private List<Element> compilationUnits() {
    Element java = aux.getConfigurationFragment(JavaProjectNature.EL_JAVA, JavaProjectNature.NS_JAVA_LASTEST, true);
    if (java == null) {
        return Collections.emptyList();
    }
    return XMLUtil.findSubElements(java);
}
 
Example #25
Source File: Interpreter.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private void parse(){
    try{
        Parser p = new XMLReaderAdapter(XMLUtil.createXMLReader());
        p.setDocumentHandler(this);
        String externalForm = url.toExternalForm();
        InputSource is = new InputSource(externalForm);
        try {
            p.parse(is);
        } catch (NullPointerException npe) {
            npe.printStackTrace();
            if (npe.getCause() != null) {
                npe.getCause().printStackTrace();
            }
        }
    }
    catch(java.io.IOException ie){
        ie.printStackTrace();
    }
    catch(org.xml.sax.SAXException se){
        se.printStackTrace();
    }
}
 
Example #26
Source File: TAXUtil.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Try to set new value to the text. Method <code>XMLUtil.toElementContent</code> is used
 * to convert value to correct element content.
 *
 * @see org.openide.xml.XMLUtil#toElementContent
 */
public static void setTextData (TreeText text, String value) throws TreeException {
    try {
        text.setData (XMLUtil.toElementContent (value));
    } catch (CharConversionException exc) {
        throw new TreeException (exc);
    }
}
 
Example #27
Source File: ReferenceHelper.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static boolean removeRawReferenceElement(String foreignProjectName, String id, Element references, boolean escaped) throws IllegalArgumentException {
    // As with addRawReference, do a linear search through.
    for (Element testRefEl : XMLUtil.findSubElements(references)) {
        RawReference testRef = RawReference.create(testRefEl);
        String refID = testRef.getID();
        String refName = testRef.getForeignProjectName();
        if (escaped) {
            refID = getUsableReferenceID(testRef.getID());
            refName = getUsableReferenceID(testRef.getForeignProjectName());
        }
        if (refName.compareTo(foreignProjectName) > 0) {
            // searched past it
            return false;
        }
        if (refName.equals(foreignProjectName)) {
            if (refID.compareTo(id) > 0) {
                // again, searched past it
                return false;
            }
            if (refID.equals(id)) {
                // Key match, remove it.
                references.removeChild(testRefEl);
                return true;
            }
        }
    }
    // Searched through to the end and did not find it.
    return false;
}
 
Example #28
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 #29
Source File: DiffTreeTable.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public Component getTableCellRendererComponent (JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
    Component comp = delegate.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
    if (comp instanceof JComponent) {
        JComponent c = (JComponent) comp;
        if (value == null) {
            c.setToolTipText(null);
        } else {
            String val = value.toString();
            String tooltip = tooltips.get(val);
            if (tooltip == null) {
                tooltip = val.replace("\r\n", "\n").replace("\r", "\n"); //NOI18N
                try {
                    tooltip = XMLUtil.toElementContent(tooltip);
                } catch (CharConversionException e1) {
                    Logger.getLogger(DiffTreeTable.class.getName()).log(Level.INFO, "Can not HTML escape: ", tooltip);  //NOI18N
                }
                if (tooltip.contains("\n")) {
                    tooltip = "<html><body><p>" + tooltip.replace("\n", "<br>") + "</p></body></html>"; //NOI18N
                    c.setToolTipText(tooltip);
                }
                tooltips.put(val, tooltip);
            }
            c.setToolTipText(tooltip);
        }
    }
    return comp;
}
 
Example #30
Source File: AntBasedProjectFactorySingleton.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public @Override Result isProject2(FileObject projectDirectory) {
    if (FileUtil.toFile(projectDirectory) == null) {
        return null;
    }
    FileObject projectFile = projectDirectory.getFileObject(PROJECT_XML_PATH);
    //#54488: Added check for virtual
    if (projectFile == null || !projectFile.isData() || projectFile.isVirtual()) {
        return null;
    }
    File projectDiskFile = FileUtil.toFile(projectFile);
    //#63834: if projectFile exists and projectDiskFile does not, do nothing:
    if (projectDiskFile == null) {
        return null;
    }
    try {
        Document projectXml = loadProjectXml(projectDiskFile);
        if (projectXml != null) {
            Element typeEl = XMLUtil.findElement(projectXml.getDocumentElement(), "type", PROJECT_NS); // NOI18N
            if (typeEl != null) {
                String type = XMLUtil.findText(typeEl);
                if (type != null) {
                    AntBasedProjectType provider = findAntBasedProjectType(type);
                    if (provider != null) {
                        if (provider instanceof AntBasedGenericType) {
                            return new ProjectManager.Result(((AntBasedGenericType)provider).getIcon());
                        } else {
                            //put special icon?
                            return new ProjectManager.Result(null);
                        }
                    }
                }
            }
        }
    } catch (IOException ex) {
        LOG.log(Level.FINE, "Failed to load the project.xml file.", ex);
    }
    // better have false positives than false negatives (according to the ProjectManager.isProject/isProject2 javadoc.
    return new ProjectManager.Result(null);
}