List of usage examples for javax.xml.transform.dom DOMSource setSystemId
@Override public void setSystemId(String systemID)
From source file:DOM2DOM.java
public static void main(String[] args) throws TransformerException, TransformerConfigurationException, FileNotFoundException, ParserConfigurationException, SAXException, IOException { TransformerFactory tFactory = TransformerFactory.newInstance(); if (tFactory.getFeature(DOMSource.FEATURE) && tFactory.getFeature(DOMResult.FEATURE)) { //Instantiate a DocumentBuilderFactory. DocumentBuilderFactory dFactory = DocumentBuilderFactory.newInstance(); // And setNamespaceAware, which is required when parsing xsl files dFactory.setNamespaceAware(true); //Use the DocumentBuilderFactory to create a DocumentBuilder. DocumentBuilder dBuilder = dFactory.newDocumentBuilder(); //Use the DocumentBuilder to parse the XSL stylesheet. Document xslDoc = dBuilder.parse("birds.xsl"); // Use the DOM Document to define a DOMSource object. DOMSource xslDomSource = new DOMSource(xslDoc); // Set the systemId: note this is actually a URL, not a local filename xslDomSource.setSystemId("birds.xsl"); // Process the stylesheet DOMSource and generate a Transformer. Transformer transformer = tFactory.newTransformer(xslDomSource); //Use the DocumentBuilder to parse the XML input. Document xmlDoc = dBuilder.parse("birds.xml"); // Use the DOM Document to define a DOMSource object. DOMSource xmlDomSource = new DOMSource(xmlDoc); // Set the base URI for the DOMSource so any relative URIs it contains can // be resolved. xmlDomSource.setSystemId("birds.xml"); // Create an empty DOMResult for the Result. DOMResult domResult = new DOMResult(); // Perform the transformation, placing the output in the DOMResult. transformer.transform(xmlDomSource, domResult); //Instantiate an Xalan XML serializer and use it to serialize the output DOM to System.out // using the default output format, except for indent="yes" java.util.Properties xmlProps = OutputPropertiesFactory.getDefaultMethodProperties("xml"); xmlProps.setProperty("indent", "yes"); xmlProps.setProperty("standalone", "no"); Serializer serializer = SerializerFactory.getSerializer(xmlProps); serializer.setOutputStream(System.out); serializer.asDOMSerializer().serialize(domResult.getNode()); } else {//from w w w . j ava 2 s . c o m throw new org.xml.sax.SAXNotSupportedException("DOM node processing not supported!"); } }
From source file:InlineSchemaValidator.java
/** Main program entry point. */ public static void main(String[] argv) { // is there anything to do? if (argv.length == 0) { printUsage();/*from w w w.j a va 2 s . c om*/ System.exit(1); } // variables Vector schemas = null; Vector instances = null; HashMap prefixMappings = null; HashMap uriMappings = null; String docURI = argv[argv.length - 1]; String schemaLanguage = DEFAULT_SCHEMA_LANGUAGE; int repetition = DEFAULT_REPETITION; boolean schemaFullChecking = DEFAULT_SCHEMA_FULL_CHECKING; boolean honourAllSchemaLocations = DEFAULT_HONOUR_ALL_SCHEMA_LOCATIONS; boolean validateAnnotations = DEFAULT_VALIDATE_ANNOTATIONS; boolean generateSyntheticAnnotations = DEFAULT_GENERATE_SYNTHETIC_ANNOTATIONS; boolean memoryUsage = DEFAULT_MEMORY_USAGE; // process arguments for (int i = 0; i < argv.length - 1; ++i) { String arg = argv[i]; if (arg.startsWith("-")) { String option = arg.substring(1); if (option.equals("l")) { // get schema language name if (++i == argv.length) { System.err.println("error: Missing argument to -l option."); } else { schemaLanguage = argv[i]; } continue; } if (option.equals("x")) { if (++i == argv.length) { System.err.println("error: Missing argument to -x option."); continue; } String number = argv[i]; try { int value = Integer.parseInt(number); if (value < 1) { System.err.println("error: Repetition must be at least 1."); continue; } repetition = value; } catch (NumberFormatException e) { System.err.println("error: invalid number (" + number + ")."); } continue; } if (arg.equals("-a")) { // process -a: xpath expressions for schemas if (schemas == null) { schemas = new Vector(); } while (i + 1 < argv.length - 1 && !(arg = argv[i + 1]).startsWith("-")) { schemas.add(arg); ++i; } continue; } if (arg.equals("-i")) { // process -i: xpath expressions for instance documents if (instances == null) { instances = new Vector(); } while (i + 1 < argv.length - 1 && !(arg = argv[i + 1]).startsWith("-")) { instances.add(arg); ++i; } continue; } if (arg.equals("-nm")) { String prefix; String uri; while (i + 2 < argv.length - 1 && !(prefix = argv[i + 1]).startsWith("-") && !(uri = argv[i + 2]).startsWith("-")) { if (prefixMappings == null) { prefixMappings = new HashMap(); uriMappings = new HashMap(); } prefixMappings.put(prefix, uri); HashSet prefixes = (HashSet) uriMappings.get(uri); if (prefixes == null) { prefixes = new HashSet(); uriMappings.put(uri, prefixes); } prefixes.add(prefix); i += 2; } continue; } if (option.equalsIgnoreCase("f")) { schemaFullChecking = option.equals("f"); continue; } if (option.equalsIgnoreCase("hs")) { honourAllSchemaLocations = option.equals("hs"); continue; } if (option.equalsIgnoreCase("va")) { validateAnnotations = option.equals("va"); continue; } if (option.equalsIgnoreCase("ga")) { generateSyntheticAnnotations = option.equals("ga"); continue; } if (option.equalsIgnoreCase("m")) { memoryUsage = option.equals("m"); continue; } if (option.equals("h")) { printUsage(); continue; } System.err.println("error: unknown option (" + option + ")."); continue; } } try { // Create new instance of inline schema validator. InlineSchemaValidator inlineSchemaValidator = new InlineSchemaValidator(prefixMappings, uriMappings); // Parse document containing schemas and validation roots DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); DocumentBuilder db = dbf.newDocumentBuilder(); db.setErrorHandler(inlineSchemaValidator); Document doc = db.parse(docURI); // Create XPath factory for selecting schema and validation roots XPathFactory xpf = XPathFactory.newInstance(); XPath xpath = xpf.newXPath(); xpath.setNamespaceContext(inlineSchemaValidator); // Select schema roots from the DOM NodeList[] schemaNodes = new NodeList[schemas != null ? schemas.size() : 0]; for (int i = 0; i < schemaNodes.length; ++i) { XPathExpression xpathSchema = xpath.compile((String) schemas.elementAt(i)); schemaNodes[i] = (NodeList) xpathSchema.evaluate(doc, XPathConstants.NODESET); } // Select validation roots from the DOM NodeList[] instanceNodes = new NodeList[instances != null ? instances.size() : 0]; for (int i = 0; i < instanceNodes.length; ++i) { XPathExpression xpathInstance = xpath.compile((String) instances.elementAt(i)); instanceNodes[i] = (NodeList) xpathInstance.evaluate(doc, XPathConstants.NODESET); } // Create SchemaFactory and configure SchemaFactory factory = SchemaFactory.newInstance(schemaLanguage); factory.setErrorHandler(inlineSchemaValidator); try { factory.setFeature(SCHEMA_FULL_CHECKING_FEATURE_ID, schemaFullChecking); } catch (SAXNotRecognizedException e) { System.err.println("warning: SchemaFactory does not recognize feature (" + SCHEMA_FULL_CHECKING_FEATURE_ID + ")"); } catch (SAXNotSupportedException e) { System.err.println("warning: SchemaFactory does not support feature (" + SCHEMA_FULL_CHECKING_FEATURE_ID + ")"); } try { factory.setFeature(HONOUR_ALL_SCHEMA_LOCATIONS_ID, honourAllSchemaLocations); } catch (SAXNotRecognizedException e) { System.err.println("warning: SchemaFactory does not recognize feature (" + HONOUR_ALL_SCHEMA_LOCATIONS_ID + ")"); } catch (SAXNotSupportedException e) { System.err.println( "warning: SchemaFactory does not support feature (" + HONOUR_ALL_SCHEMA_LOCATIONS_ID + ")"); } try { factory.setFeature(VALIDATE_ANNOTATIONS_ID, validateAnnotations); } catch (SAXNotRecognizedException e) { System.err.println( "warning: SchemaFactory does not recognize feature (" + VALIDATE_ANNOTATIONS_ID + ")"); } catch (SAXNotSupportedException e) { System.err.println( "warning: SchemaFactory does not support feature (" + VALIDATE_ANNOTATIONS_ID + ")"); } try { factory.setFeature(GENERATE_SYNTHETIC_ANNOTATIONS_ID, generateSyntheticAnnotations); } catch (SAXNotRecognizedException e) { System.err.println("warning: SchemaFactory does not recognize feature (" + GENERATE_SYNTHETIC_ANNOTATIONS_ID + ")"); } catch (SAXNotSupportedException e) { System.err.println("warning: SchemaFactory does not support feature (" + GENERATE_SYNTHETIC_ANNOTATIONS_ID + ")"); } // Build Schema from sources Schema schema; { DOMSource[] sources; int size = 0; for (int i = 0; i < schemaNodes.length; ++i) { size += schemaNodes[i].getLength(); } sources = new DOMSource[size]; if (size == 0) { schema = factory.newSchema(); } else { int count = 0; for (int i = 0; i < schemaNodes.length; ++i) { NodeList nodeList = schemaNodes[i]; int nodeListLength = nodeList.getLength(); for (int j = 0; j < nodeListLength; ++j) { sources[count++] = new DOMSource(nodeList.item(j)); } } schema = factory.newSchema(sources); } } // Setup validator and input source. Validator validator = schema.newValidator(); validator.setErrorHandler(inlineSchemaValidator); try { validator.setFeature(SCHEMA_FULL_CHECKING_FEATURE_ID, schemaFullChecking); } catch (SAXNotRecognizedException e) { System.err.println( "warning: Validator does not recognize feature (" + SCHEMA_FULL_CHECKING_FEATURE_ID + ")"); } catch (SAXNotSupportedException e) { System.err.println( "warning: Validator does not support feature (" + SCHEMA_FULL_CHECKING_FEATURE_ID + ")"); } try { validator.setFeature(HONOUR_ALL_SCHEMA_LOCATIONS_ID, honourAllSchemaLocations); } catch (SAXNotRecognizedException e) { System.err.println( "warning: Validator does not recognize feature (" + HONOUR_ALL_SCHEMA_LOCATIONS_ID + ")"); } catch (SAXNotSupportedException e) { System.err.println( "warning: Validator does not support feature (" + HONOUR_ALL_SCHEMA_LOCATIONS_ID + ")"); } try { validator.setFeature(VALIDATE_ANNOTATIONS_ID, validateAnnotations); } catch (SAXNotRecognizedException e) { System.err .println("warning: Validator does not recognize feature (" + VALIDATE_ANNOTATIONS_ID + ")"); } catch (SAXNotSupportedException e) { System.err.println("warning: Validator does not support feature (" + VALIDATE_ANNOTATIONS_ID + ")"); } try { validator.setFeature(GENERATE_SYNTHETIC_ANNOTATIONS_ID, generateSyntheticAnnotations); } catch (SAXNotRecognizedException e) { System.err.println("warning: Validator does not recognize feature (" + GENERATE_SYNTHETIC_ANNOTATIONS_ID + ")"); } catch (SAXNotSupportedException e) { System.err.println( "warning: Validator does not support feature (" + GENERATE_SYNTHETIC_ANNOTATIONS_ID + ")"); } // Validate instance documents for (int i = 0; i < instanceNodes.length; ++i) { NodeList nodeList = instanceNodes[i]; int nodeListLength = nodeList.getLength(); for (int j = 0; j < nodeListLength; ++j) { DOMSource source = new DOMSource(nodeList.item(j)); source.setSystemId(docURI); inlineSchemaValidator.validate(validator, source, docURI, repetition, memoryUsage); } } } catch (SAXParseException e) { // ignore } catch (Exception e) { System.err.println("error: Parse error occurred - " + e.getMessage()); if (e instanceof SAXException) { Exception nested = ((SAXException) e).getException(); if (nested != null) { e = nested; } } e.printStackTrace(System.err); } }
From source file:Main.java
/** * /*www . j a va2 s .com*/ * <B>Purpose:</B> XML transformation using XSL * * @param doc * @param xslInput * @param systemid * @return * @throws TransformerException */ public static Node transform(Document doc, StreamSource xslInput, String systemid) throws TransformerException { TransformerFactory tFactory = TransformerFactory.newInstance(); Transformer transformer = tFactory.newTransformer(xslInput); DOMResult domResult = new DOMResult(); DOMSource xmlDomSource = null; xmlDomSource = new DOMSource(doc); xmlDomSource.setSystemId(systemid); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); transformer.setOutputProperty("{http://xml.apache.org/xalan}line-separator", "\n"); transformer.transform(xmlDomSource, domResult); return domResult.getNode(); }
From source file:Examples.java
/** * Show how to transform a DOM tree into another DOM tree. * This uses the javax.xml.parsers to parse an XML file into a * DOM, and create an output DOM.//from w w w . ja v a 2 s .co m */ public static Node exampleDOM2DOM(String sourceID, String xslID) throws TransformerException, TransformerConfigurationException, SAXException, IOException, ParserConfigurationException { TransformerFactory tfactory = TransformerFactory.newInstance(); if (tfactory.getFeature(DOMSource.FEATURE)) { Templates templates; { DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance(); dfactory.setNamespaceAware(true); DocumentBuilder docBuilder = dfactory.newDocumentBuilder(); org.w3c.dom.Document outNode = docBuilder.newDocument(); Node doc = docBuilder.parse(new InputSource(xslID)); DOMSource dsource = new DOMSource(doc); // If we don't do this, the transformer won't know how to // resolve relative URLs in the stylesheet. dsource.setSystemId(xslID); templates = tfactory.newTemplates(dsource); } Transformer transformer = templates.newTransformer(); DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance(); // Note you must always setNamespaceAware when building .xsl stylesheets dfactory.setNamespaceAware(true); DocumentBuilder docBuilder = dfactory.newDocumentBuilder(); org.w3c.dom.Document outNode = docBuilder.newDocument(); Node doc = docBuilder.parse(new InputSource(sourceID)); transformer.transform(new DOMSource(doc), new DOMResult(outNode)); Transformer serializer = tfactory.newTransformer(); serializer.transform(new DOMSource(outNode), new StreamResult(new OutputStreamWriter(System.out))); return outNode; } else { throw new org.xml.sax.SAXNotSupportedException("DOM node processing not supported!"); } }
From source file:ddf.services.schematron.SchematronValidationService.java
private Templates compileSchematronRules(String schematronFileName) throws SchematronInitializationException { Templates template;//from www . j a va 2s .c o m File schematronFile = new File(schematronFileName); if (!schematronFile.exists()) { throw new SchematronInitializationException("Could not locate schematron file " + schematronFileName); } try { URL schUrl = schematronFile.toURI().toURL(); Source schSource = new StreamSource(schUrl.toString()); // Stage 1: Perform inclusion expansion on Schematron schema file DOMResult stage1Result = performStage(schSource, getClass().getClassLoader().getResource("iso-schematron/iso_dsdl_include.xsl")); DOMSource stage1Output = new DOMSource(stage1Result.getNode()); // Stage 2: Perform abstract expansion on output file from Stage 1 DOMResult stage2Result = performStage(stage1Output, getClass().getClassLoader().getResource("iso-schematron/iso_abstract_expand.xsl")); DOMSource stage2Output = new DOMSource(stage2Result.getNode()); // Stage 3: Compile the .sch rules that have been prepocessed by Stages 1 and 2 (i.e., // the output of Stage 2) DOMResult stage3Result = performStage(stage2Output, getClass().getClassLoader().getResource("iso-schematron/iso_svrl_for_xslt2.xsl")); DOMSource stage3Output = new DOMSource(stage3Result.getNode()); // Setting the system ID let's us resolve relative paths in the schematron files. // We need the URL string so that the string is properly formatted (e.g. space = %20). stage3Output.setSystemId(schUrl.toString()); template = transformerFactory.newTemplates(stage3Output); } catch (Exception e) { throw new SchematronInitializationException( "Error trying to create SchematronValidationService using sch file " + schematronFileName, e); } return template; }
From source file:com.enonic.vertical.adminweb.handlers.SimpleContentHandlerServlet.java
protected DOMSource buildXSL(HttpSession session, AdminService admin, int contentTypeKey) throws VerticalAdminException { DOMSource result = null; try {/* ww w. ja va2s . c om*/ Document sourceDoc = XMLTool.domparse(admin.getContentTypeModuleData(contentTypeKey)); // Set whether fields are indexed or not Document indexDoc = XMLTool.domparse(admin.getIndexingParametersXML(contentTypeKey)); Element[] indexingParams = XMLTool.getElements(indexDoc.getDocumentElement(), "index"); Element browseElem = XMLTool.getElement(sourceDoc.getDocumentElement(), "browse"); Element[] fields = XMLTool.getElements(browseElem, "field"); for (Element field : fields) { String xpath = XMLTool.getElementText(XMLTool.getElement(field, "xpath")); boolean indexed = false; // Check whether this xpath is in the index doc if (xpath != null) { for (Element indexingParam : indexingParams) { if ((xpath).equals(indexingParam.getAttribute("xpath"))) { indexed = true; } } } field.setAttribute("indexed", String.valueOf(indexed)); } Element rootElement = sourceDoc.getDocumentElement(); // check for xsl: boolean enablePreview = false; Element previewXSLElement = XMLTool.getElement(rootElement, "previewxsl"); if (previewXSLElement != null) { String cdata = XMLTool.getElementText(previewXSLElement); if (cdata.length() > 0) { enablePreview = true; } } // extract module xml: Element moduleElement = XMLTool.getElement(rootElement, "config"); sourceDoc = XMLTool.createDocument(); sourceDoc.appendChild(sourceDoc.importNode(moduleElement, true)); StringWriter swriter = new StringWriter(); Map<String, Object> xslParams = new HashMap<String, Object>(); xslParams.put("xsl_prefix", ""); xslParams.put("enablepreview", String.valueOf(enablePreview)); Source xslFile = AdminStore.getStylesheet(session, FORM_TEMPLATE); transformXML(session, swriter, new DOMSource(sourceDoc), xslFile, xslParams); result = new DOMSource(XMLTool.domparse(swriter.toString())); result.setSystemId(xslFile.getSystemId()); } catch (TransformerConfigurationException e) { VerticalAdminLogger.errorAdmin(this.getClass(), 50, "XSLT error: %t", e); } catch (TransformerException e) { VerticalAdminLogger.errorAdmin(this.getClass(), 50, "XSLT error: %t", e); } return result; }
From source file:org.sakaiproject.tool.assessment.qti.util.XmlUtil.java
/** * Create a transformer from a stylesheet * * @param stylesheet Document/*from www . j a va 2s .co m*/ * * @return the Transformer */ public static Transformer createTransformer(Document stylesheet) { if (log.isDebugEnabled()) { log.debug("createTransformer(Document " + stylesheet + ")"); } Transformer transformer = null; TransformerFactory transformerFactory = TransformerFactory.newInstance(); URIResolver resolver = new URIResolver(); transformerFactory.setURIResolver(resolver); try { DOMSource source = new DOMSource(stylesheet); String systemId = "/xml/xsl/report"; source.setSystemId(systemId); transformer = transformerFactory.newTransformer(source); } catch (TransformerConfigurationException e) { log.error(e.getMessage(), e); } return transformer; }
From source file:org.sakaiproject.tool.help.RestContentProvider.java
/** * create transformer//w w w. java2 s .co m * @param stylesheet * @return */ private static Transformer createTransformer(Document stylesheet) { if (LOG.isDebugEnabled()) { LOG.debug("createTransformer(Document " + stylesheet + ")"); } Transformer transformer = null; TransformerFactory transformerFactory = TransformerFactory.newInstance(); URIResolver resolver = new URIResolver(); transformerFactory.setURIResolver(resolver); try { DOMSource source = new DOMSource(stylesheet); String systemId = "/xsl"; source.setSystemId(systemId); transformer = transformerFactory.newTransformer(source); } catch (TransformerConfigurationException e) { LOG.error(e.getMessage(), e); e.printStackTrace(); } return transformer; }
From source file:org.wm.xml.transform.JTidyResolver.java
/** * Resolves <code>href</code> relatively to <code>base</code> into a source. * * @param href target URI, must be absolute. * @param base base URI, ignored.//from w w w. ja va 2s . co m * @return Source for the transformer, or <code>null</code> if scheme does * not match, or processing errors occured. * @throws TransformerException if this source could not be resolved. */ public Source resolve(final String href, final String base) throws TransformerException { // If URI does not match the SCHEME, return null if (!href.toLowerCase().startsWith(SCHEME)) return null; // Construct an HTTP address final String address = "http" + href.substring(SCHEME.length()); // Create a client final HttpClient client = new HttpClient(); // Check proxy configuration try { if ("true".equals(System.getProperty("proxySet"))) { client.getHostConfiguration().setProxy(System.getProperty("proxyHost"), Integer.parseInt(System.getProperty("proxyPort"))); } } catch (Exception ex) { logger.error("Error checking proxy configuration.", ex); } // Create a method final GetMethod method = new GetMethod(address); int statusCode = -1; final int attempt = 0; // We will retry up to 3 times. while (statusCode == -1 && attempt < 3) { try { // Execute the method. statusCode = client.executeMethod(method); } catch (HttpRecoverableException hrex) { logger.warn("A recoverable exception occurred, retrying." + hrex.getMessage()); } catch (IOException ioex) { logger.error("Failed to retrieve content.", ioex); return VoidSource.voidSource; } } // Check that we didn't run out of retries. if (statusCode == -1) { logger.error("Failed to recover from exception."); return VoidSource.voidSource; } // Read the response body. final byte[] responseBody = method.getResponseBody(); method.releaseConnection(); // Release the connection. final String encoding = method.getResponseCharSet(); String content; try { if (null != encoding) content = new String(responseBody, encoding); else content = new String(responseBody); } catch (Exception ex) { content = ""; } // Create Tidy instance final Tidy tidy = new Tidy(); try { // Parse HTML into DOM final InputStream is = new java.io.ByteArrayInputStream(content.getBytes("UTF-8")); tidy.setCharEncoding(org.w3c.tidy.Configuration.UTF8); final Document document = tidy.parseDOM(is, null); // Return a DOMSource based on the document. final DOMSource domSource = new DOMSource(document); domSource.setSystemId(address); return domSource; } catch (IOException e) { throw new TransformerException("Error parsing HTML at [" + address + "].", e); } }