List of usage examples for javax.xml.transform Transformer setParameter
public abstract void setParameter(String name, Object value);
From source file:com.spoledge.audao.generator.GeneratorFlow.java
public void generateDtoImpls() throws IOException, TransformerException { Transformer transformer = getTransformer(ResourceType.DTO_IMPL); if (transformer == null) return;//from w w w . j a va 2s. co m String path = dirName + "dto/" + generator.getTarget().getIdentifier() + '/'; for (String tableName : getTableNames()) { if (hasDto(tableName)) { transformer.setParameter("table_name", tableName); transformer.transform(getSource(), output.addResult(file(path, tableName, "Impl"))); } } }
From source file:com.evolveum.midpoint.util.DOMUtil.java
public static StringBuffer printDom(Node node, boolean indent, boolean omitXmlDeclaration) { StringWriter writer = new StringWriter(); TransformerFactory transfac = TransformerFactory.newInstance(); Transformer trans; try {//from ww w . j a v a2 s. c o m trans = transfac.newTransformer(); } catch (TransformerConfigurationException e) { throw new SystemException("Error in XML configuration: " + e.getMessage(), e); } trans.setOutputProperty(OutputKeys.INDENT, (indent ? "yes" : "no")); trans.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); // XALAN-specific trans.setParameter(OutputKeys.ENCODING, "utf-8"); // Note: serialized XML does not contain xml declaration trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, (omitXmlDeclaration ? "yes" : "no")); DOMSource source = new DOMSource(node); try { trans.transform(source, new StreamResult(writer)); } catch (TransformerException e) { throw new SystemException("Error in XML transformation: " + e.getMessage(), e); } return writer.getBuffer(); }
From source file:de.betterform.xml.xforms.action.LoadAction.java
private Node doIncludes(Node embed, String absoluteURI) { LOGGER.debug("LoadAction.doInclude: Node to embed: " + embed.toString() + " URI: " + absoluteURI); try {/*from ww w . j a va 2 s . co m*/ String uri = absoluteURI.substring(0, absoluteURI.lastIndexOf("/") + 1); CachingTransformerService transformerService = (CachingTransformerService) this.container.getProcessor() .getContext().get(TransformerService.TRANSFORMER_SERVICE); Transformer transformer = transformerService.getTransformerByName("include.xsl"); DOMSource source = new DOMSource(embed); DOMResult result = new DOMResult(); transformer.setParameter("root", uri); transformer.transform(source, result); return result.getNode(); } catch (TransformerException e) { LOGGER.debug("LoadAction.doInclude: TransformerException:", e); } return embed; }
From source file:com.jaspersoft.jasperserver.war.OlapPrint.java
/** Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods. * * @param request servlet request/*from w ww .ja va 2s. co m*/ * @param response servlet response */ protected void processRequest(RequestContext context) throws ServletException, IOException { HttpServletRequest request = context.getRequest(); HttpServletResponse response = context.getResponse(); HttpSession session = request.getSession(); String type = request.getParameter("type"); int identifiedType = -1; boolean xslCache = true; String view = request.getParameter("view"); if (view == null || type == null) { throw new ServletException("view and type parameters not supplied"); } //context.getFileParameters(); OutputStream outStream = response.getOutputStream(); PrintWriter out = null; try { String xslUri = null; if (type.equalsIgnoreCase("XLS")) { xslUri = "/WEB-INF/jpivot/table/xls_mdxtable.xsl"; RendererParameters.setParameter(context.getRequest(), "mode", "excel", "request"); response.setContentType("application/vnd.ms-excel"); filename = "xls_export.xls"; identifiedType = XLS; } else if (type.equalsIgnoreCase("PDF")) { xslUri = "/WEB-INF/jpivot/table/fo_mdxtable.xsl"; RendererParameters.setParameter(context.getRequest(), "mode", "print", "request"); response.setContentType("application/pdf"); filename = "xls_export.pdf"; identifiedType = PDF; } else { throw new ServletException("Unknown file type: " + type); } // Get references to needed elements. We expect them to be in the current // session String tableRef = view + "/table"; String chartRef = view + "/chart"; String printRef = view + "/print"; // get TableComponent TableComponent table = (TableComponent) context.getModelReference(tableRef); // only proceed if table component exists if (table == null) { return; } Map parameters = getPrintParameters(printRef, context); parameters.putAll(getChartParameters(chartRef, request)); //parameters.put("message",table.getReportTitle()); // add "context" and "renderId" to parameter map //parameters.put("renderId", renderId); parameters.put("context", context.getRequest().getContextPath()); // Some FOP-PDF versions require a complete URL, not a path //parameters.put("contextUrl", createContextURLValue(context)); // set up filename for download. response.setHeader("Content-Disposition", "attachment; filename=" + filename); table.setDirty(true); Document document = table.render(context); table.setDirty(true); DOMSource source = new DOMSource(document); Transformer transformer = XmlUtils.getTransformer(session, xslUri, xslCache); for (Iterator it = parameters.keySet().iterator(); it.hasNext();) { String name = (String) it.next(); Object value = parameters.get(name); transformer.setParameter(name, value); } // if this is XLS, then we are done, so output xml file. if (identifiedType == XLS) { logger.debug("Creating XLS"); // Get table rendered as XML that Excel understands StringWriter sw = new StringWriter(); StreamResult result = new StreamResult(sw); //do transform transformer.transform(source, result); sw.flush(); response.setContentLength(sw.toString().length()); out = new PrintWriter(outStream); out.write(sw.toString()); RendererParameters.removeParameter(context.getRequest(), "mode", "excel", "request"); } else { // if this is PDF, then need to generate PDF from the FO xml logger.debug("Creating PDF"); logger.debug(resources.getString("jpivot.PrintServlet.message.encoding", new Object[] { resources.getCharacterEncoding() })); FOUserAgent foUserAgent = fopFactory.newFOUserAgent(); // configure foUserAgent as desired // Construct fop with desired output format Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, foUserAgent, outStream); // 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(source, res); /* ByteArrayInputStream bain = new ByteArrayInputStream(sw.toString() .getBytes(resources.getEncodingProvider().getCharacterEncoding())); ByteArrayOutputStream baout = new ByteArrayOutputStream(16384); // process FO to PDF convertFO2PDF(bain, baout); final byte[] content = baout.toByteArray(); response.setContentLength(content.length); outStream.write(content); */ RendererParameters.removeParameter(context.getRequest(), "mode", "print", "request"); } } catch (Exception e) { logger.error(e); throw new ServletException(e); } finally { //close output streams if (out != null) { try { out.flush(); out.close(); } catch (Exception ex) { } } if (outStream != null) { try { outStream.flush(); outStream.close(); } catch (Exception ex) { } } } }
From source file:edu.unc.lib.dl.ingest.sip.METSPackageSIPProcessor.java
private AIPImpl transformMETS(METSPackageSIP metsPack, Document mets, boolean allowIndexing, DepositRecord record) throws IngestException { AIPImpl aip = new AIPImpl(metsPack.getBatchPrepDir(), record); // count the object divs in METS int num = 0;//w ww .j av a 2 s .c o m try { num = _countObjectsXpath.numberValueOf(mets).intValue(); log.debug("GOT OBJECT COUNT: " + num); } catch (JDOMException e) { throw new IngestException("METS issue: Could not get a good count of divs in the structMap.", e); } if (num < 1) { throw new IngestException("METS issue: The structMap must contain at least one div."); } // generate the right number of PIDs StringBuffer sb = new StringBuffer("<pids>"); for (PID pid : pidGenerator.getNextPIDs(num)) { sb.append("<pid>").append(pid).append("</pid>"); } sb.append("</pids>"); // get a transformer Transformer t = null; try { t = mets2fox.newTransformer(); } catch (TransformerConfigurationException e) { throw new IngestException("There was a problem configuring the transformer.", e); } // set parameters t.setParameter("pids", new StreamSource(new StringReader(sb.toString()))); String allowIndexingParam = "no"; if (allowIndexing) { allowIndexingParam = "yes"; } t.setParameter("allowAnyIndexing", allowIndexingParam); t.setParameter("ownerURI", record.getOwner()); File tempFOXDir = aip.getTempFOXDir(); t.setParameter("output.directory", tempFOXDir.getPath()); if (log.isInfoEnabled()) { log.info(tempFOXDir.getPath()); } Source src = new JDOMSource(mets); JDOMResult result = new JDOMResult(); try { t.transform(src, result); } catch (TransformerException e) { throw new IngestException("METS problem: There were problems transforming METS to FOXML.", e); } if (log.isDebugEnabled()) { log.debug(new XMLOutputter().outputString(result.getDocument())); } // fill the pid2foxml map and top pid Set<PID> topPIDs = new HashSet<PID>(); for (Object child : result.getDocument().getRootElement().getChild("objects").getChildren("object")) { Element e = (Element) child; PID pid = new PID(e.getAttributeValue("PID")); String output = e.getAttributeValue("OUTPUT"); if ("yes".equals(e.getAttributeValue("TOP"))) { Integer designatedOrder = null; Integer sipOrder = null; topPIDs.add(pid); if (e.getAttributeValue("designatedOrder") != null) { try { designatedOrder = new Integer(Integer.parseInt(e.getAttributeValue("designatedOrder"))); } catch (NumberFormatException nfe) { throw new IngestException("METS problem: designatedOrder attribute must be an integer.", nfe); } } if (e.getAttributeValue("sipOrder") != null) { try { sipOrder = new Integer(Integer.parseInt(e.getAttributeValue("sipOrder"))); } catch (NumberFormatException nfe) { throw new IngestException("METS problem: sipOrder attribute must be an integer.", nfe); } } String label = e.getAttributeValue("LABEL"); aip.setContainerPlacement(metsPack.getContainerPID(), pid, designatedOrder, sipOrder, label); } aip.setFOXMLFile(pid, new File(output)); } aip.setTopPIDs(topPIDs); return aip; }
From source file:SubmitResults.java
private File populateRequest(final Main parent, String formStatus, String filePath, HttpPost req, final String changeIdXSLT, ContentType ct, MultipartEntityBuilder entityBuilder, final String newIdent) { File ammendedFile = null;//from w ww. j a v a 2s . co m final File instanceFile = new File(filePath); if (formStatus != null) { System.out.println("Setting form status in header: " + formStatus); req.setHeader("form_status", formStatus); // smap add form_status header } else { System.out.println("Form Status null"); } if (newIdent != null) { // Transform the survey ID try { System.out.println("Transformaing Instance file: " + instanceFile); PipedInputStream in = new PipedInputStream(); final PipedOutputStream outStream = new PipedOutputStream(in); new Thread(new Runnable() { public void run() { try { InputStream xslStream = new ByteArrayInputStream(changeIdXSLT.getBytes("UTF-8")); Transformer transformer = TransformerFactory.newInstance() .newTransformer(new StreamSource(xslStream)); StreamSource source = new StreamSource(instanceFile); StreamResult out = new StreamResult(outStream); transformer.setParameter("surveyId", newIdent); transformer.transform(source, out); outStream.close(); } catch (TransformerConfigurationException e1) { parent.appendToStatus("Error changing ident: " + e1.toString()); } catch (TransformerFactoryConfigurationError e1) { parent.appendToStatus("Error changing ident: " + e1.toString()); } catch (TransformerException e) { parent.appendToStatus("Error changing ident: " + e.toString()); } catch (IOException e) { parent.appendToStatus("Error changing ident: " + e.toString()); } } }).start(); System.out.println("Saving stream to file"); ammendedFile = saveStreamTemp(in); } catch (Exception e) { parent.appendToStatus("Error changing ident: " + e.toString()); } } /* * Add submission file as file body, hence save to temporary file first */ if (newIdent == null) { ct = ContentType.create("text/xml"); entityBuilder.addBinaryBody("xml_submission_file", instanceFile, ct, instanceFile.getPath()); } else { FileBody fb = new FileBody(ammendedFile); entityBuilder.addPart("xml_submission_file", fb); } parent.appendToStatus("Instance file path: " + instanceFile.getPath()); /* * find all files referenced by the survey * Temporarily check to see if the parent directory is "uploadedSurveys". If it is * then we will need to scan the submission file to get the list of attachments to * send. * Alternatively this is a newly submitted survey stored in its own directory just as * surveys are stored on the phone. We can then just add all the surveys that are in * the same directory as the submission file. */ File[] allFiles = instanceFile.getParentFile().listFiles(); // add media files ignoring invisible files and the submission file List<File> files = new ArrayList<File>(); for (File f : allFiles) { String fileName = f.getName(); if (!fileName.startsWith(".") && !fileName.equals(instanceFile.getName())) { // ignore invisible files and instance xml file files.add(f); } } for (int j = 0; j < files.size(); j++) { File f = files.get(j); String fileName = f.getName(); ct = ContentType.create(getContentType(parent, fileName)); FileBody fba = new FileBody(f, ct, fileName); entityBuilder.addPart(fileName, fba); } req.setEntity(entityBuilder.build()); return ammendedFile; }
From source file:eionet.webq.web.controller.WebQProxyDelegation.java
/** * Fetches XML file from given xmlUri and applies XSLT conversion with xsltUri. * The resulting xml is converted to json, if format parameter equals 'json'. * Applies authorisation information to fetch XML request, if it is available through UserFile. * * @param xmlUri remote xml file URI/* w w w. j a v a2 s . c o m*/ * @param fileId WebQ session file ID to be used for applying authorisation info * @param xsltUri remote xslt file URI * @param format optional response format. Only json is supported, default is xml * @param request standard HttpServletRequest * @param response standard HttpServletResponse * @return converted XML content * @throws UnsupportedEncodingException Cannot convert xml to UTF-8 * @throws URISyntaxException xmlUri or xsltUri is incorrect * @throws FileNotAvailableException xml or xslt file is not available * @throws TransformerException error when applying xslt transformation on xml */ @RequestMapping(value = "/proxyXmlWithConversion", method = RequestMethod.GET, produces = "text/html;charset=utf-8") @ResponseBody public byte[] proxyXmlWithConversion(@RequestParam("xmlUri") String xmlUri, @RequestParam(required = false) Integer fileId, @RequestParam("xsltUri") String xsltUri, @RequestParam(required = false) String format, HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException, URISyntaxException, FileNotAvailableException, TransformerException { byte[] xml = null; UserFile file = userFileHelper.getUserFile(fileId, request); if (file != null && ProxyDelegationHelper.isCompanyIdParameterValidForBdrEnvelope(request.getRequestURI(), file.getEnvelope())) { xml = restProxyGetWithAuth(xmlUri, fileId, request).getBytes("UTF-8"); } else { xml = new RestTemplate().getForObject(new URI(xmlUri), byte[].class); } byte[] xslt = new RestTemplate().getForObject(new URI(xsltUri), byte[].class); Source xslSource = new StreamSource(new ByteArrayInputStream(xslt)); ByteArrayOutputStream xmlResultOutputStream = new ByteArrayOutputStream(); try { Transformer transformer = TransformerFactory.newInstance().newTransformer(xslSource); for (Map.Entry<String, String[]> parameter : request.getParameterMap().entrySet()) { if (!parameter.getKey().equals("xmlUri") && !parameter.getKey().equals("fileId") && !parameter.getKey().equals("xsltUri") && !parameter.getKey().equals("format")) { transformer.setParameter(parameter.getKey(), StringUtils.defaultString(parameter.getValue()[0])); } } transformer.transform(new StreamSource(new ByteArrayInputStream(xml)), new StreamResult(xmlResultOutputStream)); } catch (TransformerException e1) { LOGGER.error("Unable to transform xml uri=" + xmlUri + " with stylesheet=" + xsltUri); e1.printStackTrace(); throw e1; } byte[] result; if (StringUtils.isNotEmpty(format) && format.equals("json")) { result = jsonXMLConverter.convertXmlToJson(xmlResultOutputStream.toByteArray()); response.setContentType(String.valueOf(MediaType.APPLICATION_JSON)); } else { result = xmlResultOutputStream.toByteArray(); response.setContentType(String.valueOf(MediaType.APPLICATION_XML)); } LOGGER.info("Converted xml uri=" + xmlUri + " with stylesheet=" + xsltUri); response.setCharacterEncoding("utf-8"); return result; }
From source file:com.netspective.commons.text.Transform.java
public boolean render(Writer writer, ValueContext vc, Source transformSource, Map additionalParams, boolean writeErrors) throws TransformerConfigurationException, TransformerException, IOException { if (source == null && transformSource == null) { if (writeErrors) writer.write("No source attribute provided."); log.error("No source attribute provided for " + this); return false; }/*from w w w . j a va 2 s . c o m*/ if (styleSheet == null) { if (writeErrors) writer.write("No style-sheet attribute provided."); log.error("No style-sheet attribute provided for " + this); return false; } try { Map savedProps = new HashMap(); for (int i = 0; i < systemProperties.size(); i++) { SystemProperty prop = (SystemProperty) systemProperties.get(i); String currentValue = System.getProperty(prop.getName()); if (currentValue != null) savedProps.put(prop.getName(), currentValue); System.setProperty(prop.getName(), prop.getValue().getTextValue(vc)); } TransformerFactory tFactory = TransformerFactory.newInstance(); Transformer transformer = tFactory.newTransformer(getStreamSource(styleSheet, vc, styleSheetIsFile)); for (Iterator i = savedProps.entrySet().iterator(); i.hasNext();) { Map.Entry entry = (Map.Entry) i.next(); System.setProperty((String) entry.getKey(), (String) entry.getValue()); } List params = getParams(); for (int i = 0; i < params.size(); i++) { StyleSheetParameter param = (StyleSheetParameter) params.get(i); transformer.setParameter(param.getName(), param.getValue().getTextValue(vc)); } if (additionalParams != null) { for (Iterator i = additionalParams.entrySet().iterator(); i.hasNext();) { Map.Entry entry = (Map.Entry) i.next(); transformer.setParameter(entry.getKey().toString(), entry.getValue()); } } transformer.transform( transformSource != null ? transformSource : getStreamSource(source, vc, sourceIsFile), new StreamResult(writer)); return true; } catch (TransformerConfigurationException e) { log.error("XSLT error in " + this.getClass().getName(), e); if (writeErrors) { writer.write("<pre>" + TextUtils.getInstance().getStackTrace(e) + "</pre>"); return false; } else throw e; } catch (TransformerException e) { log.error("XSLT error in " + this.getClass().getName(), e); if (writeErrors) { writer.write("<pre>" + TextUtils.getInstance().getStackTrace(e) + "</pre>"); return false; } else throw e; } }
From source file:Transform.java
public static void multiplePages() throws Exception { InputStream isXML = Transform.class.getResourceAsStream(file("manual.xml")); InputStream isXSL = Transform.class.getResourceAsStream("html-pages.xsl"); StreamSource xsl = new StreamSource(isXSL); TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer = factory.newTransformer(xsl); Match manual = $(isXML);/*from w ww . j a v a 2 s.c o m*/ replaceVariables(manual); List<String> ids = manual.find("section").ids(); HashSet<String> uniqueIds = new HashSet<String>(ids); if (ids.size() != uniqueIds.size()) { for (String id : uniqueIds) { ids.remove(id); } throw new Exception("Duplicate section ids found! " + ids); } int blanks = 0, completed = 0; for (Match section : manual.find("section").each()) { Match sections = section.add(section.parents("section")).reverse(); String path = path(StringUtils.join(sections.ids(), "/")); String relativePath = relative(path); String root = root(); File dir = new File(path); dir.mkdirs(); PrintStream stream = System.out; boolean blank = StringUtils.isBlank(section.find("content").text()); if (blank) { blanks++; stream = System.err; } else { completed++; } stream.print("["); stream.print(blank ? " " : "x"); stream.println("] Transforming section " + path); File file = new File(dir, "index.php"); file.delete(); FileOutputStream out = new FileOutputStream(file); Source source = new DOMSource(manual.document()); Result target = new StreamResult(out); transformer.setParameter("sectionID", section.id()); transformer.setParameter("relativePath", relativePath); transformer.setParameter("root", root); transformer.transform(source, target); out.close(); } System.out.println(" Completed sections : " + completed + " / " + (blanks + completed) + " (" + (100 * completed / (blanks + completed)) + "%)"); }
From source file:org.fcrepo.server.access.FedoraAccessServlet.java
public void getObjectProfile(Context context, String PID, Date asOfDateTime, boolean xml, HttpServletRequest request, HttpServletResponse response) throws ServerException { OutputStreamWriter out = null; Date versDateTime = asOfDateTime; ObjectProfile objProfile = null;//w w w . j a v a2 s . c o m PipedWriter pw = null; PipedReader pr = null; try { pw = new PipedWriter(); pr = new PipedReader(pw); objProfile = m_access.getObjectProfile(context, PID, asOfDateTime); if (objProfile != null) { // Object Profile found. // Serialize the ObjectProfile object into XML new ProfileSerializerThread(context, PID, objProfile, versDateTime, pw).start(); if (xml) { // Return results as raw XML response.setContentType(CONTENT_TYPE_XML); // Insures stream read from PipedReader correctly translates // utf-8 // encoded characters to OutputStreamWriter. out = new OutputStreamWriter(response.getOutputStream(), "UTF-8"); char[] buf = new char[BUF]; int len = 0; while ((len = pr.read(buf, 0, BUF)) != -1) { out.write(buf, 0, len); } out.flush(); } else { // Transform results into an html table response.setContentType(CONTENT_TYPE_HTML); out = new OutputStreamWriter(response.getOutputStream(), "UTF-8"); File xslFile = new File(m_server.getHomeDir(), "access/viewObjectProfile.xslt"); Templates template = XmlTransformUtility.getTemplates(xslFile); Transformer transformer = template.newTransformer(); transformer.setParameter("fedora", context.getEnvironmentValue(FEDORA_APP_CONTEXT_NAME)); transformer.transform(new StreamSource(pr), new StreamResult(out)); } out.flush(); } else { throw new GeneralException("No object profile returned"); } } catch (ServerException e) { throw e; } catch (Throwable th) { String message = "Error getting object profile"; logger.error(message, th); throw new GeneralException(message, th); } finally { try { if (pr != null) { pr.close(); } if (out != null) { out.close(); } } catch (Throwable th) { String message = "Error closing output"; logger.error(message, th); throw new StreamIOException(message); } } }