List of usage examples for org.w3c.dom Document getDoctype
public DocumentType getDoctype();
DocumentType
) associated with this document. From source file:org.apache.shindig.gadgets.render.RenderingGadgetRewriter.java
public void rewrite(Gadget gadget, MutableContent mutableContent) throws RewritingException { // Don't touch sanitized gadgets. if (gadget.sanitizeOutput()) { return;/*from w w w.j a va 2 s . c om*/ } try { Document document = mutableContent.getDocument(); Element head = (Element) DomUtil.getFirstNamedChildNode(document.getDocumentElement(), "head"); // Insert new content before any of the existing children of the head element Node firstHeadChild = head.getFirstChild(); // Only inject default styles if no doctype was specified. if (document.getDoctype() == null) { Element defaultStyle = document.createElement("style"); defaultStyle.setAttribute("type", "text/css"); head.insertBefore(defaultStyle, firstHeadChild); defaultStyle.appendChild(defaultStyle.getOwnerDocument().createTextNode(DEFAULT_CSS)); } injectBaseTag(gadget, head); injectGadgetBeacon(gadget, head, firstHeadChild); injectFeatureLibraries(gadget, head, firstHeadChild); // This can be one script block. Element mainScriptTag = document.createElement("script"); GadgetContext context = gadget.getContext(); MessageBundle bundle = messageBundleFactory.getBundle(gadget.getSpec(), context.getLocale(), context.getIgnoreCache(), context.getContainer()); injectMessageBundles(bundle, mainScriptTag); injectDefaultPrefs(gadget, mainScriptTag); injectPreloads(gadget, mainScriptTag); // We need to inject our script before any developer scripts. head.insertBefore(mainScriptTag, firstHeadChild); Element body = (Element) DomUtil.getFirstNamedChildNode(document.getDocumentElement(), "body"); body.setAttribute("dir", bundle.getLanguageDirection()); injectOnLoadHandlers(body); mutableContent.documentChanged(); } catch (GadgetException e) { throw new RewritingException(e.getLocalizedMessage(), e, e.getHttpStatusCode()); } }
From source file:org.apache.stratos.load.balancer.conf.configurator.SynapseConfigurator.java
/** * Write xml document to file./*from w w w . ja va 2 s .co m*/ * * @param document * @param outputFilePath * @throws IOException */ private static void write(Document document, String outputFilePath) throws IOException { try { Transformer transformer = TransformerFactory.newInstance().newTransformer(); DocumentType documentType = document.getDoctype(); if (documentType != null) { String publicId = documentType.getPublicId(); if (publicId != null) { transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, publicId); } transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, documentType.getSystemId()); } transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); Source source = new DOMSource(document); FileOutputStream outputStream = new FileOutputStream(outputFilePath); Result result = new StreamResult(outputStream); transformer.transform(source, result); } catch (Exception e) { throw new RuntimeException(String.format("Could not write xml file: s%", outputFilePath), e); } }
From source file:org.cruxframework.crux.core.declarativeui.ViewParser.java
/** * @param cruxPageDocument//from ww w . j av a2s . c o m * @return */ private Document createHTMLDocument(Document cruxPageDocument) { Document htmlDocument; DocumentType doctype = cruxPageDocument.getDoctype(); if (doctype != null || Boolean.parseBoolean(ConfigurationFactory.getConfigurations().enableGenerateHTMLDoctype())) { String name = doctype != null ? doctype.getName() : "HTML"; String publicId = doctype != null ? doctype.getPublicId() : null; String systemId = doctype != null ? doctype.getSystemId() : null; DocumentType newDoctype = documentBuilder.getDOMImplementation().createDocumentType(name, publicId, systemId); htmlDocument = documentBuilder.getDOMImplementation().createDocument(XHTML_NAMESPACE, "html", newDoctype); } else { htmlDocument = documentBuilder.newDocument(); Element cruxPageElement = cruxPageDocument.getDocumentElement(); Node htmlElement = htmlDocument.importNode(cruxPageElement, false); htmlDocument.appendChild(htmlElement); } String manifest = cruxPageDocument.getDocumentElement().getAttribute("manifest"); if (!StringUtils.isEmpty(manifest)) { htmlDocument.getDocumentElement().setAttribute("manifest", manifest); } return htmlDocument; }
From source file:org.cruxframework.crux.core.declarativeui.ViewParser.java
/** * @param out// ww w . jav a 2 s .c om * @throws IOException */ private void write(Document htmlDocument, Writer out) throws IOException { DocumentType doctype = htmlDocument.getDoctype(); if (doctype != null) { out.write("<!DOCTYPE " + doctype.getName() + ">\n"); } HTMLUtils.write(htmlDocument.getDocumentElement(), out, indentOutput); }
From source file:org.dspace.installer_edm.InstallerEDMAskosi.java
/** * Modifica el archivo web.xml de Askosi para indicarle el directorio de datos de Askosi * * @param webXmlFile archivo web.xml de Askosi *///from ww w . j ava 2 s.c o m private void changeWebXml(File webXmlFile, String webXmlFileName) { try { // se abre con DOM el archivo web.xml DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(webXmlFile); XPath xpathInputForms = XPathFactory.newInstance().newXPath(); // se busca el elemento SKOSdirectory NodeList results = (NodeList) xpathInputForms.evaluate("//*[contains(*,\"SKOSdirectory\")]", doc, XPathConstants.NODESET); if (results.getLength() > 0) { Element contextParam = (Element) results.item(0); // se busca el elemento context-param como hijo del anterior if (contextParam.getTagName().equals("context-param")) { // se busca el elemento param-value como hijo del anterior NodeList resultsParamValue = contextParam.getElementsByTagName("param-value"); if (resultsParamValue.getLength() > 0) { // se modifica con la ruta del directorio de datos de Askosi Element valueParam = (Element) resultsParamValue.item(0); Text text = doc.createTextNode(finalAskosiDataDestDirFile.getAbsolutePath()); valueParam.replaceChild(text, valueParam.getFirstChild()); // se guarda TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); transformer.setOutputProperty(OutputKeys.METHOD, "xml"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); //transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); DocumentType docType = doc.getDoctype(); if (docType != null) { if (docType.getPublicId() != null) transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, docType.getPublicId()); transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, docType.getSystemId()); } DOMSource source = new DOMSource(doc); StreamResult result = (fileSeparator.equals("\\")) ? new StreamResult(webXmlFileName) : new StreamResult(webXmlFile); transformer.transform(source, result); } } } else installerEDMDisplay.showQuestion(currentStepGlobal, "changeWebXml.noSKOSdirectory", new String[] { webXmlFile.getAbsolutePath() }); } catch (ParserConfigurationException e) { showException(e); } catch (SAXException e) { showException(e); } catch (IOException e) { showException(e); } catch (XPathExpressionException e) { showException(e); } catch (TransformerConfigurationException e) { showException(e); } catch (TransformerException e) { showException(e); } }
From source file:org.josso.tooling.gshell.install.installer.VFSInstaller.java
protected Document readContentAsDom(FileObject file, boolean nameSpaceAware) throws Exception { InputStream is = null;//from w w w .j ava 2 s . c o m try { is = file.getContent().getInputStream(); DocumentBuilderFactory parserFactory = DocumentBuilderFactory.newInstance(); parserFactory.setValidating(false); parserFactory.setNamespaceAware(nameSpaceAware); 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 = file.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(); if (log.isDebugEnabled() && docType != null) { log.debug("docType.getPublicId()=" + docType.getPublicId()); log.debug("docType.getSystemId()=" + docType.getSystemId()); } return doc; } catch (Exception e) { log.error(e.getMessage(), e); throw e; } finally { if (is != null) try { is.close(); } catch (IOException e) { /**/} } }
From source file:org.openbravo.erpCommon.ad_forms.TranslationManager.java
/** * Exports a single trl table in a xml file * // www . j a v a 2 s .c o m * @param AD_Language * Language to export * @param exportReferenceData * Defines whether exporting reference data * @param exportAll * In case it is reference data if it should be exported all data or just imported * @param table * Base table * @param tableID * Base table id * @param rootDirectory * Root directory to the the exportation * @param moduleId * Id for the module to export to * @param moduleLanguage * Base language for the module * @param javaPackage * Java package for the module */ private static void exportTable(ConnectionProvider cp, String AD_Language, boolean exportReferenceData, boolean exportAll, String table, String tableID, String rootDirectory, String moduleId, String moduleLanguage, String javaPackage, boolean trl) { Statement st = null; StringBuffer sql = null; try { String trlTable = table; if (trl && !table.endsWith("_TRL")) trlTable = table + "_TRL"; final TranslationData[] trlColumns = getTrlColumns(cp, table); final String keyColumn = table + "_ID"; boolean m_IsCentrallyMaintained = false; try { m_IsCentrallyMaintained = !(TranslationData.centrallyMaintained(cp, table).equals("0")); if (m_IsCentrallyMaintained) log4j.debug("table:" + table + " IS centrally maintained"); else log4j.debug("table:" + table + " is NOT centrally maintained"); } catch (final Exception e) { log4j.error("getTrlColumns (IsCentrallyMaintained)", e); } // Prepare query to retrieve translated rows sql = new StringBuffer("SELECT "); if (trl) sql.append("t.IsTranslated,"); else sql.append("'N', "); sql.append("t.").append(keyColumn); for (int i = 0; i < trlColumns.length; i++) { sql.append(", t.").append(trlColumns[i].c).append(",o.").append(trlColumns[i].c).append(" AS ") .append(trlColumns[i].c).append("O"); } sql.append(" FROM ").append(trlTable).append(" t").append(", ").append(table).append(" o"); if (exportReferenceData && !exportAll) { sql.append(", AD_REF_DATA_LOADED DL"); } sql.append(" WHERE "); if (trl) sql.append("t.AD_Language='" + AD_Language + "'").append(" AND "); sql.append("o.").append(keyColumn).append("= t.").append(keyColumn); if (m_IsCentrallyMaintained) { sql.append(" AND ").append("o.IsCentrallyMaintained='N'"); } // AdClient !=0 not supported sql.append(" AND o.AD_Client_ID='0' "); if (!exportReferenceData) { String tempTrlTableName = trlTable; if (!tempTrlTableName.toLowerCase().endsWith("_trl")) { tempTrlTableName = tempTrlTableName + "_Trl"; } final TranslationData[] parentTable = TranslationData.parentTable(cp, tempTrlTableName); if (parentTable.length == 0) { sql.append(" AND ").append(" o.ad_module_id='").append(moduleId).append("'"); } else { /** Search for ad_module_id in the parent table */ if (StringUtils.isEmpty(parentTable[0].grandparent)) { String strParentTable = parentTable[0].tablename; sql.append(" AND "); sql.append(" exists ( select 1 from ").append(strParentTable).append(" p "); sql.append(" where p.").append(strParentTable + "_ID").append("=") .append("o." + strParentTable + "_ID"); sql.append(" and p.ad_module_id='").append(moduleId).append("')"); } else { String strParentTable = parentTable[0].tablename; String strGandParentTable = parentTable[0].grandparent; sql.append(" AND "); sql.append(" exists ( select 1 from ").append(strGandParentTable).append(" gp, ") .append(strParentTable).append(" p"); sql.append(" where p.").append(strParentTable + "_ID").append("=") .append("o." + strParentTable + "_ID"); sql.append(" and p." + strGandParentTable + "_ID = gp." + strGandParentTable + "_ID"); sql.append(" and gp.ad_module_id='").append(moduleId).append("')"); } } } if (exportReferenceData && !exportAll) { sql.append(" AND DL.GENERIC_ID = o.").append(keyColumn).append(" AND DL.AD_TABLE_ID = '") .append(tableID).append("'").append(" AND DL.AD_MODULE_ID = '").append(moduleId) .append("'"); } sql.append(" ORDER BY t.").append(keyColumn); // if (log4j.isDebugEnabled()) log4j.debug("SQL:" + sql.toString()); st = cp.getStatement(); if (log4j.isDebugEnabled()) log4j.debug("st"); final ResultSet rs = st.executeQuery(sql.toString()); if (log4j.isDebugEnabled()) log4j.debug("rs"); int rows = 0; boolean hasRows = false; DocumentBuilderFactory factory = null; DocumentBuilder builder = null; Document document = null; Element root = null; File out = null; // Create xml file String directory = ""; factory = DocumentBuilderFactory.newInstance(); builder = factory.newDocumentBuilder(); document = builder.newDocument(); // Root root = document.createElement(XML_TAG); root.setAttribute(XML_ATTRIBUTE_LANGUAGE, AD_Language); root.setAttribute(XML_ATTRIBUTE_TABLE, table); root.setAttribute(XML_ATTRIBUTE_BASE_LANGUAGE, moduleLanguage); root.setAttribute(XML_ATTRIBUTE_VERSION, TranslationData.version(cp)); document.appendChild(root); if (moduleId.equals("0")) directory = rootDirectory + AD_Language + "/"; else directory = rootDirectory + AD_Language + "/" + javaPackage + "/"; if (!new File(directory).exists()) (new File(directory)).mkdir(); String fileName = directory + trlTable + "_" + AD_Language + ".xml"; log4j.info("exportTrl - " + fileName); out = new File(fileName); while (rs.next()) { if (!hasRows && !exportReferenceData) { // Create file only in // case it has contents // or it is not rd hasRows = true; factory = DocumentBuilderFactory.newInstance(); builder = factory.newDocumentBuilder(); document = builder.newDocument(); // Root root = document.createElement(XML_TAG); root.setAttribute(XML_ATTRIBUTE_LANGUAGE, AD_Language); root.setAttribute(XML_ATTRIBUTE_TABLE, table); root.setAttribute(XML_ATTRIBUTE_BASE_LANGUAGE, moduleLanguage); root.setAttribute(XML_ATTRIBUTE_VERSION, TranslationData.version(cp)); document.appendChild(root); if (moduleId.equals("0")) directory = rootDirectory + AD_Language + "/"; else directory = rootDirectory + AD_Language + "/" + javaPackage + "/"; if (!new File(directory).exists()) (new File(directory)).mkdir(); fileName = directory + trlTable + "_" + AD_Language + ".xml"; log4j.info("exportTrl - " + fileName); out = new File(fileName); } final Element row = document.createElement(XML_ROW_TAG); row.setAttribute(XML_ROW_ATTRIBUTE_ID, String.valueOf(rs.getString(2))); // KeyColumn row.setAttribute(XML_ROW_ATTRIBUTE_TRANSLATED, rs.getString(1)); // IsTranslated for (int i = 0; i < trlColumns.length; i++) { final Element value = document.createElement(XML_VALUE_TAG); value.setAttribute(XML_VALUE_ATTRIBUTE_COLUMN, trlColumns[i].c); String origString = rs.getString(trlColumns[i].c + "O"); // Original String isTrlString = "Y"; // Value if (origString == null) { origString = ""; isTrlString = "N"; } String valueString = rs.getString(trlColumns[i].c); // Value if (valueString == null) { valueString = ""; isTrlString = "N"; } if (origString.equals(valueString)) isTrlString = "N"; value.setAttribute(XML_VALUE_ATTRIBUTE_ISTRL, isTrlString); value.setAttribute(XML_VALUE_ATTRIBUTE_ORIGINAL, origString); value.appendChild(document.createTextNode(valueString)); row.appendChild(value); } root.appendChild(row); rows++; } rs.close(); log4j.info("exportTrl - Records=" + rows + ", DTD=" + document.getDoctype()); final DOMSource source = new DOMSource(document); final TransformerFactory tFactory = TransformerFactory.newInstance(); tFactory.setAttribute("indent-number", new Integer(2)); final Transformer transformer = tFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); // Output out.createNewFile(); // Transform final OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(out), "UTF-8"); transformer.transform(source, new StreamResult(osw)); osw.close(); } catch (final Exception e) { log4j.error("Error exporting translation for table " + table + "\n" + sql, e); } finally { try { if (st != null) cp.releaseStatement(st); } catch (final Exception ignored) { } } }
From source file:org.openmrs.util.OpenmrsUtil.java
/** * Save the given xml document to the given outfile * // www . ja v a 2 s .co m * @param doc Document to be saved * @param outFile file pointer to the location the xml file is to be saved to */ public static void saveDocument(Document doc, File outFile) { OutputStream outStream = null; try { outStream = new FileOutputStream(outFile); TransformerFactory tFactory = TransformerFactory.newInstance(); Transformer transformer = tFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); DocumentType doctype = doc.getDoctype(); if (doctype != null) { transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, doctype.getPublicId()); transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, doctype.getSystemId()); } DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(outStream); transformer.transform(source, result); } catch (TransformerException e) { throw new ModuleException("Error while saving dwrmodulexml back to dwr-modules.xml", e); } catch (FileNotFoundException e) { throw new ModuleException(outFile.getAbsolutePath() + " file doesn't exist.", e); } finally { try { if (outStream != null) { outStream.close(); } } catch (Exception e) { log.warn("Unable to close outstream", e); } } }
From source file:tufts.vue.ds.XMLIngest.java
public static Schema ingestXML(XmlSchema schema, org.xml.sax.InputSource input, String itemKey) { final org.w3c.dom.Document doc = parseXML(input, false); //doc.normalizeDocument(); if (DEBUG.DR) { try {/*from w w w . j av a 2 s. co m*/ errout("XML parsed, document built:"); errout("org.w3c.dom.Document: " + Util.tags(doc)); final org.w3c.dom.DocumentType type = doc.getDoctype(); //errout("InputEncoding: " + doc.getInputEncoding()); // AbstractMethodError ? //errout("xmlEncoding: " + doc.getXmlEncoding()); // AbstractMethodError //errout("xmlVersion: " + doc.getXmlVersion()); // AbstractMethodError errout("docType: " + Util.tags(type)); if (type != null) { errout("docType.name: " + Util.tags(type.getName())); errout("docType.entities: " + Util.tags(type.getEntities())); errout("docType.notations: " + Util.tags(type.getNotations())); errout("docType.publicId: " + Util.tags(type.getPublicId())); errout("docType.systemId: " + Util.tags(type.getSystemId())); } errout("impl: " + Util.tags(doc.getImplementation().getClass())); errout("docElement: " + Util.tags(doc.getDocumentElement().getClass())); // toString() can dump whole document! } catch (Throwable t) { Log.error("debug failure", t); } } //out("element: " + Util.tags(doc.getDocumentElement())); //outln("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>"); //outln("<!-- created by RSSTest " + new Date() + " from " + src + " -->"); if (schema == null) schema = new XmlSchema(tufts.vue.Resource.instance(input), itemKey); else schema.flushData(); if (false) XPathExtract(schema, doc); else scanNode(schema, doc.getDocumentElement(), null, null); if (DEBUG.DR || DEBUG.SCHEMA) schema.dumpSchema(System.err); return schema; }