List of usage examples for javax.xml.transform Transformer setParameter
public abstract void setParameter(String name, Object value);
From source file:com.adobe.aem.importer.impl.DocImporterImpl.java
public void doImport(String importRootPath) { try {// w ww . j a v a2 s . c o m if (!initImport(importRootPath)) { log.info("initImport failed!"); return; } Node xsltNode = this.session.getNode(xsltFilePath); log.info("xsltNode: " + xsltNode); XMLReader xmlReader = XMLReaderFactory.createXMLReader(); log.info("xmlReader: " + xmlReader); xmlReader.setEntityResolver(new RejectingEntityResolver()); URIResolver uriResolver = new DocImporterURIResolver(xsltNode, this.sourceFolderNode, xmlReader); log.info("uriResolver: " + uriResolver); TransformerFactoryImpl transformerFactoryImpl = new TransformerFactoryImpl(); log.info("transformerFactoryImpl: " + transformerFactoryImpl); transformerFactoryImpl.setURIResolver(uriResolver); Transformer transformer = transformerFactoryImpl .newTransformer(new StreamSource(JcrUtils.readFile(xsltNode))); TransformerImpl transformerImpl = (TransformerImpl) transformer; transformerImpl.getUnderlyingController() .setUnparsedTextURIResolver(new DocImporterUnparsedTextURIResolver(this.sourceFolderNode)); log.info("transformer: " + transformer); for (Entry<Object, Object> entry : properties.entrySet()) { transformer.setParameter(entry.getKey().toString(), entry.getValue()); log.info("transformer.setParameter: " + entry.getKey().toString() + " = " + entry.getValue()); } transformer.setParameter("xsltFilePath", this.xsltFilePath); log.info("transformer.setParameter: xsltFilePath = " + this.xsltFilePath); ByteArrayOutputStream output = new ByteArrayOutputStream(); transformer .transform( new SAXSource(xmlReader, new InputSource( JcrUtils.readFile(this.sourceFolderNode.getNode(masterFileName)))), new StreamResult(output)); InputStream result = new ByteArrayInputStream(output.toByteArray()); log.info("result: " + result); if (this.session.itemExists(DocImporter.CONTENT_PACKAGE_PATH)) { this.session.removeItem(DocImporter.CONTENT_PACKAGE_PATH); this.session.save(); log.info("old package removed"); } Node contentPackageNode = JcrUtils.getOrCreateByPath(DocImporter.CONTENT_PACKAGE_PATH, "nt:folder", "nt:folder", this.session, true); this.session.getWorkspace().copy(DocImporter.CONTENT_PACKAGE_TEMPLATE_PATH + "/META-INF", contentPackageNode.getPath() + "/META-INF"); log.info("new package created"); Node vaultNode = contentPackageNode.getNode("META-INF/vault"); Node contentXMLNode = JcrUtil.createPath(contentPackageNode.getPath() + "/jcr_root" + targetPath, "nt:folder", "nt:folder", this.session, true); JcrUtils.putFile(contentXMLNode, ".content.xml", "application/xml", result); log.info("content.xml written"); if (this.graphicsFolderName != null && this.sourceFolderNode.hasNode(this.graphicsFolderName)) { JcrUtil.copy(this.sourceFolderNode.getNode(graphicsFolderName), contentXMLNode, this.graphicsFolderName); } JcrUtils.putFile(vaultNode, "filter.xml", "application/xml", FilterXmlBuilder.fromRoot(this.targetPath + "/").toStream(this.graphicsFolderName)); log.info("filter.xml written"); JcrArchive archive = new JcrArchive(contentPackageNode, "/"); archive.open(true); Importer importer = new Importer(); importer.getOptions().setImportMode(ImportMode.MERGE); importer.getOptions().setAccessControlHandling(AccessControlHandling.MERGE); importer.run(archive, contentPackageNode.getSession().getNode("/")); log.info("content.xml imported"); //contentPackageNode.remove(); this.session.save(); log.info("session saved."); } catch (RepositoryException e) { log.error(e.toString()); } catch (TransformerException e) { log.error(e.toString()); } catch (SAXException e) { log.error(e.toString()); } catch (IOException e) { log.error(e.toString()); } catch (ConfigurationException e) { log.error(e.toString()); } }
From source file:org.sakaiproject.metaobj.shared.control.XsltArtifactView.java
/** * Perform the actual transformation, writing to the given result. * @param source the Source to transform * @param parameters a Map of parameters to be applied to the stylesheet * @param result the result to write to/* www. ja v a 2 s . c o m*/ * @throws Exception we let this method throw any exception; the * AbstractXlstView superclass will catch exceptions */ protected void doTransform(Source source, Map parameters, Result result, String encoding) throws Exception { InputStream stylesheetLocation = null; // Nulls gets logged by getTransformer, so don't bother logging again. if (parameters != null) stylesheetLocation = (InputStream) parameters.get(STYLESHEET_LOCATION); Transformer trans = getTransformer(stylesheetLocation); // Explicitly apply URIResolver to every created Transformer. if (getUriResolver() != null) { trans.setURIResolver(getUriResolver()); } // Apply any subclass supplied parameters to the transformer. if (parameters != null) { for (Iterator it = parameters.entrySet().iterator(); it.hasNext();) { Map.Entry entry = (Map.Entry) it.next(); trans.setParameter(entry.getKey().toString(), entry.getValue()); } if (logger.isDebugEnabled()) { logger.debug("Added parameters [" + parameters + "] to transformer object"); } } // Specify default output properties. //trans.setOutputProperty(OutputKeys.ENCODING, encoding); trans.setOutputProperty(OutputKeys.INDENT, "yes"); // Xalan-specific, but won't do any harm in other XSLT engines. trans.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); // Perform the actual XSLT transformation. try { trans.transform(source, result); if (logger.isDebugEnabled()) { logger.debug("XSLT transformed with stylesheet [" + stylesheetLocation + "]"); } } catch (TransformerException ex) { throw new NestedServletException("Couldn't perform transform with stylesheet [" + stylesheetLocation + "] in XSLT view with name [" + getBeanName() + "]", ex); } }
From source file:de.betterform.agent.betty.Betty.java
protected String renderForm(Document document) throws Exception { // todo: determine from browser document String encoding = "UTF-8"; LOGGER.debug("renderForm"); // obtain transformer for stylesheet uri String stylesheetParameter = getParameter(XSLT_PARAMETER); if (stylesheetParameter == null || stylesheetParameter.length() == 0) { stylesheetParameter = XSLT_DEFAULT; }//from www . jav a 2 s . c o m LOGGER.debug("stylesheetParameter: " + stylesheetParameter); URI stylesheetURI = new URI(getCodeBase().toString()).resolve(stylesheetParameter); LOGGER.debug("styleSheetURI: " + stylesheetURI); TransformerService transformerService = new CachingTransformerService(new FileResourceResolver()); System.setProperty("javax.xml.transform.TransformerFactory", "net.sf.saxon.TransformerFactoryImpl"); Transformer transformer = transformerService.getTransformer(stylesheetURI); // setup source and result objects Source documentSource = new DOMSource(document); ByteArrayOutputStream stream = new ByteArrayOutputStream(); Result streamResult = new StreamResult(stream); // go transformer.setParameter("debug-enabled", String.valueOf(LOGGER.isDebugEnabled())); transformer.setParameter("betterform-pseudo-item", BETTERFORM_PSEUDO_ITEM); transformer.setOutputProperty(OutputKeys.ENCODING, encoding); transformer.transform(documentSource, streamResult); String result = stream.toString(encoding); if (LOGGER.isDebugEnabled()) { LOGGER.debug("result >>>>>:" + result); } // return result.substring(result.indexOf("<form"),result.lastIndexOf("</html>")); return result.substring(result.indexOf("<form")); }
From source file:com.amalto.core.plugin.base.xslt.XSLTTransformerPluginBean.java
/** * @throws XtentisException//from w ww . j ava 2s . co m * * @ejb.interface-method view-type = "local" * @ejb.facade-method */ public void init(TransformerPluginContext context, String compiledParameters) throws XtentisException { try { if (!configurationLoaded) { loadConfiguration(); } // fetech the parameters CompiledParameters parameters = CompiledParameters.deserialize(compiledParameters); // get the xslt compiled style sheet and the Transformer /** * Unfortunately this does not work for the moment PreparedStylesheet preparedStyleSheet * =parameters.getPreparedStyleSheet(); Transformer transformer = preparedStyleSheet.newTransformer(); **/ // As a replacement in the meantime setCompilationErrors(""); //$NON-NLS-1$ // USE SAXON for XSLT 2.0 Support TransformerFactory transFactory = new net.sf.saxon.TransformerFactoryImpl(); transFactory.setErrorListener(new ErrorListener() { public void error(TransformerException exception) throws TransformerException { add2CompilationErrors(exception.getLocalizedMessage()); } public void fatalError(TransformerException exception) throws TransformerException { add2CompilationErrors(exception.getLocalizedMessage()); } public void warning(TransformerException exception) throws TransformerException { String err = "XSLT Plugin: Warning during the compilation of the XSLT"; //$NON-NLS-1$ LOG.warn(err, exception); } }); transFactory.setAttribute(FeatureKeys.VERSION_WARNING, Boolean.valueOf(false)); if (!"".equals(getCompilationErrors())) { //$NON-NLS-1$ String err = "XSLT Plugin: Errors occurred during the compilation of the XSLT:" //$NON-NLS-1$ + getCompilationErrors(); LOG.error(err); throw new XtentisException(err); } Transformer transformer = transFactory .newTransformer(new StreamSource(new StringReader(parameters.getXslt()))); // Pass Parameters to the XSLT processor String username = LocalUser.getLocalUser().getUsername(); transformer.setParameter("USERNAME", username); //$NON-NLS-1$ transformer.setErrorListener(new ErrorListener() { public void error(TransformerException exception) throws TransformerException { String err = "XSLT Plugin: An error occured during the XSLT transformation"; //$NON-NLS-1$ LOG.error(err, exception); throw new TransformerException(err); } public void fatalError(TransformerException exception) throws TransformerException { String err = "XSLT Plugin: A fatal error occured during the XSLT transformation"; //$NON-NLS-1$ LOG.error(err, exception); throw new TransformerException(err); } public void warning(TransformerException exception) throws TransformerException { String err = "XSLT Plugin: Warning during the XSLT transformation"; //$NON-NLS-1$ LOG.warn(err, exception); } }); // Insert all this in the context context.put(TRANSFORMER, transformer); context.put(OUTPUT_METHOD, parameters.getOutputMethod()); } catch (Exception e) { String err = compilationErrors; if (err == null || err.length() == 0) { err = "Could not init the XSLT Plugin"; //$NON-NLS-1$ } LOG.error(err, e); throw new XtentisException(err); } }
From source file:it.cnr.icar.eric.server.cms.CanonicalXMLValidationService.java
public ServiceOutput invoke(ServerRequestContext context, ServiceInput input, ServiceType service, InvocationController invocationController, UserType user) throws RegistryException { ServerRequestContext outputContext = context; try {/*from w ww . j ava 2 s .c o m*/ //ExtrinsicObjectType eo = (ExtrinsicObjectType)input.getRegistryObject(); //RepositoryItem repositoryItem = input.getRepositoryItem(); //DataHandler dh = repositoryItem.getDataHandler(); InputSource inputSource = null; //registryObject MUST be ExrinsicObject or ExternalLink of objectType WSDL ExtrinsicObjectType ebExtrinsicObjectType = null; ExternalLinkType ebExternalLinkType = null; RegistryObjectType ebRegistryObjectType = input.getRegistryObject(); if (ebRegistryObjectType instanceof ExtrinsicObjectType) { ebExtrinsicObjectType = (ExtrinsicObjectType) ebRegistryObjectType; RepositoryItem repositoryItem = input.getRepositoryItem(); if (repositoryItem == null) { // Section 8.10 of the [ebRS] spec specifies that the RI // is optional. Log message and return log.info(ServerResourceBundle.getInstance().getString("message.noRepositoryItemIncluded", new String[] { ebRegistryObjectType.getId() })); ServiceOutput so = new ServiceOutput(); so.setOutput(outputContext); return so; } inputSource = new InputSource(repositoryItem.getDataHandler().getInputStream()); } else if (ebRegistryObjectType instanceof ExternalLinkType) { ebExternalLinkType = (ExternalLinkType) ebRegistryObjectType; String urlStr = ebExternalLinkType.getExternalURI(); urlStr = Utility.absolutize(Utility.getFileOrURLName(urlStr)); URL url = new URL(urlStr); InputStream is = url.openStream(); inputSource = new InputSource(is); } else { throw new ValidationException("RegistryObject not ExtrinsicObject or ExternalLink"); } StreamSource schematronInvControlFileSrc = rm.getAsStreamSource(invocationController.getEoId()); //Commenting out caching until we figure out how to reinit the stream position at begining //Currently if we cache then subsequent uses result in error: "Could not compile stylesheet" // The schematron XSLT file is expected to be stable and change infrequently. So, cache it. //if (schematronXSLTFileSrc == null) { schematronXSLTFileSrc = new StreamSource(this.getClass().getClassLoader() .getResourceAsStream("it/cnr/icar/eric/server/cms/conf/skeleton1-5.xsl")); //} if (log.isDebugEnabled()) { dumpStream(schematronInvControlFileSrc); dumpStream(schematronXSLTFileSrc); } // Use the Schematron Invocation Control File and Schematron XSLT to // create the XSLT Invocation Control File File xsltInvocationControlFile = File.createTempFile("InvocationControlFile_WSDLValidation", ".xslt"); xsltInvocationControlFile.deleteOnExit(); StreamResult xsltInvocationControlFileSR = new StreamResult(xsltInvocationControlFile); TransformerFactory tFactory = TransformerFactory.newInstance(); Transformer transformer = tFactory.newTransformer(schematronXSLTFileSrc); configureTransformer(transformer); // This call creates the XSLT Invocation Control File using // schematron invocation control file and schematron xslt files transformer.transform(schematronInvControlFileSrc, xsltInvocationControlFileSR); // Use generated XSLT Invocation Control File to validate the WSDL file(s) StreamSource xsltInvocationControlFileSrc = new StreamSource(xsltInvocationControlFile); transformer = tFactory.newTransformer(xsltInvocationControlFileSrc); configureTransformer(transformer); //Set respository item as parameter transformer.setParameter("repositoryItem", input.getRegistryObject().getId()); if ((ebExtrinsicObjectType != null) && (ebExtrinsicObjectType.getMimeType().equalsIgnoreCase("application/zip"))) { ArrayList<File> files = Utility.unZip(TMP_DIR, inputSource.getByteStream()); //Now iterate and create ExtrinsicObject - Repository Item pair for each unzipped file Iterator<File> iter = files.iterator(); while (iter.hasNext()) { File file = iter.next(); @SuppressWarnings("resource") BufferedReader br = new BufferedReader(new FileReader(file)); StringBuffer sb = new StringBuffer(); while (br.ready()) { sb.append(br.readLine()); } StringReader reader = new StringReader(sb.toString()); StreamSource inputSrc = new StreamSource(reader); validateXMLFile(inputSrc, transformer); } } else { //Following will fail if there are unresolved imports in the WSDL StreamSource inputSrc = new StreamSource(inputSource.getByteStream()); //dumpStream(inputSrc); //inputSrc = new StreamSource(inputSource.getByteStream()); validateXMLFile(inputSrc, transformer); } } catch (ValidationException e) { if (outputContext != context) { outputContext.rollback(); } log.error(ServerResourceBundle.getInstance().getString("message.errorValidatingXML"), e); throw e; } catch (Exception e) { if (outputContext != context) { outputContext.rollback(); } log.error(ServerResourceBundle.getInstance().getString("message.errorValidatingXML"), e); throw new RegistryException(e); } ServiceOutput so = new ServiceOutput(); so.setOutput(outputContext); if (outputContext != context) { outputContext.commit(); } return so; }
From source file:org.ambraproject.service.XMLServiceImpl.java
/** * Get a translet, compiled stylesheet, for the xslTemplate. If the doc is null * use the default template. If the doc is not null then get the DTD version. * IF the DTD version does not exist use the default template else use the * template associated with that version. * * @param doc the dtd version of document * @return Translet for the xslTemplate. * @throws javax.xml.transform.TransformerException TransformerException. *///from ww w .j a va2s. c o m private Transformer getTranslet(Document doc) throws TransformerException, URISyntaxException { Transformer transformer; // key is "" if the Attribute does not exist String key = (doc == null) ? "default" : doc.getDocumentElement().getAttribute("dtd-version").trim(); if ((!xslTemplateMap.containsKey(key)) || (key.equalsIgnoreCase(""))) { transformer = this.translet.newTransformer(); } else { Templates translet; String templateName = xslTemplateMap.get(key); File file = getAsFile(templateName); if (!file.exists()) { file = new File(templateName); } // set the Templates final TransformerFactory tFactory = TransformerFactory.newInstance(); translet = tFactory.newTemplates(new StreamSource(file)); transformer = translet.newTransformer(); } transformer.setParameter("pubAppContext", configuration.getString("ambra.platform.appContext", "")); return transformer; }
From source file:net.sf.joost.plugins.traxfilter.THResolver.java
/** * Prepare TH instance for work// www.ja v a2 s .co m * * This involves setting TrAX parameters and all other stuff if needed * * @param th * @param params */ protected void prepareTh(TransformerHandler th, Hashtable params) { if (DEBUG) log.debug("prepareTh()"); Transformer tr = th.getTransformer(); // make sure old parameters are cleaned tr.clearParameters(); // set transformation parameters if (!params.isEmpty()) { for (Enumeration e = params.keys(); e.hasMoreElements();) { String key = (String) e.nextElement(); if (DEBUG) log.debug("prepareTh(): set parameter " + key + "=" + params.get(key)); if (!key.startsWith(tmp_TRAX_ATTR_NS) && !key.startsWith(tmp_FILTER_ATTR_NS)) { // ordinary parameter, set it to the TrAX object tr.setParameter(key, params.get(key)); } } } }
From source file:com.manydesigns.portofino.pageactions.crud.CrudAction4ItsProject.java
public void exportSearchPdf(OutputStream outputStream) throws FOPException, IOException, TransformerException { setupSearchForm();//from w w w. j a v a2s . c o m loadObjects(); setupTableForm4ExportAll(Mode.VIEW); FopFactory fopFactory = FopFactory.newInstance(); // hongliangpan add try { String fopConfig = "fop.xml"; String filePath = CrudAction4ItsProject.class.getClassLoader().getResource(fopConfig).getPath(); fopFactory.setUserConfig(filePath); // String fonts = "/fonts"; fopFactory.setFontBaseURL(new File(filePath).getParent()); } catch (SAXException e) { logger.error(e.getMessage(), e); } InputStream xsltStream = null; try { Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, outputStream); xsltStream = getSearchPdfXsltStream(); // Setup XSLT TransformerFactory Factory = TransformerFactory.newInstance(); Transformer transformer = Factory.newTransformer(new StreamSource(xsltStream)); // Set the value of a <param> in the stylesheet transformer.setParameter("versionParam", "2.0"); // Setup input for XSLT transformation Reader reader = composeXmlSearch(); Source src = new StreamSource(reader); // Resulting SAX events (the generated FO) must be piped through to // FOP Result res = new SAXResult(fop.getDefaultHandler()); // Start XSLT transformation and FOP processing transformer.transform(src, res); reader.close(); outputStream.flush(); } finally { IOUtils.closeQuietly(xsltStream); } }
From source file:com.manydesigns.portofino.pageactions.crud.CrudAction4ItsProject.java
public void exportReadPdf(File tempPdfFile) throws FOPException, IOException, TransformerException { setupSearchForm();//from w ww.ja v a2 s. c om loadObjects(); setupTableForm(Mode.VIEW); FopFactory fopFactory = FopFactory.newInstance(); FileOutputStream out = null; InputStream xsltStream = null; try { out = new FileOutputStream(tempPdfFile); Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, out); xsltStream = getXsltStream(TEMPLATE_FOP_READ); // Setup XSLT TransformerFactory Factory = TransformerFactory.newInstance(); Transformer transformer = Factory.newTransformer(new StreamSource(xsltStream)); // Set the value of a <param> in the stylesheet transformer.setParameter("versionParam", "2.0"); // Setup input for XSLT transformation Reader reader = composeXmlPort(); Source src = new StreamSource(reader); // Resulting SAX events (the generated FO) must be piped through to // FOP Result res = new SAXResult(fop.getDefaultHandler()); // Start XSLT transformation and FOP processing transformer.transform(src, res); reader.close(); out.flush(); } catch (Exception e) { logger.warn("IOException", e); SessionMessages.addErrorMessage(e.getMessage()); } finally { IOUtils.closeQuietly(xsltStream); try { if (out != null) out.close(); } catch (Exception e) { logger.warn("IOException", e); SessionMessages.addErrorMessage(e.getMessage()); } } }
From source file:org.ambraproject.article.service.XslIngestArchiveProcessor.java
/** * Run the zip file through the xsl stylesheet * * @param zip the zip archive containing the items to ingest * @param zipInfo the document describing the zip archive (adheres to zip.dtd) * @param articleXml the stylesheet to run on <var>zipInfo</var>; this is the main script * @param doiUrlPrefix DOI URL prefix/*from w w w. j a v a 2 s . co m*/ * @return a document describing the fedora objects to create (must adhere to fedora.dtd) * @throws javax.xml.transform.TransformerException * if an error occurs during the processing */ private Document transformZip(ZipFile zip, String zipInfo, Document articleXml, String doiUrlPrefix) throws TransformerException, URISyntaxException { Transformer t = getTranslet(articleXml); t.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); t.setURIResolver(new ZipURIResolver(zip)); // override the doi url prefix if one is specified in the config if (doiUrlPrefix != null) t.setParameter("doi-url-prefix", doiUrlPrefix); /* * Note: it would be preferable (and correct according to latest JAXP specs) to use * t.setErrorListener(), but Saxon does not forward <xls:message>'s to the error listener. * Hence we need to use Saxon's API's in order to get at those messages. */ final StringWriter msgs = new StringWriter(); MessageWarner em = new MessageWarner(); ((Controller) t).setMessageEmitter(em); t.setErrorListener(new ErrorListener() { public void warning(TransformerException te) { log.warn("Warning received while processing zip", te); } public void error(TransformerException te) { log.warn("Error received while processing zip", te); msgs.write(te.getMessageAndLocation() + '\n'); } public void fatalError(TransformerException te) { log.warn("Fatal error received while processing zip", te); msgs.write(te.getMessageAndLocation() + '\n'); } }); Source inp = new StreamSource(new StringReader(zipInfo), "zip:/"); DOMResult res = new DOMResult(); try { t.transform(inp, res); } catch (TransformerException te) { if (msgs.getBuffer().length() > 0) { log.error(msgs.getBuffer().toString()); throw new TransformerException(msgs.toString(), te); } else throw te; } if (msgs.getBuffer().length() > 0) throw new TransformerException(msgs.toString()); return (Document) res.getNode(); }