List of usage examples for javax.xml.transform Source getSystemId
public String getSystemId();
From source file:org.docx4j.fonts.fop.fonts.LazyFont.java
private void load(boolean fail) { if (!isMetricsLoaded) { try {/*from w w w . j ava2 s . c om*/ if (metricsFileName != null) { /**@todo Possible thread problem here */ FontReader reader = null; if (resolver != null) { Source source = resolver.resolve(metricsFileName); if (source == null) { String err = "Cannot load font: failed to create Source from metrics file " + metricsFileName; if (fail) { throw new RuntimeException(err); } else { log.error(err); } return; } InputStream in = null; if (source instanceof StreamSource) { in = ((StreamSource) source).getInputStream(); } if (in == null && source.getSystemId() != null) { in = new java.net.URL(source.getSystemId()).openStream(); } if (in == null) { String err = "Cannot load font: After URI resolution, the returned" + " Source object does not contain an InputStream" + " or a valid URL (system identifier) for metrics file: " + metricsFileName; if (fail) { throw new RuntimeException(err); } else { log.error(err); } return; } InputSource src = new InputSource(in); src.setSystemId(source.getSystemId()); reader = new FontReader(src); } else { reader = new FontReader(new InputSource(new URL(metricsFileName).openStream())); } reader.setKerningEnabled(useKerning); if (this.embedded) { reader.setFontEmbedPath(fontEmbedPath); } reader.setResolver(resolver); realFont = reader.getFont(); } else { if (fontEmbedPath == null) { throw new RuntimeException("Cannot load font. No font URIs available."); } realFont = FontLoader.loadFont(fontEmbedPath, this.subFontName, this.embedded, this.encodingMode, useKerning, resolver); } if (realFont instanceof FontDescriptor) { realFontDescriptor = (FontDescriptor) realFont; } } catch (FOPException fopex) { log.error("Failed to read font metrics file " + metricsFileName, fopex); if (fail) { throw new RuntimeException(fopex.getMessage()); } } catch (IOException ioex) { log.error("Failed to read font metrics file " + metricsFileName, ioex); if (fail) { throw new RuntimeException(ioex.getMessage()); } } realFont.setEventListener(this.eventListener); isMetricsLoaded = true; } }
From source file:org.ikasan.filetransfer.xml.transform.DefaultXSLTransformer.java
/** * Compiles the specified XSL stylesheet into translets and * registers them using the internal mapping table. * * @param name - the unique name being mapped to the source instance * holding XSL stylesheet in the internal * mapping table./*from w ww . j a va 2 s .c o m*/ * @param xslSource - the source object that holds an XSL stylesheet URI, * input stream, etc. * @param useXSLTC - the flag indicating whether to use XSLTC. * @throws TransformerConfigurationException */ private synchronized void registerTemplates(String name, Source xslSource, boolean useXSLTC) throws TransformerConfigurationException { if (name == null) throw new NullPointerException("Translet reference name can't be null"); if (name.trim().length() == 0) throw new IllegalArgumentException("Translet reference name can't be empty"); if (xslSource == null) throw new NullPointerException("XSL stylesheet source can't be null"); if (useXSLTC == true) { // Try to get the translet instance associated with // the stylesheet name from the translet mapping table logger.debug("Trying to get translet for [" + name + "]."); Templates translet = translets.get(name); // First time, compile the stylesheet to create a new translet // Add it to the internal mapping table for the later use if (translet == null) { logger.debug("First time, compiling stylesheet..."); logger.debug("XSL stylesheet URI =[" + xslSource.getSystemId() + "]."); translet = this.newTemplates(xslSource); translets.put(new String(name), translet); logger.debug("Name:[" + name + "] => XSLTC:[" + translet + "]."); } else { // Log it to ensure we are using the same translet logger.debug("Name:[" + name + "] => XSLTC:[" + translet + "]."); } // Create a new transformation context for this translet object // Set it as current Transformer instance this.transformer = translet.newTransformer(); } else { // Get a new TransformerFactory instance TransformerFactory tFactory = this.newTransformerFactory(); this.transformer = tFactory.newTransformer(xslSource); } // Also clear all parameters just in case logger.debug("Got a new Transformer."); this.transformer.clearParameters(); }
From source file:org.jasig.portal.io.xml.JaxbPortalDataHandlerService.java
protected final void importData(final Source source, PortalDataKey portalDataKey) { //Get a StAX reader for the source to determine info about the data to import final BufferedXMLEventReader bufferedXmlEventReader = createSourceXmlEventReader(source); //If no PortalDataKey was passed build it from the source if (portalDataKey == null) { final StartElement rootElement = StaxUtils.getRootElement(bufferedXmlEventReader); portalDataKey = new PortalDataKey(rootElement); bufferedXmlEventReader.reset();// w w w .j av a 2 s . c om } final String systemId = source.getSystemId(); //Post Process the PortalDataKey to see if more complex import operations are needed final IPortalDataType portalDataType = this.dataKeyTypes.get(portalDataKey); if (portalDataType == null) { throw new RuntimeException("No IPortalDataType configured for " + portalDataKey + ", the resource will be ignored: " + getPartialSystemId(systemId)); } final Set<PortalDataKey> postProcessedPortalDataKeys = portalDataType.postProcessPortalDataKey(systemId, portalDataKey, bufferedXmlEventReader); bufferedXmlEventReader.reset(); //If only a single result from post processing import if (postProcessedPortalDataKeys.size() == 1) { this.importOrUpgradeData(systemId, DataAccessUtils.singleResult(postProcessedPortalDataKeys), bufferedXmlEventReader); } //If multiple results from post processing ordering is needed else { //Iterate over the data key order list to run the imports in the correct order for (final PortalDataKey orderedPortalDataKey : this.dataKeyImportOrder) { if (postProcessedPortalDataKeys.contains(orderedPortalDataKey)) { //Reset the to start of the XML document for each import/upgrade call bufferedXmlEventReader.reset(); this.importOrUpgradeData(systemId, orderedPortalDataKey, bufferedXmlEventReader); } } } }
From source file:org.toobsframework.transformpipeline.domain.ChainedXSLTransletTransformer.java
public String transform(List inputXSLs, String inputXML, Map inputParams, IXMLTransformerHelper transformerHelper) throws XMLTransformerException { String outputXML = null;/*from w w w.j a v a 2 s. com*/ ByteArrayInputStream xmlInputStream = null; ByteArrayOutputStream xmlOutputStream = null; try { TransformerFactory tFactory = new org.apache.xalan.xsltc.trax.TransformerFactoryImpl(); try { //tFactory.setAttribute("use-classpath", Boolean.TRUE); tFactory.setAttribute("auto-translet", Boolean.TRUE); } catch (IllegalArgumentException iae) { log.error("Error setting XSLTC specific attribute", iae); throw new XMLTransformerException(iae); } setFactoryResolver(tFactory); TransformerFactoryImpl traxFactory = (TransformerFactoryImpl) tFactory; // Create a TransformerHandler for each stylesheet. ArrayList tHandlers = new ArrayList(); TransformerHandler tHandler = null; // Create a SAX XMLReader. XMLReader reader = new org.apache.xerces.parsers.SAXParser(); // transformer3 outputs SAX events to the serializer. if (outputProperties == null) { outputProperties = OutputPropertiesFactory.getDefaultMethodProperties("html"); } Serializer serializer = SerializerFactory.getSerializer(outputProperties); for (int it = 0; it < inputXSLs.size(); it++) { String xslTranslet = (String) inputXSLs.get(it); Source source = uriResolver.resolve(xslTranslet + ".xsl", ""); String tPkg = source.getSystemId().substring(0, source.getSystemId().lastIndexOf("/")) .replaceAll("/", ".").replaceAll("-", "_"); // Package name needs to be set for each TransformerHandler instance tFactory.setAttribute("package-name", tPkg); tHandler = traxFactory.newTransformerHandler(source); // Set parameters and output encoding on each handlers transformer Transformer transformer = tHandler.getTransformer(); transformer.setOutputProperty("encoding", "UTF-8"); transformer.setErrorListener(tFactory.getErrorListener()); if (inputParams != null) { Iterator paramIt = inputParams.entrySet().iterator(); while (paramIt.hasNext()) { Map.Entry thisParam = (Map.Entry) paramIt.next(); transformer.setParameter((String) thisParam.getKey(), (String) thisParam.getValue()); } } if (transformerHelper != null) { transformer.setParameter(TRANSFORMER_HELPER, transformerHelper); } tHandlers.add(tHandler); } tHandler = null; // Link the handlers to each other and to the reader for (int th = 0; th < tHandlers.size(); th++) { tHandler = (TransformerHandler) tHandlers.get(th); if (th == 0) { reader.setContentHandler(tHandler); reader.setProperty("http://xml.org/sax/properties/lexical-handler", tHandler); } else { ((TransformerHandler) tHandlers.get(th - 1)).setResult(new SAXResult(tHandler)); } } // Parse the XML input document. The input ContentHandler and output ContentHandler // work in separate threads to optimize performance. InputSource xmlSource = null; xmlInputStream = new ByteArrayInputStream((inputXML).getBytes("UTF-8")); xmlSource = new InputSource(xmlInputStream); xmlOutputStream = new ByteArrayOutputStream(); serializer.setOutputStream(xmlOutputStream); // Link the last handler to the serializer ((TransformerHandler) tHandlers.get(tHandlers.size() - 1)) .setResult(new SAXResult(serializer.asContentHandler())); reader.parse(xmlSource); outputXML = xmlOutputStream.toString("UTF-8"); } catch (Exception ex) { log.error("Error performing chained transformation: " + ex.getMessage(), ex); throw new XMLTransformerException(ex); } finally { try { if (xmlInputStream != null) { xmlInputStream.close(); xmlInputStream = null; } if (xmlOutputStream != null) { xmlOutputStream.close(); xmlOutputStream = null; } } catch (IOException ex) { } } return outputXML; }
From source file:org.toobsframework.transformpipeline.domain.TransletTransformer.java
@SuppressWarnings("unchecked") protected void doTransform(String xslTranslet, StreamSource xmlSource, Map params, IXMLTransformerHelper transformerHelper, StreamResult xmlResult) throws XMLTransformerException { try {/*from w w w.j a v a2 s . c o m*/ // Dont rely on the system property to get the right transformer TransformerFactory tFactory = new org.apache.xalan.xsltc.trax.TransformerFactoryImpl(); // set the URI Resolver for the transformer factory setFactoryResolver(tFactory); Source source = uriResolver.resolve(xslTranslet + ".xsl", ""); String tPkg = source.getSystemId().substring(0, source.getSystemId().lastIndexOf("/")) .replaceAll("/", ".").replaceAll("-", "_"); try { //tFactory.setAttribute("use-classpath", Boolean.TRUE); tFactory.setAttribute("auto-translet", Boolean.TRUE); tFactory.setAttribute("package-name", tPkg); } catch (IllegalArgumentException iae) { log.error("Error setting XSLTC specific attribute", iae); throw new XMLTransformerException(iae); } Transformer transformer = tFactory.newTransformer(source); // 2.2 Set character encoding for all transforms to UTF-8. transformer.setOutputProperty("encoding", "UTF-8"); transformer.setErrorListener(tFactory.getErrorListener()); // 2.5 Set Parameters necessary for transformation. if (params != null) { Iterator paramIt = params.entrySet().iterator(); while (paramIt.hasNext()) { Map.Entry thisParam = (Map.Entry) paramIt.next(); transformer.setParameter((String) thisParam.getKey(), (String) thisParam.getValue()); } } if (transformerHelper != null) { transformer.setParameter(TRANSFORMER_HELPER, transformerHelper); } // 3. Use the Transformer to transform an XML Source and send the // output to a Result object. transformer.transform(xmlSource, xmlResult); } catch (TransformerConfigurationException tce) { log.error(tce.toString(), tce); throw new XMLTransformerException(tce); } catch (TransformerException te) { log.error(te.toString(), te); throw new XMLTransformerException(te); } }
From source file:org.wm.xml.transform.CachingTransformerFactory.java
/** * Process the source into a Transformer object. If source is a StreamSource * with <code>systemID</code> pointing to a file, transformer is produced * from a cached templates object. Cache is done in soft references; cached * objects are reloaded, when file's date of last modification changes. * * @param source An object that holds a URI, input stream, etc. * @return A Transformer object that may be used to perform a transformation * in a single thread, never null. * @throws TransformerConfigurationException * - May throw this during the/*w ww .j a v a 2 s . com*/ * parse when it is constructing the Templates object and fails. */ public Transformer newTransformer(final Source source) throws TransformerConfigurationException { // Check that source is a StreamSource if (source instanceof StreamSource) try { if (null != source.getSystemId()) { // Create URI of the source final URI uri = new URI(source.getSystemId()); // If URI points to a file, load transformer from the file // (or from the cache) if (FILE_SCHEME.equalsIgnoreCase(uri.getScheme())) return getTemplatesCacheEntry(new File(uri)).templates.newTransformer(); } } catch (URISyntaxException urise) { throw new TransformerConfigurationException(urise); } return super.newTransformer(source); }
From source file:org.wyona.yanel.impl.resources.usecase.UsecaseResource.java
/** * Generate jelly view.//from w w w . j ava 2s. co m */ private InputStream getJellyInputStream(String viewID, String viewTemplate, boolean XMLoutput) throws UsecaseException { try { if (log.isDebugEnabled()) log.debug("viewTemplate: " + viewTemplate); Repository repo = this.getRealm().getRepository(); JellyContext jellyContext = new JellyContext(); jellyContext.setVariable("resource", this); jellyContext.setVariable("yanel.back2context", PathUtil.backToContext(realm, getPath())); jellyContext.setVariable("yanel.back2realm", PathUtil.backToRealm(getPath())); jellyContext.setVariable("yanel.globalHtdocsPath", PathUtil.getGlobalHtdocsPath(this)); jellyContext.setVariable("yanel.resourcesHtdocsPath", PathUtil.getResourcesHtdocsPathURLencoded(this)); jellyContext.setVariable("yanel.reservedPrefix", this.getYanel().getReservedPrefix()); //jellyContext.setVariable("request", request); ByteArrayOutputStream jellyResultStream = new ByteArrayOutputStream(); XMLOutput jellyOutput = XMLOutput.createXMLOutput(jellyResultStream, XMLoutput); InputStream templateInputStream; String templatePublicId; String templateSystemId; if (viewTemplate.startsWith("/")) { if (log.isDebugEnabled()) log.debug( "Accessing view template directly from the repo (no protocol specified). View Template: " + viewTemplate); // for backwards compatibility. when not using a protocol templateInputStream = repo.getNode(viewTemplate).getInputStream(); templatePublicId = "yanelrepo:" + viewTemplate; /*XXX HACK the following does not work: Jelly wants URLs => protocol must be registered by the JVM! templateSystemId = "yanelrepo:"+viewTemplate; */ templateSystemId = "file:///yanelrepo" + viewTemplate; } else { if (log.isDebugEnabled()) log.debug( "Accessing view template through the source-resolver (protocol specified). View Template: " + viewTemplate); SourceResolver resolver = new SourceResolver(this); Source templateSource = resolver.resolve(viewTemplate, null); templateInputStream = ((StreamSource) templateSource).getInputStream(); templatePublicId = templateSource.getSystemId(); /*XXX HACK the following does not work: Jelly wants URLs => protocol must be registered by the JVM! templateSystemId = templateSource.getSystemId(); */ templateSystemId = "file:///" + viewTemplate.replaceFirst(":", "/"); } InputSource inputSource = new InputSource(templateInputStream); inputSource.setPublicId(templatePublicId); inputSource.setSystemId(templateSystemId); jellyContext.runScript(inputSource, jellyOutput); //XXX should we close templateInputStream here?!? jellyOutput.flush(); byte[] result = jellyResultStream.toByteArray(); //System.out.println(new String(result, "utf-8")); return new ByteArrayInputStream(result); } catch (Exception e) { String errorMsg = "Error creating 'jelly' view '" + viewID + "' of usecase resource: " + getName() + ": " + e; log.error(errorMsg, e); throw new UsecaseException(errorMsg, e); } }
From source file:org.xmlunit.builder.InputTest.java
@Test public void should_parse_existing_file_by_name() throws Exception { // given/* ww w . j a va 2 s . com*/ File testFile = TestResources.ANIMAL_FILE.getFile(); // when Source source = Input.fromFile(testFile.getAbsolutePath()).build(); Document doc = parseDocument(source); // then assertThat(doc.getDocumentElement().getTagName()).isEqualTo("animal"); assertThat(TestResources.ANIMAL_FILE.getUri().toString()).isEqualTo(source.getSystemId()); }
From source file:org.xmlunit.builder.InputTest.java
@Test public void should_parse_existing_file_by_file() throws Exception { // given// www. jav a2 s . c o m File testFile = TestResources.ANIMAL_FILE.getFile(); // when Source source = Input.fromFile(testFile).build(); Document doc = parseDocument(source); // then assertThat(doc.getDocumentElement().getTagName()).isEqualTo("animal"); assertThat(TestResources.ANIMAL_FILE.getUri().toString()).isEqualTo(source.getSystemId()); }