List of usage examples for org.w3c.dom Document normalize
public void normalize();
Text
nodes in the full depth of the sub-tree underneath this Node
, including attribute nodes, into a "normal" form where only structure (e.g., elements, comments, processing instructions, CDATA sections, and entity references) separates Text
nodes, i.e., there are neither adjacent Text
nodes nor empty Text
nodes. From source file:Main.java
/** * Try to normalize a document by removing nonsignificant whitespace. * * @see "#62006"/* w w w.j ava2 s .co m*/ */ private static Document normalize(Document orig) throws IOException { DocumentBuilder builder = null; DocumentBuilderFactory factory = getFactory(false, false); try { builder = factory.newDocumentBuilder(); } catch (ParserConfigurationException e) { throw new IOException("Cannot create parser satisfying configuration parameters: " + e, e); //NOI18N } DocumentType doctype = null; NodeList nl = orig.getChildNodes(); for (int i = 0; i < nl.getLength(); i++) { if (nl.item(i) instanceof DocumentType) { // We cannot import DocumentType's, so we need to manually copy it. doctype = (DocumentType) nl.item(i); } } Document doc; if (doctype != null) { doc = builder.getDOMImplementation().createDocument(orig.getDocumentElement().getNamespaceURI(), orig.getDocumentElement().getTagName(), builder.getDOMImplementation().createDocumentType(orig.getDoctype().getName(), orig.getDoctype().getPublicId(), orig.getDoctype().getSystemId())); // XXX what about entity decls inside the DOCTYPE? doc.removeChild(doc.getDocumentElement()); } else { doc = builder.newDocument(); } for (int i = 0; i < nl.getLength(); i++) { Node node = nl.item(i); if (!(node instanceof DocumentType)) { try { doc.appendChild(doc.importNode(node, true)); } catch (DOMException x) { // Thrown in NB-Core-Build #2896 & 2898 inside GeneratedFilesHelper.applyBuildExtensions throw new IOException("Could not import or append " + node + " of " + node.getClass(), x); } } } doc.normalize(); nl = doc.getElementsByTagName("*"); // NOI18N for (int i = 0; i < nl.getLength(); i++) { Element e = (Element) nl.item(i); removeXmlBase(e); NodeList nl2 = e.getChildNodes(); for (int j = 0; j < nl2.getLength(); j++) { Node n = nl2.item(j); if (n instanceof Text && ((Text) n).getNodeValue().trim().length() == 0) { e.removeChild(n); j--; // since list is dynamic } } } return doc; }
From source file:com.ibm.rpe.web.service.docgen.impl.GenerateBaseTemplate.java
private static void createTemplateXmls(String inputFile, BaseTemplateInput data) throws ParserConfigurationException, SAXException, IOException { String directory = (new File(inputFile)).getParent() + File.separator; DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = null; builder = factory.newDocumentBuilder(); Document document = builder.parse(new File(inputFile)); NodeList nlist = document.getElementsByTagName("element"); if (nlist != null && nlist.getLength() > 0) { for (int i = 0; i < nlist.getLength(); i++) { Node node = nlist.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { Element ele = (Element) node; String attr = ele.getAttribute("id"); if (attr.contentEquals(data.getElementId())) { Node newNode = document.createTextNode(data.getReplacement()); node.getParentNode().insertBefore(newNode, node); try { } catch (Exception e1) { e1.printStackTrace(); }/*from w w w . jav a 2s. co m*/ Node removedNode = node.getParentNode().removeChild(node); // System.out.println(nodeToString(removedNode)); String removed = nodeToString(removedNode); removed = replace(removed, data.getReplaceMap()); if (data.isReplaceElementId()) { removed = replaceElementId(removed); } document.normalize(); FileUtils.writeFile(directory + data.getOutputFile(), removed); System.out.println("Removed : " + ((Element) removedNode).getAttribute("id")); try { // prettyPrint(document); } catch (Exception e) { e.printStackTrace(); } break; } } } FileUtils.writeFile(inputFile, transformToString(document)); } }
From source file:com.twinsoft.convertigo.engine.util.RemoteAdmin.java
private void decodeResponseError(String httpResponse) throws RemoteAdminException { Document domResponse; try {//from ww w . j av a2 s.c o m DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder(); domResponse = parser.parse(new InputSource(new StringReader(httpResponse))); domResponse.normalize(); NodeList nodeList = domResponse.getElementsByTagName("error"); if (nodeList.getLength() != 0) { Element errorNode = (Element) nodeList.item(0); Element errorMessage = (Element) errorNode.getElementsByTagName("message").item(0); Element exceptionName = (Element) errorNode.getElementsByTagName("exception").item(0); Element stackTrace = (Element) errorNode.getElementsByTagName("stacktrace").item(0); throw new RemoteAdminException(errorMessage.getTextContent(), exceptionName == null ? "" : exceptionName.getTextContent(), stackTrace == null ? "" : stackTrace.getTextContent()); } } catch (ParserConfigurationException e) { throw new RemoteAdminException("Unable to parse the Convertigo server response: \n" + e.getMessage() + ".\n" + "Received response: " + httpResponse); } catch (IOException e) { throw new RemoteAdminException( "An unexpected error has occured during the Convertigo project deployment.\n" + "(IOException) " + e.getMessage() + "\n" + "Received response: " + httpResponse, e); } catch (SAXException e) { throw new RemoteAdminException("Unable to parse the Convertigo server response: " + e.getMessage() + ".\n" + "Received response: " + httpResponse); } }
From source file:com.servoy.extension.install.LibActivationHandler.java
protected void writeBackXML(Document doc, File f, String encoding) throws IOException, TransformerFactoryConfigurationError, TransformerException, DocumentException { BufferedOutputStream os = null; try {//from w w w . j a v a 2s . co m os = new BufferedOutputStream(new FileOutputStream(f)); doc.normalize(); StringWriter sw = new StringWriter(1024); DOMSource source = new DOMSource(doc); Transformer newTransformer = TransformerFactory.newInstance().newTransformer(); newTransformer.setOutputProperty(OutputKeys.ENCODING, encoding); newTransformer.setOutputProperty(OutputKeys.INDENT, "yes"); //$NON-NLS-1$ newTransformer.transform(source, new StreamResult(sw)); // normally the transformer code above should have been enough for producing pretty formatted XML (needed so that repeated remove/restore of tags // doesn't produce endless newlines or other bad looking XML); but it seems that with some versions of the JDK that doesn't do it's job so we use dom4j final OutputFormat format = OutputFormat.createPrettyPrint(); format.setEncoding(encoding); final XMLWriter writer = new XMLWriter(os, format); writer.write(DocumentHelper.parseText(sw.toString())); } finally { Utils.closeOutputStream(os); } }
From source file:com.twinsoft.convertigo.engine.util.RemoteAdmin.java
public void deployArchive(File archiveFile, boolean bAssembleXsl) throws RemoteAdminException { String deployServiceURL = (bHttps ? "https" : "http") + "://" + serverBaseUrl + "/admin/services/projects.Deploy?bAssembleXsl=" + bAssembleXsl; PostMethod deployMethod = null;//w w w .ja v a2s .c o m Protocol myhttps = null; try { if (bHttps && bTrustAllCertificates) { ProtocolSocketFactory socketFactory = MySSLSocketFactory.getSSLSocketFactory(null, null, null, null, true); myhttps = new Protocol("https", socketFactory, serverPort); Protocol.registerProtocol("https", myhttps); hostConfiguration = httpClient.getHostConfiguration(); hostConfiguration.setHost(host, serverPort, myhttps); httpClient.setHostConfiguration(hostConfiguration); } deployMethod = new PostMethod(deployServiceURL); Part[] parts = { new FilePart(archiveFile.getName(), archiveFile) }; deployMethod.setRequestEntity(new MultipartRequestEntity(parts, deployMethod.getParams())); int returnCode = httpClient.executeMethod(deployMethod); String httpResponse = deployMethod.getResponseBodyAsString(); if (returnCode == HttpStatus.SC_OK) { Document domResponse; try { DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder(); domResponse = parser.parse(new InputSource(new StringReader(httpResponse))); domResponse.normalize(); NodeList nodeList = domResponse.getElementsByTagName("error"); if (nodeList.getLength() != 0) { Element errorNode = (Element) nodeList.item(0); Element errorMessage = (Element) errorNode.getElementsByTagName("message").item(0); Element exceptionName = (Element) errorNode.getElementsByTagName("exception").item(0); Element stackTrace = (Element) errorNode.getElementsByTagName("stacktrace").item(0); if (errorMessage != null) { throw new RemoteAdminException(errorMessage.getTextContent(), exceptionName.getTextContent(), stackTrace.getTextContent()); } else { throw new RemoteAdminException( "An unexpected error has occured during the Convertigo project deployment: \n" + "Body content: \n\n" + XMLUtils.prettyPrintDOMWithEncoding(domResponse, "UTF-8")); } } } catch (ParserConfigurationException e) { throw new RemoteAdminException("Unable to parse the Convertigo server response: \n" + e.getMessage() + ".\n" + "Received response: " + httpResponse); } catch (IOException e) { throw new RemoteAdminException( "An unexpected error has occured during the Convertigo project deployment.\n" + "(IOException) " + e.getMessage() + "\n" + "Received response: " + httpResponse, e); } catch (SAXException e) { throw new RemoteAdminException("Unable to parse the Convertigo server response: " + e.getMessage() + ".\n" + "Received response: " + httpResponse); } } else { decodeResponseError(httpResponse); } } catch (HttpException e) { throw new RemoteAdminException( "An unexpected error has occured during the Convertigo project deployment.\n" + "Cause: " + e.getMessage(), e); } catch (IOException e) { throw new RemoteAdminException( "Unable to reach the Convertigo server: \n" + "(IOException) " + e.getMessage(), e); } catch (Exception e) { throw new RemoteAdminException( "Unable to reach the Convertigo server: \n" + "(Exception) " + e.getMessage(), e); } finally { Protocol.unregisterProtocol("https"); if (deployMethod != null) deployMethod.releaseConnection(); } }
From source file:com.twinsoft.convertigo.engine.util.RemoteAdmin.java
public void login(String username, String password) throws RemoteAdminException, EngineException { PostMethod loginMethod = null;//ww w . j a va 2 s . c om try { String loginServiceURL = (bHttps ? "https" : "http") + "://" + serverBaseUrl + "/admin/services/engine.Authenticate"; Protocol myhttps = null; hostConfiguration = httpClient.getHostConfiguration(); if (bHttps) { if (bTrustAllCertificates) { ProtocolSocketFactory socketFactory = new EasySSLProtocolSocketFactory(); myhttps = new Protocol("https", socketFactory, serverPort); Protocol.registerProtocol("https", myhttps); hostConfiguration.setHost(host, serverPort, myhttps); } } if (("").equals(username) || username == null) { throw new RemoteAdminException( "Unable to connect to the Convertigo server: \"Server administrator\" field is empty."); } if (("").equals(password) || password == null) { throw new RemoteAdminException( "Unable to connect to the Convertigo server: \"Password\" field is empty."); } URL url = new URL(loginServiceURL); HttpState httpState = new HttpState(); httpClient.setState(httpState); // Proxy configuration Engine.theApp.proxyManager.setProxy(hostConfiguration, httpState, url); loginMethod = new PostMethod(loginServiceURL); loginMethod.addParameter("authType", "login"); loginMethod.addParameter("authUserName", username); loginMethod.addParameter("authPassword", password); int returnCode = httpClient.executeMethod(loginMethod); String httpResponse = loginMethod.getResponseBodyAsString(); if (returnCode == HttpStatus.SC_OK) { Document domResponse; try { DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder(); domResponse = parser.parse(new InputSource(new StringReader(httpResponse))); domResponse.normalize(); NodeList nodeList = domResponse.getElementsByTagName("error"); if (nodeList.getLength() != 0) { throw new RemoteAdminException( "Unable to connect to the Convertigo server: wrong username or password."); } } catch (ParserConfigurationException e) { throw new RemoteAdminException("Unable to parse the Convertigo server response: \n" + e.getMessage() + ".\n" + "Received response: " + httpResponse); } catch (IOException e) { throw new RemoteAdminException( "An unexpected error has occured during the Convertigo server login.\n" + "(IOException) " + e.getMessage() + "\n" + "Received response: " + httpResponse, e); } catch (SAXException e) { throw new RemoteAdminException("Unable to parse the Convertigo server response: " + e.getMessage() + ".\n" + "Received response: " + httpResponse); } } else { decodeResponseError(httpResponse); } } catch (HttpException e) { throw new RemoteAdminException("An unexpected error has occured during the Convertigo server login.\n" + "Cause: " + e.getMessage(), e); } catch (UnknownHostException e) { throw new RemoteAdminException( "Unable to find the Convertigo server (unknown host): " + e.getMessage()); } catch (IOException e) { String message = e.getMessage(); if (message.indexOf("unable to find valid certification path") != -1) { throw new RemoteAdminException( "The SSL certificate of the Convertigo server is not trusted.\nPlease check the 'Trust all certificates' checkbox."); } else throw new RemoteAdminException( "Unable to reach the Convertigo server: \n" + "(IOException) " + e.getMessage(), e); } catch (GeneralSecurityException e) { throw new RemoteAdminException( "Unable to reach the Convertigo server: \n" + "(GeneralSecurityException) " + e.getMessage(), e); } finally { Protocol.unregisterProtocol("https"); if (loginMethod != null) loginMethod.releaseConnection(); } }
From source file:com.github.zhanhb.ckfinder.connector.support.XmlConfigurationParser.java
/** * Initializes configuration from XML file. * * @param builder context builder/*from w ww .ja v a 2 s .c o m*/ * @param basePathBuilder base url and path builder * @param resourceLoader resource loader to load xml configuration * @param basePath base path * @param xmlFilePath string representation of the xml file * @throws ConnectorException when error occurs * @throws IOException when IO Exception occurs. * @throws org.xml.sax.SAXException syntax error in xml file * @throws ParserConfigurationException no xml provider is avaliable */ private void init(DefaultCKFinderContext.Builder builder, ResourceLoader resourceLoader, String xmlFilePath, Path basePath, BasePathBuilder basePathBuilder) throws ConnectorException, IOException, ParserConfigurationException, SAXException { Resource resource = getFullConfigPath(resourceLoader, xmlFilePath); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc; try (InputStream stream = resource.getInputStream()) { doc = db.parse(stream); } doc.normalize(); License.Builder licenseBuilder = License.builder().name("").key(""); Node node = doc.getFirstChild(); ThumbnailProperties thumbnail = null; ImageProperties.Builder image = ImageProperties.builder(); if (node != null) { NodeList nodeList = node.getChildNodes(); for (int i = 0; i < nodeList.getLength(); i++) { Node childNode = nodeList.item(i); switch (childNode.getNodeName()) { case "enabled": builder.enabled(Boolean.parseBoolean(nullNodeToString(childNode))); break; case "licenseName": licenseBuilder.name(nullNodeToString(childNode)); break; case "licenseKey": licenseBuilder.key(nullNodeToString(childNode)); break; case "imgWidth": String width = nullNodeToString(childNode); width = width.replaceAll("\\D", ""); try { image.maxWidth(Integer.parseInt(width)); } catch (NumberFormatException e) { image.maxWidth(Constants.DEFAULT_IMG_WIDTH); } break; case "imgQuality": String quality = nullNodeToString(childNode); quality = quality.replaceAll("\\D", ""); image.quality(adjustQuality(quality)); break; case "imgHeight": String height = nullNodeToString(childNode); height = height.replaceAll("\\D", ""); try { image.maxHeight(Integer.parseInt(height)); } catch (NumberFormatException e) { image.maxHeight(Constants.DEFAULT_IMG_HEIGHT); } break; case "thumbs": thumbnail = createThumbs(childNode.getChildNodes(), basePath, basePathBuilder); break; case "accessControls": setACLs(builder, childNode.getChildNodes()); break; case "hideFolders": setHiddenFolders(builder, childNode.getChildNodes()); break; case "hideFiles": setHiddenFiles(builder, childNode.getChildNodes()); break; case "checkDoubleExtension": builder.checkDoubleFileExtensions(Boolean.parseBoolean(nullNodeToString(childNode))); break; case "disallowUnsafeCharacters": builder.disallowUnsafeCharacters(Boolean.parseBoolean(nullNodeToString(childNode))); break; case "forceASCII": builder.forceAscii(Boolean.parseBoolean(nullNodeToString(childNode))); break; case "checkSizeAfterScaling": builder.checkSizeAfterScaling(Boolean.parseBoolean(nullNodeToString(childNode))); break; case "htmlExtensions": String htmlExt = nullNodeToString(childNode); StringTokenizer scanner = new StringTokenizer(htmlExt, ","); while (scanner.hasMoreTokens()) { String val = scanner.nextToken(); if (val != null && !val.isEmpty()) { builder.htmlExtension(val.trim().toLowerCase()); } } break; case "secureImageUploads": builder.secureImageUploads(Boolean.parseBoolean(nullNodeToString(childNode))); break; case "uriEncoding": break; case "userRoleSessionVar": builder.userRoleName(nullNodeToString(childNode)); break; case "defaultResourceTypes": String value = nullNodeToString(childNode); StringTokenizer sc = new StringTokenizer(value, ","); while (sc.hasMoreTokens()) { builder.defaultResourceType(sc.nextToken()); } break; case "plugins": setPlugins(builder, childNode, resourceLoader); break; default: break; } } } builder.image(image.build()); builder.licenseFactory(new FixLicenseFactory(licenseBuilder.build())); setTypes(builder.thumbnail(thumbnail), doc, basePathBuilder, thumbnail); }
From source file:ambit.data.qmrf.QMRFObject.java
public void transform_and_read(Reader in, boolean appendHelp) throws Exception { DOMResult result = new DOMResult(); String filename = "ambit/data/qmrf/qmrf_insert_help.xsl"; if (!appendHelp) filename = "ambit/data/qmrf/qmrf_delete_help.xsl"; InputStream xslt = this.getClass().getClassLoader().getResourceAsStream(filename); xsltTransform(in, xslt, result);/*from ww w . ja v a2 s.c o m*/ xslt.close(); Document doc = (Document) result.getNode(); doc.normalize(); fromXML(doc.getDocumentElement()); setNotModified(); fireAmbitObjectEvent(); }
From source file:ambit.data.qmrf.QMRFObject.java
protected void write(Document doc, Writer out) throws Exception { Source source;// w w w . j a va 2s.com try { DOMResult result = transform_help(doc, false); Document newdoc = (Document) result.getNode(); newdoc.normalize(); source = new DOMSource(newdoc); } catch (Exception x) { source = new DOMSource(doc); } Transformer xformer = TransformerFactory.newInstance().newTransformer(); xformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, dtdSchema); xformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "qmrf.dtd"); xformer.setOutputProperty(OutputKeys.INDENT, "Yes"); xformer.setOutputProperty(OutputKeys.STANDALONE, "No"); Result result = new StreamResult(out); xformer.transform(source, result); out.flush(); setNotModified(); fireAmbitObjectEvent(); }
From source file:com.hp.application.automation.tools.results.RunResultRecorder.java
private void write2XML(Document document, String filename) throws TransformerException, FileNotFoundException { document.normalize(); TransformerFactory tFactory = TransformerFactory.newInstance(); Transformer transformer = tFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); DOMSource source = new DOMSource(document); PrintWriter pw = new PrintWriter(new FileOutputStream(filename)); StreamResult result = new StreamResult(pw); transformer.transform(source, result); }