List of usage examples for javax.xml.transform Transformer setParameter
public abstract void setParameter(String name, Object value);
From source file:de.betterform.agent.web.servlet.XSLTServlet.java
/** * This method is only called when non-scripted mode is used to update the UI. This basically exists to support * the PFG (POST/FORWARD/GET) pattern that allows to use the browser back button without POSTDATA warning from the browser * and to re-initialize the preceding form (if any). * <p/>//from www . j a v a 2s . c om * To make sure that an update is requested from the XFormsSession and not by the user clicking the reload button the * XFormsSession holds a property XFormsSession.UPDATE_REQUEST when coming from XFormsSession. If this property exists, * the UI is refreshed otherwise the form is re-inited with a GET. * * @param request servlet request * @param response servlet response * @throws javax.servlet.ServletException * @throws java.io.IOException */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ServletContext servletContext = getServletContext(); String stylePath = null; try { stylePath = WebFactory.getRealPath(editorHome, servletContext); } catch (XFormsConfigException e) { throw new ServletException(e); } File styleFile = new File(stylePath, xslFile); if (styleFile == null) { throw new ServletException("XSL stylesheet cannot be found: " + styleFile); } String contentType = null; Document doc = null; String xsl = null; contentType = (String) request.getAttribute("contenttype"); if (contentType == null) contentType = defContentType; // The servlet returns HTML. response.setContentType(contentType); if (cache == null) cache = new HashMap(); Transformer t = null; // Get the XML input document and the stylesheet. // Source xmlSource = new DOMSource(doc); String inputFile = request.getPathTranslated(); File input = new File(inputFile); if (input == null) { throw new ServletException("XML document cannot be found: " + inputFile); } Source xmlSource = new StreamSource(new FileInputStream(input)); // Perform the transformation, sending the output to the response. // XSL processing can be time consuming, but this is mainly due to the overhead // of compiling the XSL sheet. // By caching the compiled sheets, the process is speeded up dramatically. // Time saved on subsequent requests can be 99% or more (hundreds of milliseconds). try { // check if the XSL sheet was found in cache, and use that if available // if (cache.containsKey(xsl)) t = (Transformer)cache.get(xsl); // else // { // otherwise, load the XSL sheet from disk, compile it and store the compiled // sheet in the cache TransformerFactory tFactory = TransformerFactory.newInstance(); Source xslSource = new StreamSource(new FileInputStream(styleFile)); t = tFactory.newTransformer(xslSource); String contextName = request.getContextPath(); t.setParameter("APP_CONTEXT", contextName); t.setParameter("EDITOR_HOME", stylePath.substring(stylePath.indexOf("/betterform/")) + "/"); t.setParameter("filename", "file://" + inputFile); // cache.put(xsl, t); // } // perform the XSL transformation of the XML Document into the servlet outputstream // t.transform(xmlSource, new StreamResult(out)); Document resultDoc = DOMUtil.newDocument(true, false); t.transform(xmlSource, new DOMResult(resultDoc)); request.setAttribute(WebFactory.XFORMS_NODE, resultDoc); } catch (TransformerConfigurationException e) { e.printStackTrace(); throw new ServletException(e); } catch (TransformerFactoryConfigurationError e) { e.printStackTrace(); throw new ServletException(e); } catch (TransformerException e) { e.printStackTrace(); throw new ServletException(e); } }
From source file:com.servicelibre.jxsl.scenario.XslScenario.java
/** * Apply XSL transformation on XML bytes. * //from w ww . ja v a 2s. c o m * @param xmlBytes * @return */ public Map<String, String> apply(byte[] xmlBytes, String systemId) { Map<String, String> xslOutputs = new HashMap<String, String>(1); Transformer transformer = getTransformer(); if (transformer == null) { logger.warn("No transformer available for xslPath {}", xslPath); return xslOutputs; } multipleOutputs.clearResults(); xslOutputs.put(mainOutputKey, ""); // TODO can do better, but as fast? if (xmlBytes.length <= 10) { logger.warn("No enough bytes to apply XSL on..."); return xslOutputs; } try { setTimestamp(df.format(new Date())); logger.debug("Going to execute [{}], on a document of {} bytes", this.xslPath, xmlBytes.length); // Pass parameters to XSL for (String paramName : parameters.keySet()) { logger.debug("Setting up parameter {} to {}", paramName, parameters.get(paramName)); transformer.setParameter(paramName, parameters.get(paramName)); } String xmlSourceFilename = ""; // save XML source if requested if (saveXmlSource) { File xmlSourceFile = saveXmlSourceFile(xmlBytes); if (xmlSourceFile != null) { xmlSourceFilename = xmlSourceFile.getAbsolutePath(); } } InputSource inputSource = new InputSource(new ByteArrayInputStream(xmlBytes)); // To prevent error such FORG0002 (Base URI {} is not an absolute // URI), etc. inputSource.setSystemId(systemId); SAXSource saxSource = new SAXSource(reader, inputSource); StringWriter xslMainStringOutput = new StringWriter(); logger.debug("Start execution of [{}]", this.xslPath); Date startDate = new Date(); long startTime = System.nanoTime(); transformer.transform(saxSource, new StreamResult(xslMainStringOutput)); long executionTime = System.nanoTime() - startTime; logger.debug("Stop execution of [{}] ({}ms)", this.xslPath, (double) executionTime / 1000000); executionCount++; // Add main result output logger.debug("Storing main output (key={})", mainOutputKey); xslOutputs.put(mainOutputKey, xslMainStringOutput.toString()); // Add potential other result outputs Map<String, StringWriter> outputs = multipleOutputs.getOutputs(); for (String outputName : outputs.keySet()) { logger.debug("Storing additional output (key={})", outputName); xslOutputs.put(outputName, outputs.get(outputName).toString()); } setLastRunReport(createRunReport(xmlSourceFilename, xslOutputs, startDate, executionTime)); } catch (TransformerConfigurationException e) { logger.error("Error during XSL transformation.", e); } catch (TransformerException e) { logger.error("Error during XSL transformation.", e); } catch (IllegalArgumentException e) { logger.error("Error during XSL transformation.", e); } return xslOutputs; }
From source file:at.ac.tuwien.auto.iotsys.gateway.connectors.knx.KNXDeviceLoaderETSImpl.java
public ArrayList<Connector> initDevices(ObjectBroker objectBroker) { log.info("KNX ETS device loader starting. - connectorsConfig: " + connectorsConfig); setConfiguration(connectorsConfig);// w ww. j a va 2 s . c o m ArrayList<Connector> connectors = new ArrayList<Connector>(); log.info("connectors config now: " + connectorsConfig); Object knxConnectors = connectorsConfig.getProperty("knx-ets.connector.name"); int connectorsSize = 0; if (knxConnectors != null) { connectorsSize = 1; } if (knxConnectors instanceof Collection<?>) { connectorsSize = ((Collection<?>) knxConnectors).size(); } // Networks List networks = new List(); networks.setName("networks"); networks.setOf(new Contract(Network.CONTRACT)); networks.setHref(new Uri("/networks")); boolean networkEnabled = false; for (int connector = 0; connector < connectorsSize; connector++) { HierarchicalConfiguration subConfig = connectorsConfig .configurationAt("knx-ets.connector(" + connector + ")"); // String connectorName = subConfig.getString("name"); String routerIP = subConfig.getString("router.ip"); int routerPort = subConfig.getInteger("router.port", 3671); String localIP = subConfig.getString("localIP"); Boolean enabled = subConfig.getBoolean("enabled", false); Boolean forceRefresh = subConfig.getBoolean("forceRefresh", false); String knxProj = subConfig.getString("knx-proj"); Boolean enableGroupComm = subConfig.getBoolean("groupCommEnabled", false); Boolean enableHistories = subConfig.getBoolean("historyEnabled", false); if (enabled) { if (!networkEnabled) { objectBroker.addObj(networks, true); networkEnabled = true; } File file = new File(knxProj); if (!file.exists() || file.isDirectory() || !file.getName().endsWith(".knxproj") || file.getName().length() < 8) { log.warning("KNX project file " + knxProj + " is not a valid KNX project file."); continue; } String projDirName = knxProj.substring(0, knxProj.length() - 8); File projDir = new File(projDirName); if (!projDir.exists() || forceRefresh) { log.info("Expanding " + knxProj + " into directory " + projDirName); unZip(knxProj, projDirName); } String directory = "./" + knxProj.substring(knxProj.indexOf("/") + 1).replaceFirst(".knxproj", ""); // now the unpacked ETS project should be available in the directory String transformFileName = knxProj.replaceFirst(".knxproj", "") + "/" + file.getName().replaceFirst(".knxproj", "") + ".xml"; File transformFile = new File(transformFileName); if (!transformFile.exists() || forceRefresh) { log.info("Transforming ETS configuration."); // System.setProperty("javax.xml.transform.TransformerFactory", "net.sf.saxon.TransformerFactoryImpl"); // Create a transform factory instance. TransformerFactory tfactory = TransformerFactory.newInstance(); // Create a transformer for the stylesheet. Transformer transformer; try { transformer = tfactory.newTransformer(new StreamSource("knx-config/stylesheet_knx.xsl")); Collection<File> listFiles = FileUtils.listFiles(projDir, FileFilterUtils.nameFileFilter("0.xml"), new IOFileFilter() { @Override public boolean accept(File file) { return true; } @Override public boolean accept(File dir, String name) { return true; } }); if (listFiles.size() != 1) { log.severe("Found no or more than one 0.xml file in " + projDirName); continue; } log.info("Transforming with directory parameter set to " + directory); transformer.setParameter("directory", directory); transformer.transform(new StreamSource(listFiles.iterator().next().getAbsoluteFile()), new StreamResult(transformFileName)); log.info("Transformation completed and result written to: " + transformFileName); } catch (TransformerConfigurationException e) { e.printStackTrace(); } catch (TransformerException e) { e.printStackTrace(); } } try { devicesConfig = new XMLConfiguration(transformFileName); } catch (Exception e) { log.log(Level.SEVERE, e.getMessage(), e); } KNXConnector knxConnector = new KNXConnector(routerIP, routerPort, localIP); connect(knxConnector); initNetworks(knxConnector, objectBroker, networks, enableGroupComm, enableHistories); connectors.add(knxConnector); } } return connectors; }
From source file:com.ephesoft.dcma.ibm.IBMCMExporter.java
/** * This method transforms the batch.xml to another XML acceptable by IBM Content Management. * // w ww. j a v a2 s . c o m * @param batchInstanceID {@link String} * @throws JAXBException root exception class for all JAXB exceptions * @throws DCMAApplicationException if any exception occurs. */ public void exportFiles(final String batchInstanceID) throws JAXBException, DCMAApplicationException { LOGGER.info("IBM Content Management plugin."); LOGGER.info("Initializing properties..."); String ibmCMSwitch = pluginPropertiesService.getPropertyValue(batchInstanceID, IBMCMConstant.IBM_CM_PLUGIN.getId(), IBMCMProperties.IBM_CM_SWITCH); if (IBMCMConstant.ON_STRING.equalsIgnoreCase(ibmCMSwitch)) { updateBatch(batchInstanceID); String exportFolder = pluginPropertiesService.getPropertyValue(batchInstanceID, IBMCMConstant.IBM_CM_PLUGIN.getId(), IBMCMProperties.IBM_CM_EXPORT_FOLDER); int totalDocSize = getTotalDocumentSize(batchInstanceID); if (null == exportFolder || "".equalsIgnoreCase(exportFolder)) { validateExportFolder(); } LOGGER.info("Properties Initialized Successfully"); boolean isZipSwitchOn = batchSchemaService.isZipSwitchOn(); LOGGER.info("Zipped Batch XML switch is:" + isZipSwitchOn); String exportToFolder = batchInstanceService.getSystemFolderForBatchInstanceId(batchInstanceID); String baseDocsFolder = exportToFolder + File.separator + batchInstanceID; boolean isExportFolderCreated = folderCreation(exportFolder); String batchXmlName = batchInstanceID + ICommonConstants.UNDERSCORE_BATCH_XML; String sourceXMLPath = baseDocsFolder + File.separator + batchInstanceID + ICommonConstants.UNDERSCORE_BATCH_XML; Batch batch = batchSchemaService.getBatch(batchInstanceID); String targetXmlPath = null; String batchName = ""; Map<String, String> subPoenaLoanMap = getSubPoenaLoanNumber(batch.getDocuments().getDocument()); if (subPoenaLoanMap.size() == 2) { batchName = validateSubPoenaLoanMap(subPoenaLoanMap); } if ((batch != null && batch.getBatchName() != null && !batch.getBatchName().isEmpty()) || (batchName != null && !batchName.isEmpty())) { targetXmlPath = getTargetFilePath(batchInstanceID, exportFolder, batch, IBMCMConstant.XML_EXTENSION.getId(), batchName); } InputStream xslStream = null; try { xslStream = xslResource.getInputStream(); } catch (IOException e) { throw new DCMAApplicationException("Could not find xsl file in the classpath resource", e); } InputStream inputStream = null; tracingLogs(isExportFolderCreated, sourceXMLPath, targetXmlPath, xslStream); if (targetXmlPath == null) { validateTargetXmlPath(exportFolder); } if (xslStream == null) { validateXslStream(); } if (!isExportFolderCreated) { throw new DCMAApplicationException( "Unable to create directory in " + exportFolder + ". Please verify the permission"); } try { TransformerFactory tFactory = TransformerFactory.newInstance(); Transformer transformer = null; try { transformer = tFactory.newTransformer(new StreamSource(xslStream)); } finally { IOUtils.closeQuietly(xslStream); } if (transformer != null) { String prefixSubpoenaValue = ""; prefixSubpoenaValue = getPrefixSubpoenaValue(prefixSubpoenaValue, batch); String cmodAppGroupLocal = ""; String cmodAppLocal = ""; if (prefixSubpoenaValue.equalsIgnoreCase("FRE")) { cmodAppLocal = "FreddieMac_Loans_PDF"; cmodAppGroupLocal = "FreddieMac_Loans"; } else if (prefixSubpoenaValue.equalsIgnoreCase("FNM")) { cmodAppLocal = "FannieMae_Loans_PDF"; cmodAppGroupLocal = "FannieMae_Loans"; } else { cmodAppGroupLocal = this.cmodAppGroup; cmodAppLocal = this.cmodApp; } parsingParamterToXML(batchInstanceID, transformer, cmodAppGroupLocal, cmodAppLocal); transformer.setParameter(IBMCMConstant.TOTAL_DOCUMENT_SIZE.getId(), totalDocSize); String datFile = getTargetFilePath(batchInstanceID, exportFolder, batch, IBMCMConstant.DAT_EXTENSION.getId(), batchName); transformer.setParameter(IBMCMConstant.DAT_FILE_NAME.getId(), new File(datFile).getName()); transformer.setParameter(IBMCMConstant.SUPLLYING_SYSTEM.getId(), this.getSupplyingSystem()); inputStream = transformIntoXML(isZipSwitchOn, batchXmlName, sourceXMLPath, targetXmlPath, inputStream, transformer); updateDocumentOffsetValue(batchInstanceID, targetXmlPath); } else { LOGGER.error("Transformer is null due to Invalid xsl file."); } } catch (FileNotFoundException e) { throw new DCMAApplicationException( "Error in creating output xml file :" + targetXmlPath + " " + e.getMessage(), e); } catch (TransformerException e1) { throw new DCMAApplicationException( "Could not transform ibmCMTransform.xsl file : " + e1.getMessage(), e1); } catch (IOException ioe) { throw new DCMAApplicationException( "Could not transform ibmCMTransform.xsl file : " + ioe.getMessage(), ioe); } finally { IOUtils.closeQuietly(inputStream); } generateDATFile(batchInstanceID, exportFolder, batch); generateCTLFile(batchInstanceID, exportFolder, batch); } else { LOGGER.info("IBM Content Management Exporter is switched off or null"); } }
From source file:de.betterform.connector.xslt.XSLTSubmissionHandler.java
/** * Serializes and submits the specified instance data over the * <code>xslt</code> protocol. * * @param submission the submission issuing the request. * @param instance the instance data to be serialized and submitted. * @return xslt transformation result.//from w w w .j a va 2s .c o m * @throws XFormsException if any error occurred during submission. */ public Map submit(Submission submission, Node instance) throws XFormsException { try { if (LOGGER.isDebugEnabled()) { LOGGER.debug("uri: " + getURI()); } URI uri = ConnectorHelper.resolve(submission.getContainerObject().getProcessor().getBaseURI(), getURI()); Map parameters = ConnectorHelper.getURLParameters(uri); URI stylesheetURI = ConnectorHelper.removeURLParameters(uri); if (LOGGER.isDebugEnabled()) { LOGGER.debug("stylesheet uri: " + stylesheetURI); } // pass output properties from submission CachingTransformerService transformerService = (CachingTransformerService) getContext() .get(TransformerService.TRANSFORMER_SERVICE); if (transformerService == null) { if (uri.getScheme().equals("http")) { transformerService = new CachingTransformerService(new HttpResourceResolver()); } else if (uri.getScheme().equals("file")) { transformerService = new CachingTransformerService(new FileResourceResolver()); } else { throw new XFormsException( "Protocol " + stylesheetURI.getScheme() + " not supported for XSLT Submission Handler"); } } if (parameters != null && parameters.get("nocache") != null) { transformerService.setNoCache(true); } Transformer transformer = transformerService.getTransformer(stylesheetURI); if (submission.getVersion() != null) { transformer.setOutputProperty(OutputKeys.VERSION, submission.getVersion()); } if (submission.getIndent() != null) { transformer.setOutputProperty(OutputKeys.INDENT, Boolean.TRUE.equals(submission.getIndent()) ? "yes" : "no"); } if (submission.getMediatype() != null) { transformer.setOutputProperty(OutputKeys.MEDIA_TYPE, submission.getMediatype()); } if (submission.getEncoding() != null) { transformer.setOutputProperty(OutputKeys.ENCODING, submission.getEncoding()); } else { transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); } if (submission.getOmitXMLDeclaration() != null) { transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, Boolean.TRUE.equals(submission.getOmitXMLDeclaration()) ? "yes" : "no"); } if (submission.getStandalone() != null) { transformer.setOutputProperty(OutputKeys.STANDALONE, Boolean.TRUE.equals(submission.getStandalone()) ? "yes" : "no"); } if (submission.getCDATASectionElements() != null) { transformer.setOutputProperty(OutputKeys.CDATA_SECTION_ELEMENTS, submission.getCDATASectionElements()); } // pass parameters form uri if any if (parameters != null) { Iterator iterator = parameters.keySet().iterator(); String name; while (iterator.hasNext()) { name = (String) iterator.next(); transformer.setParameter(name, parameters.get(name)); } } // transform instance to byte array ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); long start = System.currentTimeMillis(); DOMSource domSource; //check for 'parse' param String parseParam = null; if (parameters.containsKey("parseString")) { parseParam = (String) parameters.get("parseString"); } if (parseParam != null && parseParam.equalsIgnoreCase("true")) { String xmlString = DOMUtil.getTextNodeAsString(instance); domSource = new DOMSource(DOMUtil.parseString(xmlString, true, false)); } else { domSource = new DOMSource(instance); } transformer.transform(domSource, new StreamResult(outputStream)); long end = System.currentTimeMillis(); if (LOGGER.isDebugEnabled()) { LOGGER.debug("transformation time: " + (end - start) + " ms"); } // create input stream from result InputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray()); Map response = new HashMap(); response.put(XFormsProcessor.SUBMISSION_RESPONSE_STREAM, inputStream); return response; } catch (Exception e) { throw new XFormsException(e); } }
From source file:com.amalto.core.plugin.base.xslt.XSLTTransformerPluginBean.java
/** * @throws XtentisException//w w w.j av a2 s . c o m * * @ejb.interface-method view-type = "local" * @ejb.facade-method */ public void execute(TransformerPluginContext context) throws XtentisException { try { // fetch data from context Transformer transformer = (Transformer) context.get(TRANSFORMER); String outputMethod = (String) context.get(OUTPUT_METHOD); TypedContent xmlTC = (TypedContent) context.get(INPUT_XML); // get the charset String charset = Util.extractCharset(xmlTC.getContentType()); // get the xml String String xml = new String(xmlTC.getContentBytes(), charset); // get the xml parameters TypedContent parametersTC = (TypedContent) context.get(INPUT_PARAMETERS); if (parametersTC != null) { String parametersCharset = Util.extractCharset(parametersTC.getContentType()); byte[] parametersBytes = parametersTC.getContentBytes(); if (parametersBytes != null) { String parameters = new String(parametersBytes, parametersCharset); Document parametersDoc = Util.parse(parameters); NodeList paramList = Util.getNodeList(parametersDoc.getDocumentElement(), "//Parameter"); //$NON-NLS-1$ for (int i = 0; i < paramList.getLength(); i++) { String paramName = Util.getFirstTextNode(paramList.item(i), "Name"); //$NON-NLS-1$ String paramValue = Util.getFirstTextNode(paramList.item(i), "Value"); //$NON-NLS-1$ if (paramValue == null) paramValue = ""; //$NON-NLS-1$ if (paramName != null) { transformer.setParameter(paramName, paramValue); } } } } // FIXME: ARRRRGHHHHHH - How do you prevent the Transformer to process doctype instructions? // Sets the current time transformer.setParameter("TIMESTAMP", getTimestamp()); //$NON-NLS-1$ transformer.setErrorListener(new ErrorListener() { public void error(TransformerException exception) throws TransformerException { transformatioError = exception.getMessage(); } public void fatalError(TransformerException exception) throws TransformerException { transformatioError = exception.getMessage(); } public void warning(TransformerException exception) throws TransformerException { transformationeWarning = exception.getMessage(); } }); transformatioError = null; transformationeWarning = null; ByteArrayOutputStream baos = new ByteArrayOutputStream(); if ("xml".equals(outputMethod) || "xhtml".equals(outputMethod)) { //$NON-NLS-1$ //$NON-NLS-2$ DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document document = builder.newDocument(); DOMResult domResult = new DOMResult(document); transformer.transform(new StreamSource(new StringReader(xml)), domResult); if (transformationeWarning != null) { String err = "Warning processing the XSLT: " + transformationeWarning; //$NON-NLS-1$ LOG.warn(err); } if (transformatioError != null) { String err = "Error processing the XSLT: " + transformatioError; //$NON-NLS-1$ LOG.error(err); throw new XtentisException(err); } Node rootNode = document.getDocumentElement(); // process the cross-referencings NodeList xrefl = Util.getNodeList(rootNode.getOwnerDocument(), "//*[@xrefCluster]"); //$NON-NLS-1$ int len = xrefl.getLength(); for (int i = 0; i < len; i++) { Element xrefe = (Element) xrefl.item(i); xrefe = processMappings(xrefe); } TransformerFactory transFactory = new net.sf.saxon.TransformerFactoryImpl(); Transformer serializer = transFactory.newTransformer(); serializer.setOutputProperty(OutputKeys.METHOD, outputMethod); serializer.setOutputProperty(OutputKeys.INDENT, "yes"); //$NON-NLS-1$ serializer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); //$NON-NLS-1$ serializer.transform(new DOMSource(rootNode), new StreamResult(baos)); } else { if (transformationeWarning != null) { String err = "Warning processing the XSLT: " + transformationeWarning; //$NON-NLS-1$ LOG.warn(err); } if (transformatioError != null) { String err = "Error processing the XSLT: " + transformatioError; //$NON-NLS-1$ LOG.error(err); throw new XtentisException(err); } // transform the item transformer.transform(new StreamSource(new StringReader(xml)), new StreamResult(baos)); } // Call Back byte[] bytes = baos.toByteArray(); if (LOG.isDebugEnabled()) { LOG.debug("execute() Inserting XSL Result in '" + OUTPUT_TEXT + "'\n" + new String(bytes, "utf-8")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } context.put(OUTPUT_TEXT, new TypedContent(bytes, ("xhtml".equals(outputMethod) ? "application/xhtml+xml" //$NON-NLS-1$//$NON-NLS-2$ : "text/" //$NON-NLS-1$ + outputMethod) + "; charset=utf-8")); //$NON-NLS-1$ context.getPluginCallBack().contentIsReady(context); } catch (Exception e) { String err = "Could not start the XSLT plugin"; //$NON-NLS-1$ LOG.error(err, e); throw new XtentisException(err); } }
From source file:de.interactive_instruments.ShapeChange.Target.FeatureCatalogue.FeatureCatalogue.java
private void fopWrite(String xmlName, String xslfofileName, String outfileName, String outputMimetype) { Properties outputFormat = OutputPropertiesFactory.getDefaultMethodProperties("xml"); outputFormat.setProperty("indent", "yes"); outputFormat.setProperty("{http://xml.apache.org/xalan}indent-amount", "2"); outputFormat.setProperty("encoding", encoding); // redirect FOP-logging to our system, Level 'Warning' by default Logger fl = Logger.getLogger("org.apache.fop"); fl.setLevel(Level.WARNING);//from ww w .ja va 2 s.c o m FopMsgHandler fmh = new FopMsgHandler(result, this); fl.addHandler(fmh); try { // configure fopFactory as desired FopFactory fopFactory = FopFactory.newInstance(); FOUserAgent foUserAgent = fopFactory.newFOUserAgent(); // configure foUserAgent as desired boolean skip = false; // Setup directories File outDir = new File(outputDirectory); // Setup input and output files File xmlFile = new File(outDir, xmlName); File xsltFile = new File(xsltPath, xslfofileName); File outFile = new File(outDir, outfileName); if (!xmlFile.canRead()) { result.addError(null, 301, xmlFile.getName(), outfileName); skip = true; } if (!xsltFile.canRead()) { result.addError(null, 301, xsltFile.getName(), outfileName); skip = true; } if (skip == false) { // Setup output OutputStream out = null; try { out = new java.io.FileOutputStream(outFile); out = new java.io.BufferedOutputStream(out); } catch (Exception e) { result.addError(null, 304, outFile.getName(), e.getMessage()); skip = true; } if (skip == false) { try { // Construct fop with desired output format Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, foUserAgent, out); // Setup XSLT if (xslTransformerFactory != null) { // use TransformerFactory specified in configuration System.setProperty("javax.xml.transform.TransformerFactory", xslTransformerFactory); } else { // use TransformerFactory determined by system } TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer = factory.newTransformer(new StreamSource(xsltFile)); FopErrorListener el = new FopErrorListener(xmlFile.getName(), result, this); transformer.setErrorListener(el); // Set the value of a <param> in the stylesheet transformer.setParameter("versionParam", "2.0"); // Setup input for XSLT transformation Source src = new StreamSource(xmlFile); // 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); } catch (Exception e) { result.addError(null, 304, outfileName, e.getMessage()); skip = true; } finally { out.close(); result.addResult(getTargetID(), outputDirectory, outfileName, null); if (deleteXmlFile) xmlFile.delete(); } } } } catch (Exception e) { String m = e.getMessage(); if (m != null) { result.addError(m); } e.printStackTrace(System.err); } }
From source file:ddf.catalog.services.xsltlistener.XsltMetacardTransformer.java
@Override public BinaryContent transform(Metacard metacard, Map<String, Serializable> arguments) throws CatalogTransformerException { LOGGER.debug("Entering metacard xslt transform."); Transformer transformer; Map<String, Object> mergedMap = new HashMap<String, Object>(localMap); if (arguments != null) { mergedMap.putAll(arguments);/*from ww w . ja v a 2 s. c om*/ } // adding metacard data not in document mergedMap.put("id", getValueOrEmptyString(metacard.getId())); mergedMap.put("siteName", getValueOrEmptyString(metacard.getSourceId())); mergedMap.put("title", getValueOrEmptyString(metacard.getTitle())); mergedMap.put("type", getValueOrEmptyString(metacard.getMetacardType())); mergedMap.put("date", getValueOrEmptyString(metacard.getCreatedDate())); mergedMap.put("product", getValueOrEmptyString(metacard.getResourceURI())); mergedMap.put("thumbnail", getValueOrEmptyString(metacard.getThumbnail())); mergedMap.put("geometry", getValueOrEmptyString(metacard.getLocation())); ServiceReference[] refs = null; try { LOGGER.debug("Searching for other Metacard Transformers."); // TODO INJECT THESE!!! refs = context.getServiceReferences(MetacardTransformer.class.getName(), null); } catch (InvalidSyntaxException e) { // can't happen because filter is null } if (refs != null) { List<String> serviceList = new ArrayList<String>(); LOGGER.debug("Found other Metacard transformers, adding them to a service reference list."); for (ServiceReference ref : refs) { if (ref != null) { String title = null; String shortName = (String) ref.getProperty(Constants.SERVICE_SHORTNAME); if ((title = (String) ref.getProperty(Constants.SERVICE_TITLE)) == null) { title = "View as " + shortName.toUpperCase(); } String url = "/services/catalog/" + metacard.getId() + "?transform=" + shortName; // define the services serviceList.add(title); serviceList.add(url); } } mergedMap.put("services", serviceList); } else { LOGGER.debug("No other Metacard transformers were found."); } // TODO: maybe add updated, type, and uuid here? // map.put("updated", fmt.print(result.getPostedDate().getTime())); // map.put("type", card.getSingleType().getValue()); BinaryContent resultContent; StreamResult resultOutput = null; Source source = new StreamSource( new ByteArrayInputStream(metacard.getMetadata().getBytes(StandardCharsets.UTF_8))); ByteArrayOutputStream baos = new ByteArrayOutputStream(); resultOutput = new StreamResult(baos); try { transformer = templates.newTransformer(); } catch (TransformerConfigurationException tce) { throw new CatalogTransformerException("Could not perform Xslt transform: " + tce.getException(), tce.getCause()); } if (!mergedMap.isEmpty()) { for (Map.Entry<String, Object> entry : mergedMap.entrySet()) { LOGGER.debug("Adding parameter to transform {}:{}", entry.getKey(), entry.getValue()); transformer.setParameter(entry.getKey(), entry.getValue()); } } try { transformer.transform(source, resultOutput); byte[] bytes = baos.toByteArray(); IOUtils.closeQuietly(baos); LOGGER.debug("Transform complete."); resultContent = new XsltTransformedContent(bytes, mimeType); } catch (TransformerException te) { throw new CatalogTransformerException("Could not perform Xslt transform: " + te.getMessage(), te.getCause()); } finally { // TODO: if we ever start to reuse transformers, we should add this // code back in // transformer.reset(); } return resultContent; }
From source file:edu.ucsd.library.dams.api.DAMSAPIServlet.java
public String xslt(String xml, Transformer t, Map<String, String[]> params, String queryString) throws TransformerException { if (xml == null) { throw new TransformerException("No input document provided"); }/*from w ww . ja v a 2s . com*/ if (t == null) { throw new TransformerException("Null transform"); } // params String casGroupTest = getParamString(params, "casGroupTest", null); // clear stale parameters t.clearParameters(); // add request params to xsl if (params != null) { Iterator<String> it = params.keySet().iterator(); while (it.hasNext()) { String key = it.next(); String val = null; String[] vals = (String[]) params.get(key); for (int i = 0; i < vals.length; i++) { if (vals[i] != null && !vals[i].equals("")) { if (val == null) { val = vals[i]; } else { val += "; " + vals[i]; } } } if (key != null && val != null) { String escaped = StringEscapeUtils.escapeJava(val); t.setParameter(key, escaped); } } } if (queryString != null) { t.setParameter("queryString", StringEscapeUtils.escapeJava(queryString)); } if (casGroupTest != null) { t.setParameter("casTest", casGroupTest); } StringWriter sw = new StringWriter(); t.transform(new StreamSource(new StringReader(xml)), new StreamResult(sw)); return sw.toString(); }
From source file:com.seajas.search.contender.service.modifier.ArchiveModifierService.java
/** * Handle the given archive's content by sending each entry to the given handler. * /*w ww . ja v a2 s.co m*/ * @param archive * @param handler * @throws Exception */ public void handleArchive(final Archive archive, final ArchiveResultHandler handler) throws Exception { // Create a validating SAX parser final SAXParserFactory parserFactory = SAXParserFactory.newInstance(); parserFactory.setValidating(true); parserFactory.setNamespaceAware(true); // Create a common transformer per thread Transformer transformer = null; try { transformer = transformerCache.getTransformer(archive.getId(), "archive", archive.getModificationDate()); if (transformer == null) transformer = transformerCache.putContent(archive.getId(), "archive", archive.getModificationDate(), archive.getTransformerContent()); } catch (TransformerConfigurationException e) { logger.error("Unable to generate a (cached) transformer from the given content", e); return; } catch (TransformerFactoryConfigurationError e) { logger.error("Unable to generate a (cached) transformer from the given content", e); return; } // Store and process the files try { Map<File, String> storedResults = storeAndDecompressFiles(archive); List<String> deletedLinks = new ArrayList<String>(); // Only process deletes when a deletion expression has been provided if (StringUtils.hasText(archive.getDeletionExpression())) { // Process all entries beforehand, so to exclude deletes from the final result for (Map.Entry<File, String> storedResult : storedResults.entrySet()) { File storedResultsFolder = storedResult.getKey(); for (File entryLocation : storedResultsFolder.listFiles()) if (entryLocation.getName().matches(archive.getDeletionExpression())) { String deleteLink = entryLocation.getName().replaceAll(archive.getDeletionExpression(), archive.getInternalLink()); deletedLinks.add(deleteLink); // Delete the actual link cacheService .addDeleted(new CacheService.DeletedEntry(archive.getCollection(), deleteLink)); } } } // Now process the stored results themselves for (Map.Entry<File, String> storedResult : storedResults.entrySet()) { File storedResultsFolder = storedResult.getKey(); // Create the descriptions folder if it doesn't already exist File descriptionsFolderLocation = new File(storedResultsFolder, "descriptions"); if (!descriptionsFolderLocation.exists()) descriptionsFolderLocation.mkdirs(); for (File entryLocation : storedResultsFolder.listFiles()) { if (entryLocation.isDirectory()) { if (!entryLocation.getName().equals("descriptions")) logger.warn("Unknown folder '" + entryLocation.getName() + "'found in decompressed archive folder '" + storedResultsFolder.getAbsolutePath() + "'"); continue; } else if (StringUtils.hasText(archive.getDeletionExpression()) && entryLocation.getName().matches(archive.getDeletionExpression())) continue; InputStream transformationInputStream = null; try { transformationInputStream = new BufferedInputStream(new FileInputStream(entryLocation)); // Now determine the content type and create a reader in case of structured content MediaType entryMediaType = autoDetectParser.getDetector().detect(transformationInputStream, new Metadata()); if (!(entryMediaType.getSubtype().equals("xml") || entryMediaType.getSubtype().endsWith("+xml"))) { logger.warn("Archive entry " + entryLocation.getAbsolutePath() + " contains " + entryMediaType + " data which is unstructured, ignoring"); continue; } } catch (IOException e) { logger.error("Could not close input stream during archive processing", e); if (transformationInputStream != null) transformationInputStream.close(); continue; } // Process it as (semi-)structured content XmlReader transformationReader = new XmlReader(transformationInputStream, true); StringWriter transformationWriter = new StringWriter(); try { transformer.setOutputProperty(OutputKeys.ENCODING, "UTF8"); // Use a SAX reader for entity resolution XMLReader xmlReader = parserFactory.newSAXParser().getXMLReader(); InputSource inputSource = new InputSource(transformationReader); xmlReader.setEntityResolver(transformerCache.getEntityResolver()); inputSource.setSystemId("file://" + transformerCache.getDtdImportPath() + "/template.xsl"); // Perform the actual transformation transformer.setParameter("substituteUrl", archive.getInternalLink()); transformer.transform(new SAXSource(xmlReader, inputSource), new StreamResult(transformationWriter)); } catch (TransformerException e) { logger.error("Unable to perform content transformation for entry " + entryLocation.getAbsolutePath()); continue; } catch (SAXException e) { logger.error("Unable to perform content transformation for entry " + entryLocation.getAbsolutePath()); continue; } catch (ParserConfigurationException e) { logger.error("Unable to perform content transformation for entry " + entryLocation.getAbsolutePath()); continue; } finally { transformationInputStream.close(); transformationReader.close(); } // Create a syndication feed from the given result String resultContent = transformationWriter.toString(); SyndFeed resultFeed = null; try { SyndFeedInput feedInput = new SyndFeedInput(); resultFeed = feedInput.build(new StringReader(resultContent)); } catch (FeedException e) { logger.error("Could not parse the feed resulting from the archive entry transformation"); continue; } finally { transformationWriter.close(); } // Write the <description> content to a separate file and add it as an <enclosure> if (resultFeed.getEntries().size() > 0) { Integer entryNumber = 0; for (SyndEntry feedEntry : (Collection<SyndEntry>) resultFeed.getEntries()) { if (!deletedLinks.contains(feedEntry.getLink())) { String description = feedEntry.getDescription().getValue().trim(); File descriptionLocation = new File(descriptionsFolderLocation, stripExtension(entryLocation.getName()) + "-" + entryNumber++ + (feedEntry.getDescription().getType().equals("text/html") ? ".html" : ".xml")); Writer descriptionWriter = new OutputStreamWriter( new FileOutputStream(descriptionLocation), "UTF-8"); if (!description.endsWith("</html>")) descriptionWriter.write("<html>\n<head>\n\t<title>" + feedEntry.getTitle() + "</title>\n</head>\n<body>\n"); descriptionWriter.write(description); if (!description.endsWith("</html>")) descriptionWriter.write("\n</body>\n</html>"); descriptionWriter.flush(); descriptionWriter.close(); // Remove the link from the processed cache should it already be in there, taking care of updates cacheService.deleteElement(feedEntry.getLink()); // Then offer it up to the handler if (logger.isDebugEnabled()) logger.debug("Adding result content (" + entryNumber + ") for archive entry with path " + entryLocation.getAbsolutePath()); try { // NOTE: The encoding of 'UTF-8' is implied for archive-related files handler.process(new URI(feedEntry.getLink()), archive.getHostname(), feedEntry, resultFeed); } catch (FeedException e) { logger.error(String.format( "Could not offer feed entry with link '%s' - invalid entry", feedEntry.getLink()), e); } catch (URISyntaxException e) { logger.error(String.format( "Could not offer feed entry with link '%s' - invalid link", feedEntry.getLink()), e); } } else logger.info("Skipping over feed entry with link '" + feedEntry.getLink() + "' - marked for deletion"); } } else if (logger.isDebugEnabled()) logger.debug("No entries were found in archive entry with path " + entryLocation.getAbsolutePath()); } logger.info("Finished processing archive with name " + storedResult.getValue()); // Now archive the entry in the cache cacheService.addArchived(storedResult.getValue()); } logger.info("Finishing archive populator thread"); } catch (IOException e) { logger.error("Could not close input stream during archive processing", e); } }