/** * This method returns a list of CMDocumentReferences associated with a particular node or subtree */ public List getCMDocumentReferences(Node node, boolean deep) { List result = new ArrayList(); Document document = (node.getNodeType() == Node.DOCUMENT_NODE) ? (Document) node : node.getOwnerDocument(); DocumentType doctype = document.getDoctype(); // defect 206833 ... here we test for DTDs that are declared inline // since we currently have no way of making use of inline DTDs we ingore them // so that the implict DTD (if any) can be used if (doctype != null && (doctype.getPublicId() != null || doctype.getSystemId() != null)) { String uri = resolveGrammarURI(document, doctype.getPublicId(), doctype.getSystemId()); result.add(new CMDocumentReferenceImpl(doctype.getPublicId(), uri)); } else if (getImplictDoctype(document) != null) { String[] implicitDoctype = getImplictDoctype(document); String uri = resolveGrammarURI(document, implicitDoctype[0], implicitDoctype[1]); result.add(new CMDocumentReferenceImpl(implicitDoctype[0], uri)); } else { NamespaceTable namespaceTable = new NamespaceTable(document); if (node.getNodeType() == Node.ELEMENT_NODE) { namespaceTable.addElement((Element) node); } if (deep) { addChildElementsToNamespaceTable(node, namespaceTable); } List list = namespaceTable.getNamespaceInfoList(); for (Iterator i = list.iterator(); i.hasNext(); ) { NamespaceInfo info = (NamespaceInfo) i.next(); String uri = resolveGrammarURI(document, info.uri, info.locationHint); result.add(new CMDocumentReferenceImpl(info.uri, uri)); } } return result; }
public static String getNodeReference( Node node, boolean cacheIfPossible, boolean errIfNull, ClientDocumentStfulDelegateImpl clientDoc) { // El código devuelto debe ser enviado al cliente y ejecutado pues puede llevar información de // cacheado y haber sido cacheado ahora en el servidor if (node == null) if (errIfNull) throw new ItsNatException("No specified node"); else return "null"; ItsNatStfulDocumentImpl itsNatDoc = clientDoc.getItsNatStfulDocument(); Document doc = itsNatDoc.getDocument(); if (node == ((DocumentView) doc).getDefaultView()) return "itsNatDoc.win"; else if (node == doc) return "itsNatDoc.doc"; else if (node == doc.getDoctype()) return "itsNatDoc.doc.doctype"; else if (node == doc.getDocumentElement()) return "itsNatDoc.doc.documentElement"; // Es una tentación considerar también el caso document.body pero creo recordar // que en Safari y XHTML el API DOM no es el HTML DOM sino DOM Core a secas. // node no puede ser nulo, ya está comprobado antes NodeLocationImpl nodeLoc = clientDoc.getNodeLocation(node, cacheIfPossible); return getNodeReference( nodeLoc, errIfNull); // errIfNull puede ser false si se quiere, es redundante pues ya se chequeó // antes }
/** * Runs the test case. * * @throws Throwable Any uncaught exception causes test to fail */ public void runTest() throws Throwable { Document doc; NamedNodeMap notations; DocumentType docType; Node retval; Element elem; doc = (Document) load("hc_staff", true); docType = doc.getDoctype(); if (!(("text/html".equals(getContentType())))) { assertNotNull("docTypeNotNull", docType); notations = docType.getNotations(); assertNotNull("notationsNotNull", notations); elem = doc.createElementNS("http://www.w3.org/1999/xhtml", "br"); try { retval = notations.setNamedItemNS(elem); fail("throw_HIER_OR_NO_MOD_ERR"); } catch (DOMException ex) { switch (ex.code) { case 3: break; case 7: break; default: throw ex; } } } }
private void modifyDomainConfig(AppServerParameters params) throws Exception { File domainXML = getInstanceFile("config/domain.xml"); System.err.println("Modifying domain configuration at " + domainXML.getAbsolutePath()); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); // disable the resolve of the external DTD -- The monkey failed once since it timed out talking // to sun's web site factory.setAttribute( "http://apache.org/xml/features/nonvalidating/load-external-dtd", Boolean.FALSE); DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.parse(domainXML); NodeList list = document.getElementsByTagName("java-config"); if (list.getLength() != 1) { throw new RuntimeException("wrong number of elements " + list.getLength()); } Node javaConfig = list.item(0); // if you want debugging of the spawned glassfish, play with this if (false) { NamedNodeMap attrs = javaConfig.getAttributes(); attrs.getNamedItem("debug-enabled").setNodeValue("true"); attrs .getNamedItem("debug-options") .setNodeValue("-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000"); } appendDSOParams(document, javaConfig, params); TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); if (document.getDoctype() != null) { transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, document.getDoctype().getPublicId()); transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, document.getDoctype().getSystemId()); } StringWriter sw = new StringWriter(); transformer.transform(new DOMSource(document), new StreamResult(sw)); FileUtils.writeStringToFile(domainXML, sw.toString(), "UTF-8"); }
/** * Tries to read from the given filename the outbound message * * @param file The file to read from * @return Outbound message read form the file * @throws IllegalArgumentExcpetion Is thrown if there's something wrong with the content of the * file * @throws IOExcpetion Is throws if there's an I/O problem while reading the file */ private OutboundMessage readDocument(File file) throws IllegalArgumentException { Document xmldoc = null; try { /* Check for valid XML file */ DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance(); dbfac.setValidating(true); DocumentBuilder db = dbfac.newDocumentBuilder(); db.setErrorHandler( new ErrorHandler() { /* * (non-Javadoc) * * @see org.xml.sax.ErrorHandler#error(org.xml.sax.SAXParseException) */ public void error(SAXParseException arg0) { throw new IllegalArgumentException(arg0); } /* * (non-Javadoc) * * @see org.xml.sax.ErrorHandler#fatalError(org.xml.sax.SAXParseException) */ public void fatalError(SAXParseException arg0) { throw new IllegalArgumentException(arg0); } /* * (non-Javadoc) * * @see org.xml.sax.ErrorHandler#warning(org.xml.sax.SAXParseException) */ public void warning(SAXParseException arg0) { throw new IllegalArgumentException(arg0); } }); xmldoc = db.parse(file); DocumentType outDoctype = xmldoc.getDoctype(); if (!"message".equals(outDoctype.getName())) { throw new IllegalArgumentException("Wrong DOCTYPE - Have to be message!"); } if (!"smssvr_out.dtd".equals(outDoctype.getSystemId())) { throw new IllegalArgumentException( "Wrong SystemId in DOCTYPE - Have to be smssvr_out.dtd!"); } } catch (Exception e) { throw new IllegalArgumentException(e); } /* Search "message" root element */ NodeList rnl = xmldoc.getElementsByTagName("message"); if (rnl == null || rnl.getLength() != 1) { throw new IllegalArgumentException("Wrong root element or root element count!"); } /* Process all child elements aka "message" */ return readNode(rnl.item(0)); }
/** * Runs the test case. * * @throws Throwable Any uncaught exception causes test to fail */ public void runTest() throws Throwable { Document doc; DocumentType docType; NamedNodeMap entitiesMap; Entity entity; String encodingName; doc = (Document) load("external_barfoo", false); docType = doc.getDoctype(); entitiesMap = docType.getEntities(); entity = (Entity) entitiesMap.getNamedItem("ent5"); encodingName = entity.getXmlEncoding(); assertNull("entitygetxmlencoding02", encodingName); }
private static void printDoctype(Document doc, PrintStream pstrm) { if (doc.getDoctype() != null) { pstrm.println("<!DOCTYPE " + doc.getDoctype().getName()); String pubid = doc.getDoctype().getPublicId(); if (pubid != null) { pstrm.print("\tPUBLIC \"" + pubid + "\""); } String sysid = doc.getDoctype().getSystemId(); if (sysid != null) { if (pubid != null) { pstrm.println(""); } pstrm.print("\tSYSTEM \"" + sysid + "\""); } pstrm.print(">"); } }
/** * Convenience class to create a compiled stylesheet. * * @param node DOM source for the stylesheet. * @return a compiled stylesheet */ public javax.xml.transform.Templates newTemplates(Node node) throws TransformerConfigurationException { Document doc = node.getOwnerDocument(); if (node instanceof Document) doc = (Document) node; DocumentType dtd = doc.getDoctype(); if (dtd != null && dtd.getSystemId() != null) return generate(node, getSearchPath().lookup(dtd.getSystemId())); else if (doc instanceof CauchoDocument) { String systemId = ((CauchoDocument) doc).getFilename(); return generate(node, getSearchPath().lookup(systemId)); } else return generate(node, null); }
public static String[] getDoctypeInfo(Document document) { String[] result = null; DocumentType doctype = document.getDoctype(); // defect 206833 ... here we test for DTDs that are declared inline // since we currently have no way of making use of inline DTDs we ignore them // so that the implict DTD (if any) can be used if (doctype != null && (doctype.getPublicId() != null || doctype.getSystemId() != null)) { result = new String[2]; result[0] = doctype.getPublicId(); result[1] = doctype.getSystemId(); } else if (getImplictDoctype(document) != null) { result = getImplictDoctype(document); } return result; }
private boolean validSMSDtdDocType(Document doc) { boolean valid = false; DocumentType docType = doc.getDoctype(); if (docType != null) { String dtdPath = docType.getSystemId(); if (dtdPath != null) { int idx = dtdPath.lastIndexOf('/'); if (idx != -1) { dtdPath = dtdPath.substring(idx + 1); } valid = dtdPath.equals("sms.dtd"); } } return valid; }
private Document loadAsDom(FileObject inFile) throws Exception { InputStream is = null; try { is = inFile.getContent().getInputStream(); DocumentBuilderFactory parserFactory = DocumentBuilderFactory.newInstance(); parserFactory.setValidating(false); parserFactory.setNamespaceAware(false); // this is the only diference from readContentAsDom parserFactory.setIgnoringElementContentWhitespace(false); parserFactory.setIgnoringComments(false); DocumentBuilder builder = parserFactory.newDocumentBuilder(); boolean dtdNotFound = false; Document doc = null; try { doc = builder.parse(is); } catch (FileNotFoundException e) { dtdNotFound = true; } // if dtd doesn't exist parse the document again without trying to load dtd if (dtdNotFound) { is = inFile.getContent().getInputStream(); // disable dtd loading parserFactory.setFeature( "http://apache.org/xml/features/nonvalidating/load-external-dtd", false); builder = parserFactory.newDocumentBuilder(); doc = builder.parse(is); } DocumentType docType = doc.getDoctype(); return doc; } finally { if (is != null) try { is.close(); } catch (IOException e) { /**/ } } }
@Override public void receive(String title, String type, Document doc) { outputDir.mkdir(); File outputFile = new File(outputDir, title + "." + type); DocumentType doctype = doc.getDoctype(); try { Source source = new DOMSource(doc); Result result = new StreamResult(outputFile); Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.METHOD, "xml"); transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, doctype.getPublicId()); transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, doctype.getSystemId()); transformer.transform(source, result); } catch (TransformerException e) { throw new PrintingException("Failed during transform", e); } }
/** * Runs the test case. * * @throws Throwable Any uncaught exception causes test to fail */ public void runTest() throws Throwable { Document doc; DocumentType docType; Entity entity; NamedNodeMap entitymap; String textContent; doc = (Document) load("hc_staff", true); docType = doc.getDoctype(); entitymap = docType.getEntities(); entity = (Entity) entitymap.getNamedItem("delta"); { boolean success = false; try { entity.setTextContent("NA"); } catch (DOMException ex) { success = (ex.code == DOMException.NO_MODIFICATION_ALLOWED_ERR); } assertTrue("nodesettextcontent13", success); } }
/** * Runs the test case. * * @throws Throwable Any uncaught exception causes test to fail */ public void runTest() throws Throwable { Document doc; DocumentType docType; NamedNodeMap entities; NamedNodeMap notations; Entity entity; Notation notation; Node newNode; String nullNS = null; doc = (Document) load("staffNS", true); docType = doc.getDoctype(); entities = docType.getEntities(); assertNotNull("entitiesNotNull", entities); notations = docType.getNotations(); assertNotNull("notationsNotNull", notations); entity = (Entity) entities.getNamedItem("ent1"); notation = (Notation) notations.getNamedItem("notation1"); { boolean success = false; try { newNode = entities.setNamedItemNS(entity); } catch (DOMException ex) { success = (ex.code == DOMException.NO_MODIFICATION_ALLOWED_ERR); } assertTrue("throw_NO_MODIFICATION_ALLOWED_ERR_entities", success); } { boolean success = false; try { newNode = notations.setNamedItemNS(notation); } catch (DOMException ex) { success = (ex.code == DOMException.NO_MODIFICATION_ALLOWED_ERR); } assertTrue("throw_NO_MODIFICATION_ALLOWED_ERR_notations", success); } }
public static String getDTDVersion(Document document) { String dtdVersion = null; DocumentType docType = document.getDoctype(); if (docType != null) { String publicId = docType.getPublicId(); String systemId = docType.getSystemId(); if (publicId != null && systemId != null) { if (publicId.contains("6.0.0") || systemId.contains("6.0.0")) // $NON-NLS-1$ //$NON-NLS-2$ { dtdVersion = "6.0.0"; // $NON-NLS-1$ } else if (publicId.contains("6.1.0") || systemId.contains("6.1.0")) // $NON-NLS-1$ //$NON-NLS-2$ { dtdVersion = "6.1.0"; // $NON-NLS-1$ } } } return dtdVersion; }
@Override public DocumentNode convert(Document document) { DocumentTypeNode documentTypeNode = convert(document.getDoctype()); ElementNode rootElementNode = convert(document.getDocumentElement()); DocumentBuilder documentBuilder = NodeBuilderFactory.newDocumentBuilder(); DocumentNode documentNode = null; documentNode = documentBuilder // documentNode define .nodeName(document.getNodeName()) // node name .version(document.getXmlEncoding()) // Version .encoding(document.getXmlEncoding()) // encoding .standalone(document.getXmlStandalone()) // standalone .documentTypeNode(documentTypeNode) // DOCTYPE .rootElementNode(rootElementNode) // rootElementNode .build(); // return result return documentNode; }
@Override public DocumentType getDoctype() { return doc.getDoctype(); }
/** * Generates a compiled stylesheet from a parsed XSL document. * * @param xsl the parsed xsl document. * @param path the path to the document. */ Templates generate(Node xsl, Path path) throws TransformerConfigurationException { log.fine("Generating XSL from " + path); // The code generation needs a static lock because the // application might have a separate factory object // for each thread. The static lock protects the code generation // from overwriting its own code. synchronized (AbstractStylesheetFactory.class) { Generator gen = null; try { if (path == null && xsl != null) { Document doc = xsl.getOwnerDocument(); if (doc == null && xsl instanceof Document) doc = (Document) xsl; DocumentType dtd = doc.getDoctype(); String systemId = null; if (dtd != null) systemId = dtd.getSystemId(); if (systemId != null) path = getStylePath().lookup(systemId); } if (path == null && xsl instanceof CauchoNode) { String filename = ((CauchoNode) xsl).getFilename(); if (filename != null) path = getStylePath().lookup(filename); } if (path == null) path = getStylePath().lookup("anonymous.xsl"); Path stylePath = path.getParent(); Expr expr = XPath.parseExpr("//xtp:directive.page/@language"); String language = expr.evalString(xsl); String userName = path.getUserPath(); String mangledName = getMangledName(userName); String encoding = XPath.evalString("//xsl:output/@encoding", xsl); if (encoding != null && encoding.equals("")) encoding = null; if (language == null || language.equals("") || language.equals("java")) { language = "java"; gen = new JavaGenerator(this, mangledName, encoding); } else throw new XslParseException(L.l("unsupported language `{0}'", language)); gen.setPath(path); Iterator iter = XPath.select("//xtp:directive.page/@*", xsl); while (iter.hasNext()) { Attr attr = (Attr) iter.next(); String name = attr.getNodeName(); String value = attr.getNodeValue(); if (name.equals("errorPage")) gen.setErrorPage(value); else if (name.equals("import")) gen.addImport(value); else if (name.equals("contentType")) gen.setContentType(value); else if (name.equals("language")) { if (!language.equalsIgnoreCase(value)) throw new XslParseException(L.l("mismatched language `{0}'", value)); } else if (name.equals("xml:space")) { } else throw new XslParseException(L.l("unknown directive `{0}'", name)); } StylesheetImpl stylesheet = gen.generate(xsl); gen = null; stylesheet.init(path); // XXX: why was this here? stylesheet.init(getStylePath()); stylesheet.setURIResolver(_uriResolver); return stylesheet; } catch (TransformerConfigurationException e) { throw e; } catch (Exception e) { throw new XslParseException(e); } finally { try { if (gen != null) gen.close(); } catch (IOException e) { } } } }
public static String getMergedSource(GeneratedXmlFile generatedXmlFile, File existingFile) throws ShellException { try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setExpandEntityReferences(false); DocumentBuilder builder = factory.newDocumentBuilder(); builder.setEntityResolver(new NullEntityResolver()); Document existingDocument = builder.parse(existingFile); StringReader sr = new StringReader(generatedXmlFile.getFormattedContent()); Document newDocument = builder.parse(new InputSource(sr)); DocumentType newDocType = newDocument.getDoctype(); DocumentType existingDocType = existingDocument.getDoctype(); if (!newDocType.getName().equals(existingDocType.getName())) { throw new ShellException( Messages.getString( "Warning.12", //$NON-NLS-1$ existingFile.getName())); } Element existingRootElement = existingDocument.getDocumentElement(); Element newRootElement = newDocument.getDocumentElement(); // reconcile the root element attributes - // take all attributes from the new element and add to the existing element // remove all attributes from the existing root element NamedNodeMap attributes = existingRootElement.getAttributes(); int attributeCount = attributes.getLength(); for (int i = attributeCount - 1; i >= 0; i--) { Node node = attributes.item(i); existingRootElement.removeAttribute(node.getNodeName()); } // add attributes from the new root node to the old root node attributes = newRootElement.getAttributes(); attributeCount = attributes.getLength(); for (int i = 0; i < attributeCount; i++) { Node node = attributes.item(i); existingRootElement.setAttribute(node.getNodeName(), node.getNodeValue()); } // remove the old ibator generated elements and any // white space before the old ibator nodes List<Node> nodesToDelete = new ArrayList<Node>(); NodeList children = existingRootElement.getChildNodes(); int length = children.getLength(); for (int i = 0; i < length; i++) { Node node = children.item(i); if (isAnIbatorNode(node)) { nodesToDelete.add(node); } else if (isWhiteSpace(node) && isAnIbatorNode(children.item(i + 1))) { nodesToDelete.add(node); } } for (Node node : nodesToDelete) { existingRootElement.removeChild(node); } // add the new ibator generated elements children = newRootElement.getChildNodes(); length = children.getLength(); Node firstChild = existingRootElement.getFirstChild(); for (int i = 0; i < length; i++) { Node node = children.item(i); // don't add the last node if it is only white space if (i == length - 1) { if (isWhiteSpace(node)) { break; } } Node newNode = existingDocument.importNode(node, true); if (firstChild == null) { existingRootElement.appendChild(newNode); } else { existingRootElement.insertBefore(newNode, firstChild); } } // pretty print the result return prettyPrint(existingDocument); } catch (Exception e) { throw new ShellException( Messages.getString( "Warning.13", //$NON-NLS-1$ existingFile.getName()), e); } }
/** Writes the specified node, recursively. */ public void write(Node node) { // is there anything to do? if (node == null) { return; } short type = node.getNodeType(); switch (type) { case Node.DOCUMENT_NODE: { Document document = (Document) node; if (!fCanonical) { fOut.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); fOut.flush(); write(document.getDoctype()); } write(document.getDocumentElement()); break; } case Node.DOCUMENT_TYPE_NODE: { DocumentType doctype = (DocumentType) node; fOut.print("<!DOCTYPE "); fOut.print(doctype.getName()); String publicId = doctype.getPublicId(); String systemId = doctype.getSystemId(); if (publicId != null) { fOut.print(" PUBLIC '"); fOut.print(publicId); fOut.print("' '"); fOut.print(systemId); fOut.print('\''); } else { fOut.print(" SYSTEM '"); fOut.print(systemId); fOut.print('\''); } String internalSubset = doctype.getInternalSubset(); if (internalSubset != null) { fOut.println(" ["); fOut.print(internalSubset); fOut.print(']'); } fOut.println('>'); break; } case Node.ELEMENT_NODE: { fOut.print('<'); fOut.print(node.getNodeName()); Attr attrs[] = sortAttributes(node.getAttributes()); for (int i = 0; i < attrs.length; i++) { Attr attr = attrs[i]; fOut.print(' '); fOut.print(attr.getNodeName()); fOut.print("=\""); normalizeAndPrint(attr.getNodeValue()); fOut.print('"'); } fOut.print('>'); fOut.flush(); Node child = node.getFirstChild(); while (child != null) { write(child); child = child.getNextSibling(); } break; } case Node.ATTRIBUTE_NODE: { Attr attr = (Attr) node; fOut.print(attr.getValue()); fOut.flush(); break; } case Node.ENTITY_REFERENCE_NODE: { if (fCanonical) { Node child = node.getFirstChild(); while (child != null) { write(child); child = child.getNextSibling(); } } else { fOut.print('&'); fOut.print(node.getNodeName()); fOut.print(';'); fOut.flush(); } break; } case Node.CDATA_SECTION_NODE: { if (fCanonical) { normalizeAndPrint(node.getNodeValue()); } else { fOut.print("<![CDATA["); fOut.print(node.getNodeValue()); fOut.print("]]>"); } fOut.flush(); break; } case Node.TEXT_NODE: { normalizeAndPrint(node.getNodeValue()); fOut.flush(); break; } case Node.PROCESSING_INSTRUCTION_NODE: { fOut.print("<?"); fOut.print(node.getNodeName()); String data = node.getNodeValue(); if (data != null && data.length() > 0) { fOut.print(' '); fOut.print(data); } fOut.println("?>"); fOut.flush(); break; } } if (type == Node.ELEMENT_NODE) { fOut.print("</"); fOut.print(node.getNodeName()); fOut.print('>'); fOut.flush(); } } // write(Node)