List of usage examples for javax.xml.transform Templates newTransformer
Transformer newTransformer() throws TransformerConfigurationException;
From source file:edu.unc.lib.dl.schematron.SchematronValidator.java
/** * This is the lowest level validation call, which returns an XML validation * report in schematron output format. (see http://purl.oclc.org/dsdl/svrl) * * @param source/*from w w w . j a va 2 s .c o m*/ * XML Source to validate * @param schema * name of the schema to use * @return schematron output document */ public Document validate(Source source, String schema) { // lookup templates object Templates template = templates.get(schema); if (template == null) { throw new Error("Unknown Schematron schema name: " + schema); } // get a transformer Transformer t = null; try { t = template.newTransformer(); } catch (TransformerConfigurationException e) { throw new Error("There was a problem configuring the transformer.", e); } // call the transform JDOMResult svrlRes = new JDOMResult(); try { t.transform(source, svrlRes); } catch (TransformerException e) { throw new Error("There was a problem running Schematron validation XSL.", e); } return svrlRes.getDocument(); }
From source file:org.kuali.mobility.knowledgebase.service.KnowledgeBaseServiceImpl.java
public String getConvertedKnowledgeBaseDocument(String documentId, String templatesCode, Map<String, Object> transformerParameters) { String xml = this.getKnowledgeBaseDocument(documentId); String output = ""; try {/*from ww w .ja v a2 s . c o m*/ Templates templates = this.getXslTemplates(templatesCode); // Templates templates = this.cacheService.findCachedXSLTemplates(templatesCode); Transformer transformer = templates.newTransformer(); for (String key : transformerParameters.keySet()) { transformer.setParameter(key, transformerParameters.get(key)); } ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); transformer.transform(new StreamSource(new ByteArrayInputStream(xml.getBytes())), new StreamResult(byteArrayOutputStream)); output = byteArrayOutputStream.toString(); } catch (Exception e) { LOG.error(e.getMessage(), e); } return output; }
From source file:it.geosolutions.geobatch.task.TaskExecutor.java
private String buildArgument(final Source xmlSource, final InputStream is) throws TransformerException { // XML parsing to setup a command line final TransformerFactory f = TransformerFactory.newInstance(); final StringWriter result = new StringWriter(); final Templates transformation = f.newTemplates(new StreamSource(is)); final Transformer transformer = transformation.newTransformer(); transformer.transform(xmlSource, new StreamResult(result)); final String argument = result.toString().replace("\n", " "); return argument; }
From source file:com.esri.geoportal.commons.csw.client.impl.Client.java
/** * Reads record from the stream//from www .j a v a 2 s .c om * * @param contentStream content stream * @return list of records * @throws IOException if reading records fails * @throws TransformerConfigurationException if creating transformer fails * @throws TransformerException if creating transformer fails * @throws ParserConfigurationException if unable to create XML parser * @throws SAXException if unable to parse content * @throws XPathExpressionException if invalid XPath */ private List<IRecord> readRecords(InputStream contentStream) throws IOException, TransformerConfigurationException, TransformerException, ParserConfigurationException, SAXException, XPathExpressionException { ArrayList<IRecord> records = new ArrayList<>(); // create transformer Templates template = TemplatesManager.getInstance().getTemplate(profile.getResponsexslt()); Transformer transformer = template.newTransformer(); // perform transformation StringWriter writer = new StringWriter(); transformer.transform(new StreamSource(contentStream), new StreamResult(writer)); LOG.trace(String.format("Received records:\n%s", writer.toString())); try (ByteArrayInputStream transformedContentStream = new ByteArrayInputStream( writer.toString().getBytes("UTF-8"))) { // create internal request DOM DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = builderFactory.newDocumentBuilder(); Document resultDom = builder.parse(new InputSource(transformedContentStream)); // create xpath XPathFactory xPathfactory = XPathFactory.newInstance(); XPath xpath = xPathfactory.newXPath(); NodeList recordNodeList = (NodeList) xpath.evaluate("/Records/Record", resultDom, XPathConstants.NODESET); for (int i = 0; i < recordNodeList.getLength(); i++) { Node recordNode = recordNodeList.item(i); String id = (String) xpath.evaluate("ID", recordNode, XPathConstants.STRING); String strModifiedDate = (String) xpath.evaluate("ModifiedDate", recordNode, XPathConstants.STRING); Date modifedDate = parseIsoDate(strModifiedDate); IRecord record = new Record(id, modifedDate); records.add(record); } } return records; }
From source file:net.sf.joost.trax.TransformerFactoryImpl.java
/** * Gets a new Transformer object for transformation. * @param source The <code>Source</code> of the stylesheet. * @return A <code>Transformer</code> object according to the * <code>Templates</code> object. * @throws TransformerConfigurationException */// ww w .j a v a 2 s . c o m public Transformer newTransformer(Source source) throws TransformerConfigurationException { synchronized (reentryGuard) { if (DEBUG) log.debug("get a Transformer-instance"); Templates templates = newTemplates(source); Transformer transformer = templates.newTransformer(); return (transformer); } }
From source file:com.esri.geoportal.commons.csw.client.impl.Client.java
@Override public String readMetadata(String id) throws Exception { LOG.debug(String.format("Executing readMetadata(id=%s)", id)); loadCapabilities();// w w w . jav a2 s. c o m String getRecordByIdUrl = createGetMetadataByIdUrl(capabilites.get_getRecordByIDGetURL(), URLEncoder.encode(id, "UTF-8")); HttpGet getMethod = new HttpGet(getRecordByIdUrl); getMethod.setConfig(DEFAULT_REQUEST_CONFIG); try (CloseableHttpResponse httpResponse = httpClient.execute(getMethod); InputStream responseStream = httpResponse.getEntity().getContent();) { if (httpResponse.getStatusLine().getStatusCode() >= 400) { throw new HttpResponseException(httpResponse.getStatusLine().getStatusCode(), httpResponse.getStatusLine().getReasonPhrase()); } String response = IOUtils.toString(responseStream, "UTF-8"); if (CONFIG_FOLDER_PATH.equals(profile.getMetadataxslt())) { return response; } // create transformer Templates template = TemplatesManager.getInstance().getTemplate(profile.getMetadataxslt()); Transformer transformer = template.newTransformer(); try (ByteArrayInputStream contentStream = new ByteArrayInputStream(response.getBytes("UTF-8"));) { // perform transformation StringWriter writer = new StringWriter(); transformer.transform(new StreamSource(contentStream), new StreamResult(writer)); String intermediateResult = writer.toString(); // select url to get meta data DcList lstDctReferences = new DcList(intermediateResult); String xmlUrl = lstDctReferences.stream() .filter(v -> v.getValue().toLowerCase().endsWith(".xml") || v.getScheme().equals(SCHEME_METADATA_DOCUMENT)) .map(v -> v.getValue()).findFirst().orElse(""); // use URL to get meta data if (!xmlUrl.isEmpty()) { HttpGet getRequest = new HttpGet(xmlUrl); try (CloseableHttpResponse httpResp = httpClient.execute(getRequest); InputStream metadataStream = httpResp.getEntity().getContent();) { return IOUtils.toString(metadataStream, "UTF-8"); } } if (!intermediateResult.isEmpty()) { try { Transformer tr = TransformerFactory.newInstance().newTransformer(); tr.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); tr.setOutputProperty(OutputKeys.INDENT, "yes"); ByteArrayInputStream intermediateStream = new ByteArrayInputStream( intermediateResult.getBytes("UTF-8")); StringWriter intermediateBuffer = new StringWriter(); tr.transform(new StreamSource(intermediateStream), new StreamResult(intermediateBuffer)); return intermediateBuffer.toString(); } catch (Exception ex) { return makeResourceFromCswResponse(response, id); } } return response; } } }
From source file:org.ambraproject.admin.service.impl.DocumentManagementServiceImpl.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 . jav a 2 s. c om*/ */ private Transformer getTranslet(Document doc) throws TransformerException { Transformer transformer; StreamSource templateStream = null; String templateName; try { String key = doc.getDocumentElement().getAttribute("dtd-version").trim(); if ((doc == null) || (!xslTemplateMap.containsKey(key)) || (key.equalsIgnoreCase(""))) { templateStream = getAsStream(xslDefaultTemplate); } else { templateName = xslTemplateMap.get(key); templateStream = getAsStream(templateName); } } catch (Exception e) { log.error("XmlTransform not found", e); } final TransformerFactory tFactory = TransformerFactory.newInstance(); Templates translet = tFactory.newTemplates(templateStream); transformer = translet.newTransformer(); return transformer; }
From source file:com.esri.geoportal.commons.csw.client.impl.Client.java
/** * Creates get records request body.// ww w. j a v a2 s . c o m * * @param criteria criteria * @return POST body * @throws IOException if IO operation fails * @throws ParserConfigurationException if unable to create XML parser * @throws SAXException if unable to parse content * @throws TransformerConfigurationException if unable to create transformer * @throws TransformerException if error transforming data */ private String createGetRecordsRequest(ICriteria criteria) throws IOException, ParserConfigurationException, SAXException, TransformerConfigurationException, TransformerException { String internalRequestXml = createInternalXmlRequest(criteria); // create transformer Templates template = TemplatesManager.getInstance() .getTemplate(Constants.CONFIG_FOLDER_PATH + "/" + profile.getGetRecordsReqXslt()); Transformer transformer = template.newTransformer(); try (ByteArrayInputStream internalRequestInputStream = new ByteArrayInputStream( internalRequestXml.getBytes("UTF-8"));) { // create internal request DOM DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = builderFactory.newDocumentBuilder(); Document internalRequestDOM = builder.parse(new InputSource(internalRequestInputStream)); // perform transformation StringWriter writer = new StringWriter(); transformer.transform(new DOMSource(internalRequestDOM), new StreamResult(writer)); return writer.toString(); } }
From source file:be.ibridge.kettle.job.entry.xslt.JobEntryXSLT.java
public Result execute(Result prev_result, int nr, Repository rep, Job parentJob) { LogWriter log = LogWriter.getInstance(); Result result = new Result(nr); result.setResult(false);/* ww w.ja v a2 s . c o m*/ String realxmlfilename = getRealxmlfilename(); String realxslfilename = getRealxslfilename(); String realoutputfilename = getRealoutputfilename(); FileObject xmlfile = null; FileObject xlsfile = null; FileObject outputfile = null; try { if (xmlfilename != null && xslfilename != null && outputfilename != null) { xmlfile = KettleVFS.getFileObject(realxmlfilename); xlsfile = KettleVFS.getFileObject(realxslfilename); outputfile = KettleVFS.getFileObject(realoutputfilename); if (xmlfile.exists() && xlsfile.exists()) { if (outputfile.exists() && iffileexists == 2) { //Output file exists // User want to fail log.logError(toString(), Messages.getString("JobEntryXSLT.OuputFileExists1.Label") + realoutputfilename + Messages.getString("JobEntryXSLT.OuputFileExists2.Label")); result.setResult(false); result.setNrErrors(1); } else if (outputfile.exists() && iffileexists == 1) { // Do nothing log.logDebug(toString(), Messages.getString("JobEntryXSLT.OuputFileExists1.Label") + realoutputfilename + Messages.getString("JobEntryXSLT.OuputFileExists2.Label")); result.setResult(true); } else { if (outputfile.exists() && iffileexists == 0) { // the zip file exists and user want to create new one with unique name //Format Date DateFormat dateFormat = new SimpleDateFormat("mmddyyyy_hhmmss"); // Try to clean filename (without wildcard) String wildcard = realoutputfilename.substring(realoutputfilename.length() - 4, realoutputfilename.length()); if (wildcard.substring(0, 1).equals(".")) { // Find wildcard realoutputfilename = realoutputfilename.substring(0, realoutputfilename.length() - 4) + "_" + dateFormat.format(new Date()) + wildcard; } else { // did not find wilcard realoutputfilename = realoutputfilename + "_" + dateFormat.format(new Date()); } log.logDebug(toString(), Messages.getString("JobEntryXSLT.OuputFileExists1.Label") + realoutputfilename + Messages.getString("JobEntryXSLT.OuputFileExists2.Label")); log.logDebug(toString(), Messages.getString("JobEntryXSLT.OuputFileNameChange1.Label") + realoutputfilename + Messages.getString("JobEntryXSLT.OuputFileNameChange2.Label")); } //String xmlSystemXML = new File(realxmlfilename).toURL().toExternalForm( ); //String xsltSystemXSL = new File(realxslfilename).toURL().toExternalForm( ); // Create transformer factory TransformerFactory factory = TransformerFactory.newInstance(); // Use the factory to create a template containing the xsl file Templates template = factory .newTemplates(new StreamSource(new FileInputStream(realxslfilename))); // Use the template to create a transformer Transformer xformer = template.newTransformer(); // Prepare the input and output files Source source = new StreamSource(new FileInputStream(realxmlfilename)); StreamResult resultat = new StreamResult(new FileOutputStream(realoutputfilename)); // Apply the xsl file to the source file and write the result to the output file xformer.transform(source, resultat); // Everything is OK result.setResult(true); } } else { if (!xmlfile.exists()) { log.logError(toString(), Messages.getString("JobEntryXSLT.FileDoesNotExist1.Label") + realxmlfilename + Messages.getString("JobEntryXSLT.FileDoesNotExist2.Label")); } if (!xlsfile.exists()) { log.logError(toString(), Messages.getString("JobEntryXSLT.FileDoesNotExist1.Label") + realxslfilename + Messages.getString("JobEntryXSLT.FileDoesNotExist2.Label")); } result.setResult(false); result.setNrErrors(1); } } else { log.logError(toString(), Messages.getString("JobEntryXSLT.AllFilesNotNull.Label")); result.setResult(false); result.setNrErrors(1); } } catch (Exception e) { log.logError(toString(), Messages.getString("JobEntryXSLT.ErrorXLST.Label") + Messages.getString("JobEntryXSLT.ErrorXLSTXML1.Label") + realxmlfilename + Messages.getString("JobEntryXSLT.ErrorXLSTXML2.Label") + Messages.getString("JobEntryXSLT.ErrorXLSTXSL1.Label") + realxslfilename + Messages.getString("JobEntryXSLT.ErrorXLSTXSL2.Label") + e.getMessage()); result.setResult(false); result.setNrErrors(1); } finally { try { if (xmlfile != null) xmlfile.close(); if (xlsfile != null) xlsfile.close(); if (outputfile != null) outputfile.close(); } catch (IOException e) { } } return result; }
From source file:com.spoledge.audao.generator.GeneratorFlow.java
private Transformer getTransformer(String resourceKey) { try {//from w w w . ja v a 2s . com TemplatesCache tc = generator.getTemplatesCache(); Templates templates = tc.getTemplates(resourceKey); if (templates == null) { InputStream is = getClass().getResourceAsStream(resourceKey); templates = tc.getTemplates(resourceKey, new StreamSource(is, resourceKey)); } Transformer ret = templates.newTransformer(); ret.setURIResolver(generator.getResourceURIResolver()); // not auto copied from TrFactory ret.setErrorListener(this); ret.setParameter("pkg_db", pkgName); return ret; } catch (TransformerConfigurationException e) { throw new RuntimeException(e); } }