下面列出了org.xml.sax.helpers.XMLReaderAdapter#org.openide.xml.XMLUtil 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/** 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"));
}
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;
}
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);
}
}
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);
}
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;
}
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);
}
/**
* 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;
}
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;
}
/**
* 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();
}
}
/**
* 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;
}
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);
}
/**
* Check to see if a given Ant target uses a given task once (and only once).
* @param target an Ant <code><target></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;
}
@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();
}
}
@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;
}
}
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()));
}
/** 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"));
}
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;
}
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();
}
}
/**
* 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);
}
}
private static Element getOrCreateRootElement(AuxiliaryConfiguration conf, boolean shared) {
Element el = conf.getConfigurationFragment(ROOT, NAMESPACE, shared);
if (el == null) {
el = XMLUtil.createDocument(ROOT, NAMESPACE, null, null).getDocumentElement();
}
return el;
}
private static String escape(String s) {
if (s != null) {
try {
return XMLUtil.toAttributeValue(s);
} catch (Exception ex) {}
}
return s;
}
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;
}
}
}
try (OutputStream out = fo.getOutputStream()) {
XMLUtil.write(doc, out, "UTF-8");
}
} catch (Exception ex) {
Exceptions.printStackTrace(ex);
writeFile(str, fo);
}
}
private String escapeAttrValue(String attrValue) {
try {
return XMLUtil.toAttributeValue(attrValue);
} catch (CharConversionException e) {
return null;
}
}
public void testForFolderLocal() throws Exception {
TestFileUtils.writeFile(new File(getWorkDir(), ".git/config"),
"[core]\n"
+ "\trepositoryformatversion = 0\n");
assertEquals(null, HudsonGitSCM.getRemoteOrigin(Utilities.toURI(getWorkDir()), null));
HudsonSCM.Configuration cfg = new HudsonGitSCM().forFolder(getWorkDir());
assertNotNull(cfg);
Document doc = XMLUtil.createDocument("whatever", null, null, null);
cfg.configure(doc);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
XMLUtil.write(doc, baos, "UTF-8");
String text = baos.toString("UTF-8");
assertTrue(text, text.contains(getWorkDirPath()));
}
@CheckForNull
public static String escape(@NonNull final String s) {
if (s != null) {
try {
return XMLUtil.toAttributeValue(s);
} catch (CharConversionException ex) {
}
}
return null;
}
private Document createNewSharedDocument() throws DOMException {
String element = "project-shared-configuration";
Document doc = XMLUtil.createDocument(element, null, null, null);
doc.getDocumentElement().appendChild(doc.createComment(
"\nThis file contains additional configuration written by modules in the NetBeans IDE.\n" +
"The configuration is intended to be shared among all the users of project and\n" +
"therefore it is assumed to be part of version control checkout.\n" +
"Without this configuration present, some functionality in the IDE may be limited or fail altogether.\n"));
return doc;
}
/**
* Create XML contents of the shortcut to be generated, based on current data.
*/
private String generateContents() {
try {
Document doc = XMLUtil.createDocument("project", null, null, null); // NOI18N
Element pel = doc.getDocumentElement();
String displayName = (String)getProperty(PROP_DISPLAY_NAME);
if (displayName != null && displayName.length() > 0) {
pel.setAttribute("name", displayName); // NOI18N
}
pel.setAttribute("default", "run"); // NOI18N
Element tel = doc.createElement("target"); // NOI18N
tel.setAttribute("name", "run"); // NOI18N
Element ael = doc.createElement("ant"); // NOI18N
ael.setAttribute("antfile", project.getFile().getAbsolutePath()); // NOI18N
// #34802: let the child project decide on the basedir:
ael.setAttribute("inheritall", "false"); // NOI18N
ael.setAttribute("target", target.getAttribute("name")); // NOI18N
tel.appendChild(ael);
pel.appendChild(tel);
ByteArrayOutputStream baos = new ByteArrayOutputStream(1000);
XMLUtil.write(doc, baos, "UTF-8"); // NOI18N
return baos.toString("UTF-8"); // NOI18N
} catch (IOException e) {
AntModule.err.notify(e);
return ""; // NOI18N
}
}
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;
}
}
/**
* The recognizer entry method taking an InputSource.
* @param input InputSource to be parsed.
* @throws IOException on I/O error.
* @throws SAXException propagated exception thrown by a DocumentHandler.
*/
public void parse(final InputSource input) throws SAXException, IOException {
XMLReader parser = XMLUtil.createXMLReader(false, false); // fastest mode
parser.setContentHandler(this);
parser.setErrorHandler(this);
parser.setEntityResolver(this);
parser.parse(input);
}
/**
* Remove a piece of the configuration subtree by name.
* @param elementName the simple XML element name expected
* @param namespace the XML namespace expected
* @param shared to use project.xml vs. private.xml
* @return true if anything was actually removed
*/
boolean removeConfigurationFragment(final String elementName, final String namespace, final boolean shared) {
return ProjectManager.mutex().writeAccess(new Mutex.Action<Boolean>() {
public Boolean run() {
synchronized (modifiedMetadataPaths) {
Element root = null;
Element data = null;
try {
root = getConfigurationDataRoot(shared);
data = XMLUtil.findElement(root, elementName, namespace);
} catch (IllegalArgumentException iae) {
//thrown from XmlUtil.findElement when more than 1 equal elements are present.
LOG.log(Level.INFO, iae.getMessage(), iae);
}
if(shared) {
findDuplicateElements(projectXml.getDocumentElement(), dir.getFileObject(PROJECT_XML_PATH), shared);
} else {
findDuplicateElements(privateXml.getDocumentElement(), dir.getFileObject(PRIVATE_XML_PATH), shared);
}
if (data != null) {
root.removeChild(data);
modifying(shared ? PROJECT_XML_PATH : PRIVATE_XML_PATH);
return true;
} else {
return false;
}
}
}
});
}