List of usage examples for javax.xml.transform.stream StreamSource StreamSource
public StreamSource(File f)
From source file:com.healthcit.cacure.web.controller.ModuleImportExportController.java
@RequestMapping(method = RequestMethod.GET) public void exportModule(@RequestParam(value = "moduleId", required = true) long id, @RequestParam(value = "format", required = true) String format, HttpServletResponse response) { try {/*from w ww. j av a 2 s.c o m*/ response.setContentType("text/xml"); OutputStream oStream = response.getOutputStream(); Cure cureXml = dataExporter.constructModuleXML(id); JAXBContext jc = JAXBContext.newInstance("com.healthcit.cacure.export.model"); if (ExportFormat.XML.name().equals(format)) { String fileNameHeader = String.format("attachment; filename=form-%d.xml;", id); response.setHeader("Content-Disposition", fileNameHeader); Marshaller m = jc.createMarshaller(); m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); m.marshal(cureXml, oStream); } else if (ExportFormat.EXCEL.name().equals(format)) { String fileNameHeader = String.format("attachment; filename=form-%d.xlxml;", id); response.setHeader("Content-Disposition", fileNameHeader); response.setContentType("application/xml"); StreamSource xslSource = new StreamSource(this.getClass().getClassLoader() .getResourceAsStream(AppConfig.getString(Constants.EXPORT_EXCEL_XSLT_FILE))); JAXBSource xmlSource = new JAXBSource(jc, cureXml); Transformer transformer = TransformerFactory.newInstance().newTransformer(xslSource); transformer.transform(xmlSource, new StreamResult(oStream)); } oStream.flush(); } catch (IOException e) { log.error("Unable to obtain output stream from the response"); log.error(e.getMessage(), e); } catch (JAXBException e) { log.error("Unable to marshal the object"); log.error(e.getMessage(), e); } catch (TransformerException e) { log.error("XSLT transformation failed"); log.error(e.getMessage(), e); } }
From source file:com.quangphuong.crawler.util.XMLUtil.java
public ByteArrayOutputStream convertToPDF(String xmlPath, String xsltInputPath, String pdfOutputPath) throws IOException { File xsltFile = new File(rootPath, xsltInputPath); StreamSource xmlSource = new StreamSource(new File(rootPath, xmlPath)); FopFactory fopFactory = FopFactory.newInstance(new File(".").toURI()); FOUserAgent foUserAgent = fopFactory.newFOUserAgent(); ByteArrayOutputStream out = null; try {/*w ww.j a v a 2 s . c o m*/ out = new ByteArrayOutputStream(); Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, foUserAgent, out); TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer = factory.newTransformer(new StreamSource(xsltFile)); Result res = new SAXResult(fop.getDefaultHandler()); transformer.transform(xmlSource, res); } catch (Exception e) { e.printStackTrace(); } return out; }
From source file:io.mapzone.controller.catalog.csw.CswResponse.java
protected <T> T readObject(InputStream in, Class<T> type) throws JAXBException { Unmarshaller unmarshaller = jaxbContext.get().createUnmarshaller(); JAXBElement<T> elm = unmarshaller.unmarshal(new StreamSource(in), type); return elm.getValue(); }
From source file:io.onedecision.engine.decisions.model.dmn.validators.SchemaValidator.java
public void validate(InputStream obj, Errors errors) { InputStream is = (InputStream) obj; SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); schemaFactory.setResourceResolver(new LocalResourceResolver()); try {/*from w ww. j a v a 2 s .co m*/ schemaFactory.newSchema(new StreamSource(getResourceAsStreamWrapper("schema/dmn.xsd"))); } catch (SAXException e1) { errors.reject("Cannot find / read schema", "Exception: " + e1.getMessage()); } SAXParserFactory parserFactory = SAXParserFactory.newInstance(); // parserFactory.setValidating(true); parserFactory.setNamespaceAware(true); // parserFactory.setSchema(schema); SAXParser parser = null; try { parser = parserFactory.newSAXParser(); XMLReader reader = parser.getXMLReader(); reader.setErrorHandler(this); try { parser.parse(new InputSource(is), (DefaultHandler) null); } catch (Exception e) { String msg = "Schema validation failed"; LOGGER.error(msg, e); errors.reject(msg, "Exception: " + e.getMessage()); } if (this.errors.size() > 0) { errors.reject("Schema validation failed", this.errors.toString()); } } catch (ParserConfigurationException e1) { errors.reject("Cannot create parser", "Exception: " + e1.getMessage()); } catch (SAXException e1) { errors.reject("Parser cannot be created", "Exception: " + e1.getMessage()); } }
From source file:com.sangupta.clitools.file.Format.java
private void formatXML(File file) { try {//from w ww.j ava2 s . c o m Source xmlInput = new StreamSource(file); StringWriter stringWriter = new StringWriter(); StreamResult xmlOutput = new StreamResult(stringWriter); TransformerFactory transformerFactory = TransformerFactory.newInstance(); transformerFactory.setAttribute("indent-number", 4); Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.transform(xmlInput, xmlOutput); String out = xmlOutput.getWriter().toString(); // add a new line after "?>< for next tag starting int index = out.indexOf("\"?><"); if (index > 0) { out = out.substring(0, index + 3) + "\n" + out.substring(index + 3); } if (!this.overwrite) { System.out.println(out); return; } org.apache.commons.io.FileUtils.writeStringToFile(file, out); } catch (Exception e) { System.out.println("Unable to format file!"); e.printStackTrace(); } }
From source file:org.callimachusproject.xml.InputSourceResolver.java
@Override public StreamSource resolve(String href, String base) throws TransformerException { try {/*from www. j a v a 2 s . co m*/ InputSource input = resolve(resolveURI(href, base)); if (input == null) return null; InputStream in = input.getByteStream(); if (in != null) { if (input.getSystemId() == null) return new StreamSource(in); return new StreamSource(in, input.getSystemId()); } Reader reader = input.getCharacterStream(); if (reader != null) { if (input.getSystemId() == null) return new StreamSource(reader); return new StreamSource(reader, input.getSystemId()); } if (input.getSystemId() == null) return new StreamSource(); return new StreamSource(input.getSystemId()); } catch (IOException e) { throw new TransformerException(e); } }
From source file:ddf.catalog.transformer.input.tika.TikaInputTransformer.java
public TikaInputTransformer(BundleContext bundleContext) { ClassLoader tccl = Thread.currentThread().getContextClassLoader(); try {// w w w .j a v a 2 s. co m Thread.currentThread().setContextClassLoader(getClass().getClassLoader()); templates = TransformerFactory .newInstance(net.sf.saxon.TransformerFactoryImpl.class.getName(), net.sf.saxon.TransformerFactoryImpl.class.getClassLoader()) .newTemplates( new StreamSource(TikaMetadataExtractor.class.getResourceAsStream("/metadata.xslt"))); } catch (TransformerConfigurationException e) { LOGGER.warn("Couldn't create XML transformer", e); } finally { Thread.currentThread().setContextClassLoader(tccl); } if (bundleContext == null) { LOGGER.error("Bundle context is null. Unable to register {} as an osgi service.", TikaInputTransformer.class.getSimpleName()); return; } registerService(bundleContext); IIORegistry.getDefaultInstance().registerServiceProvider(new J2KImageReaderSpi()); IIORegistry.getDefaultInstance().registerServiceProvider(new TIFFImageReaderSpi()); }
From source file:dk.defxws.fgssolrremote.OperationsImpl.java
public String getIndexInfo(String indexName, String resultPageXslt) throws java.rmi.RemoteException { super.getIndexInfo(indexName, resultPageXslt); InputStream infoStream = null; String indexInfoPath = "/" + config.getConfigName() + "/index/" + config.getIndexName(indexName) + "/indexInfo.xml"; try {/*from w w w . j a va 2s.c om*/ infoStream = OperationsImpl.class.getResourceAsStream(indexInfoPath); if (infoStream == null) { throw new GenericSearchException("Error " + indexInfoPath + " not found in classpath"); } } catch (IOException e) { throw new GenericSearchException("Error " + indexInfoPath + " not found in classpath", e); } String xsltPath = config.getConfigName() + "/index/" + config.getIndexName(indexName) + "/" + config.getIndexInfoResultXslt(indexName, resultPageXslt); StringBuffer sb = (new GTransformer()).transform(xsltPath, new StreamSource(infoStream), new String[] {}); return sb.toString(); }
From source file:moodle.android.moodle.helpers.MoodleWebService.java
private JSONObject getWebServiceResponse(String serverurl, String functionName, String urlParameters, int xslRawId) { JSONObject jsonobj = null;/* w w w .j a va2 s . c o m*/ try { HttpURLConnection con = (HttpURLConnection) new URL(serverurl + functionName).openConnection(); //HttpURLConnection con = (HttpURLConnection) new URL(serverurl + functionName + "&moodlewsrestformat=json").openConnection(); con.setConnectTimeout(30000); con.setReadTimeout(30000); con.setRequestMethod("POST"); con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); con.setRequestProperty("Content-Language", "en-US"); con.setDoOutput(true); con.setUseCaches(false); con.setDoInput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); Log.d("URLParameters: ", urlParameters.toString()); wr.writeBytes(urlParameters); wr.flush(); wr.close(); //Get Response InputStream is = con.getInputStream(); Source xmlSource = new StreamSource(is); Source xsltSource = new StreamSource(context.getResources().openRawResource(xslRawId)); TransformerFactory transFact = TransformerFactory.newInstance(); Transformer trans = transFact.newTransformer(xsltSource); StringWriter writer = new StringWriter(); trans.transform(xmlSource, new StreamResult(writer)); String jsonstr = writer.toString(); jsonstr = jsonstr.replace("<div class=\"no-overflow\"><p>", ""); jsonstr = jsonstr.replace("</p></div>", ""); jsonstr = jsonstr.replace("<p>", ""); jsonstr = jsonstr.replace("</p>", ""); Log.d("TransformObject: ", jsonstr); jsonobj = new JSONObject(jsonstr); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (TransformerConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (TransformerFactoryConfigurationError e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (TransformerException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return jsonobj; }
From source file:fr.efl.saxon.basex.BaseXQueryTest.java
/** * Test of makeCallExpression method, of class BaseXQuery. *//* w ww . j a v a 2 s. c o m*/ @Test public void testMakeCallExpression() { Configuration config = new Configuration(); config.registerExtensionFunction(new BaseXQuery()); Processor proc = new Processor(config); XPathCompiler xpc = proc.newXPathCompiler(); try { xpc.declareNamespace(BaseXQuery.EXT_NS_COMMON_PREFIX, BaseXQuery.EXT_NAMESPACE_URI); QName var = new QName("connect"); xpc.declareVariable(var); XPathSelector xp = xpc.compile(BaseXQuery.EXT_NS_COMMON_PREFIX + ":" + BaseXQuery.FUNCTION_NAME + "('for $i in 1 to 10 return <test>{$i}</test>', $connect)").load(); DocumentBuilder builder = proc.newDocumentBuilder(); XdmNode docConnect = builder .build(new StreamSource(new ByteArrayInputStream(CONNECT_STRING.getBytes("UTF-8")))); XdmNode connect = (XdmNode) docConnect.axisIterator(Axis.DESCENDANT_OR_SELF, new QName("basex")).next(); // System.err.println("connect is "+connect.getClass().getName()); // System.err.println("connect is "+connect.getNodeName()); // System.err.println("connect is "+connect.getNodeKind()); xp.setVariable(var, connect); xp.setContextItem(docConnect); XdmValue result = xp.evaluate(); SequenceIterator it = result.getUnderlyingValue().iterate(); Item item = it.next(); int count = 1; while (item != null) { assertEquals(Integer.toString(count++), item.getStringValue()); item = it.next(); } it.close(); } catch (SaxonApiException | UnsupportedEncodingException | XPathException ex) { ex.printStackTrace(System.err); fail(ex.getMessage()); } }