List of usage examples for javax.xml.transform TransformerConfigurationException printStackTrace
@Override public void printStackTrace()
From source file:org.socialhistoryservices.pid.database.dao.HandleDaoImpl.java
public HandleDaoImpl() { try {//from w w w. j a v a2 s . c o m templates = TransformerFactory.newInstance().newTemplates( new StreamSource(this.getClass().getResourceAsStream("/locations.remove.ns.xsl"))); } catch (TransformerConfigurationException e) { e.printStackTrace(); } }
From source file:edu.harvard.i2b2.crc.dao.setfinder.querybuilder.temporal.TemporalPanelCellQueryItem.java
private String convertNodeToString(Node request) { StringWriter writer = new StringWriter(); Transformer transformer;// w ww .java 2 s .c om try { transformer = TransformerFactory.newInstance().newTransformer(); transformer.transform(new DOMSource(request), new StreamResult(writer)); } 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(); } return writer.toString(); }
From source file:com.wooki.services.parsers.XHTMLToFormattingObjects.java
public InputStream performTransformation(Resource xmlDocument) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); StreamResult toReturn = new StreamResult(baos); // Use the TransformerFactory to instantiate a Transformer that will // work with the stylesheet you specify. This method call also processes // the stylesheet into // a compiled Templates object. try {//from w ww . j av a 2s. com URL url = this.xslStylesheet.getURL(); Element processedStylesheet = cache.get(url); if (processedStylesheet == null) { if (url.getProtocol().equals("http")) { GetMethod method = new GetMethod(url.toString()); this.httpClient.executeMethod(method); byte[] body = method.getResponseBody(); StreamSource input = new StreamSource(new ByteArrayInputStream(body)); input.setSystemId(url.toString()); tFactory.setURIResolver(this); transformer = tFactory.newTransformer(input); transformer.setURIResolver(this); processedStylesheet = new Element(this.xslStylesheet.getURL(), transformer); } else { StreamSource input = new StreamSource(this.xslStylesheet.getInputStream()); input.setSystemId(this.xslStylesheet.getFile()); transformer = tFactory.newTransformer(input); transformer.setURIResolver(this); processedStylesheet = new Element(this.xslStylesheet.getURL(), transformer); } cache.put(processedStylesheet); } else { transformer = (Transformer) processedStylesheet.getObjectValue(); } XMLReader reader = XMLReaderFactory.createXMLReader(); reader.setEntityResolver(this); // transformer. // Use the Transformer to apply the associated Templates object to // an // XML document (foo.xml) and write the output to a file. transformer.transform(new SAXSource(reader, new InputSource(xmlDocument.getInputStream())), toReturn); String result = new String(baos.toByteArray()); return new ByteArrayInputStream(baos.toByteArray()); } catch (TransformerConfigurationException e) { e.printStackTrace(); logger.error(e.getLocalizedMessage()); return null; } catch (IOException e) { e.printStackTrace(); logger.error(e.getLocalizedMessage()); return null; } catch (TransformerException e) { e.printStackTrace(); logger.error(e.getLocalizedMessage()); return null; } catch (SAXException e) { e.printStackTrace(); logger.error(e.getLocalizedMessage()); return null; } catch (Error e) { e.printStackTrace(); logger.error(e.getLocalizedMessage()); } return new ByteArrayInputStream(baos.toByteArray()); }
From source file:de.tudarmstadt.ukp.lmf.writer.xml.LMFXmlWriter.java
/** * Creates XML TransformerHandler//from w ww .j a v a2s .co m * @param xmlOutPath * @param dtdPath * @return * @throws IOException * @throws TransformerException */ public TransformerHandler getXMLTransformerHandler(OutputStream out) { StreamResult streamResult = new StreamResult(out); SAXTransformerFactory tf = (SAXTransformerFactory) SAXTransformerFactory.newInstance(); TransformerHandler th = null; try { th = tf.newTransformerHandler(); } catch (TransformerConfigurationException e) { logger.error("Error on initiating TransformerHandler"); e.printStackTrace(); } Transformer serializer = th.getTransformer(); serializer.setOutputProperty(OutputKeys.METHOD, "xml"); serializer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); if (dtdPath != null) serializer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, dtdPath); serializer.setOutputProperty(OutputKeys.INDENT, "yes"); serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); th.setResult(streamResult); return th; }
From source file:curam.molsa.test.customfunctions.MOLSADOMReader.java
/** * Transforms an inbound DOM document according to a specific stylesheet. * //from w w w. ja v a 2s . co m * @param document * Contains the Inbound DOM document. * @param stylesheet * The file location of the stylesheet use to transform the document * @param rootElement * The expected root element of the transformed document * @return The transformed document */ public Document transformDocumentBasedOnXSL(final Document document, final String stylesheet, final String responseRootElement) throws ParserConfigurationException, SAXException, IOException { String xmlString = ""; Document transformedDocument = null; final DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance(); dbfac.setNamespaceAware(true); final DocumentBuilder builder = dbfac.newDocumentBuilder(); try { final InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(stylesheet); final Transformer transformer = TransformerFactory.newInstance() .newTransformer(new StreamSource(inputStream)); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); final StringWriter stringWriter = new StringWriter(); final StreamResult streamResult = new StreamResult(stringWriter); final DOMSource source = new DOMSource(document); transformer.transform(source, streamResult); xmlString = stringWriter.toString(); if (xmlString.contains(responseRootElement)) { transformedDocument = builder.parse(new InputSource(new StringReader(xmlString))); } else { transformedDocument = builder.newDocument(); } } catch (final TransformerConfigurationException tcExp) { tcExp.printStackTrace(); } catch (final TransformerException tExp) { tExp.printStackTrace(); } return transformedDocument; }
From source file:de.ifgi.lodum.sparqlfly.SparqlFly.java
/** * executes an sparql query and writes the query solution to the servlet response * @param queryString/*from w w w . j ava 2s.co m*/ * @param baseRequest * @param request * @param writer * @param response */ private void executeQuery(String queryString, Request baseRequest, HttpServletRequest request, PrintWriter writer, HttpServletResponse response) throws Exception { response.setHeader("Connection", "Keep-Alive"); response.setHeader("Cache-Control", "no-cache"); response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Access-Control-Allow-Methods", "GET"); response.setHeader("Access-Control-Allow-Headers", "Content-Type"); // add RDF++ rules Reasoner reasoner = new GenericRuleReasoner(Rule.rulesFromURL("files/rdfsplus.rule")); // Create inferred model using the reasoner and write it out. InfModel inf = ModelFactory.createInfModel(reasoner, ModelFactory.createDefaultModel(ReificationStyle.Standard)); Query query = null; query = QueryFactory.create(queryString); Iterator<String> remoteFiles = query.getGraphURIs().iterator(); while (remoteFiles.hasNext()) { String temp = remoteFiles.next(); inf.add(getModelFromURL(temp, getFormat(temp))); } QueryExecution qexec = null; //check if geo methods have been used in the query. if not no spatial index is needed if (query.getPrefixMapping().getNsPrefixMap().containsValue("java:org.geospatialweb.arqext.")) { Indexer i = Indexer.createDefaultIndexer(); i.createIndex(inf); qexec = QueryExecutionFactory.create(query, inf); Geo.setContext(qexec, i); } else { qexec = QueryExecutionFactory.create(query, inf); } if (query.isSelectType()) { ResultSet results = qexec.execSelect(); String outputString = null; StringOutputStream outstream = new StringOutputStream(); //write the query solution to different formats depending on the requested format if (accept.getPrefMIME().equalsIgnoreCase("application/sparql-results+json") || accept.getPrefMIME().equalsIgnoreCase("application/json")) { response.setContentType("application/sparql-results+json"); ResultSetFormatter.outputAsJSON(outstream, results); writer.print(outstream); } else if (accept.getPrefMIME().equalsIgnoreCase("application/sparql-results+xml")) { response.setContentType("application/sparql-results+xml"); ResultSetFormatter.outputAsXML(outstream, results); writer.print(outstream.toString()); } else if (accept.getPrefMIME().equalsIgnoreCase("application/rdf+xml")) { response.setContentType("application/rdf+xml"); // Model model = ModelFactory.createDefaultModel(); ResultSetFormatter.asRDF(inf, results); inf.write(writer, "RDF/XML"); } else if (accept.getPrefMIME().equalsIgnoreCase("application/x-turtle")) { response.setContentType("application/x-turtle"); // Model model = ModelFactory.createDefaultModel(); ResultSetFormatter.asRDF(inf, results); inf.write(writer, "TURTLE"); } else if (accept.getPrefMIME().equalsIgnoreCase("text/html")) { response.setContentType("text/html"); ResultSetFormatter.outputAsXML(outstream, results); //transform xml sparql result to html table with xslt transformation Source xmlSource = new StreamSource(new StringInputStream(outstream.toString())); Source xsltSource = null; xsltSource = new StreamSource(new FileInputStream(new File("files/result-to-html.xsl"))); StringOutputStream resultStream = new StringOutputStream(); Result result = new StreamResult(resultStream); TransformerFactory transFact = TransformerFactory.newInstance(); Transformer trans = null; try { trans = transFact.newTransformer(xsltSource); } catch (TransformerConfigurationException e1) { e1.printStackTrace(); } try { trans.transform(xmlSource, result); } catch (TransformerException e) { e.printStackTrace(); } String html = resultStream.toString(); String prefixes = ""; if (request.getParameter("prefix") != null && request.getParameter("prefix").equals("true")) { prefixes += "<b>Prefixes</b><br>"; for (Entry<String, String> pre : inf.getNsPrefixMap().entrySet()) { if (pre.getKey() != null && pre.getValue() != null && html.contains(pre.getValue())) { prefixes += pre.getKey() + " :" + pre.getValue() + "<br>"; html = html.replace(pre.getValue(), pre.getKey() + " : "); } } prefixes += "<br/><br/>"; } html = html.replace("$PREFIXES$", prefixes); writer.write(header.toString() + html + "<br><br><br><input type=button value=\"<< back\" onClick=\"history.back()\">" + footer.toString()); } else if (accept.getPrefMIME().equalsIgnoreCase("application/n3")) { response.setContentType("application/n3"); ResultSetFormatter.asRDF(inf, results); inf.write(writer, "N3"); } else if (accept.getPrefMIME().equalsIgnoreCase("text/comma-separated-values")) { response.setContentType("text/comma-separated-values"); ResultSetFormatter.outputAsCSV(outstream, results); writer.print(outstream.toString()); } else { response.setContentType("text/plain"); outputString = new TextOutput(inf).asString(results); writer.print(outputString); } //if the query is a construct query } else if (query.isConstructType()) { Model resultModel = qexec.execConstruct(); if (accept.getPrefMIME().equalsIgnoreCase("application/x-turtle")) { response.setContentType("application/x-turtle"); resultModel.write(writer, "TURTLE"); } else if (accept.getPrefMIME().equalsIgnoreCase("application/n3")) { response.setContentType("application/n3"); resultModel.write(writer, "N3"); } else { response.setContentType("application/rdf+xml"); resultModel.write(writer, "RDF/XML"); } } response.setStatus(HttpServletResponse.SC_OK); baseRequest.setHandled(true); form.reset(); header.reset(); }
From source file:de.thorstenberger.taskmodel.view.webapp.filter.ExportPDFFilter.java
/** * <ul>// ww w . j a v a2 s . com * <li>Strip <script> elements, because xml characters within these tags lead to invalid xhtml.</li> * <li>Xhtmlrenderer does not render form elements right (will probably support real PDF forms in the future), so we * need to replace select boxes with simple strings: Replace each select box with a bold string containing the * selected option.</li> * <li>Replace every input checkbox with [ ] for unchecked or [X] for checked inputs.</li> * </ul> * * @param xhtml * xhtml as {@link Document} * @return */ private Document processDocument(final Document xhtml) { final String xslt = readFile(this.getClass().getResourceAsStream("adjustforpdfoutput.xslt")); final Source xsltSource = new StreamSource(new StringReader(xslt)); try { final Transformer transformer = TransformerFactory.newInstance().newTransformer(xsltSource); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF8"); final DOMResult result = new DOMResult(); transformer.transform(new DOMSource(xhtml), result); return (Document) result.getNode(); } catch (final TransformerConfigurationException e) { log.error("Internal: Wrong xslt configuration", e); } catch (final TransformerFactoryConfigurationError e) { log.error("Internal: Wrong xslt configuration", e); } catch (final TransformerException e) { log.error("Internal: Could not strip script tags from xhtml", e); e.printStackTrace(); } // fall through in error case: return untransformed xhtml log.warn("Could not clean up html, using orginial instead. This might lead to missing content!"); return xhtml; }
From source file:it.ciroppina.idol.generic.tunnel.IdolOEMTunnel.java
/** * @param response//from ww w . j av a2s . c o m * @return the ACI aurtnresponse in XML compact format */ private String xmlResponse(Document response) { String result = ""; StreamResult xmlOutput = new StreamResult(new StringWriter()); Transformer transformer; try { transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); transformer.transform(new DOMSource(response.getDocumentElement()), xmlOutput); result = xmlOutput.getWriter().toString(); } catch (TransformerConfigurationException e) { e.printStackTrace(); return "Error occurred parsing XML-formatted autnresponse - Badly formatted request"; } catch (TransformerFactoryConfigurationError e) { e.printStackTrace(); return "Error occurred parsing XML-formatted autnresponse - Badly formatted request"; } catch (TransformerException e) { e.printStackTrace(); return "Error occurred parsing XML-formatted autnresponse - Badly formatted request"; } return result; }
From source file:bridge.toolkit.commands.MobileBuilder.java
/** * The unit of processing work to be performed for the MobileBuilder module. * /*from w w w .j a v a 2s. c om*/ * @see org.apache.commons.chain.Command#execute(org.apache.commons.chain.Context) */ @Override public boolean execute(Context ctx) { System.out.println("Executing Mobile Builder"); if ((ctx.get(Keys.SCPM_FILE) != null) && (ctx.get(Keys.RESOURCE_PACKAGE) != null)) { CopyDirectory cd = new CopyDirectory(); src_dir = (String) ctx.get(Keys.RESOURCE_PACKAGE); scpm_file = (String) ctx.get(Keys.SCPM_FILE); List<File> src_files = new ArrayList<File>(); try { src_files = URNMapper.getSourceFiles(src_dir); } catch (NullPointerException npe) { System.out.println(MOBILEBUILDER_FAILED); System.out.println("The 'Resource Package' is empty."); return PROCESSING_COMPLETE; } catch (JDOMException e) { System.out.println(MOBILEBUILDER_FAILED); e.printStackTrace(); return PROCESSING_COMPLETE; } catch (IOException e) { System.out.println(MOBILEBUILDER_FAILED); e.printStackTrace(); return PROCESSING_COMPLETE; } urn_map = URNMapper.writeURNMap(src_files, "../media/"); //write urn map file out to the ViewerApplication directory temporarily. File js = null; File jsviewer = null; File xsldir = null; try { jsviewer = new File(System.getProperty("user.dir") + File.separator + "ViewerApplication"); js = new File(System.getProperty("user.dir") + File.separator + "ViewerApplication/app/urn_resource_map.xml"); //check if the directory exists if it does use it and set the file object to null so it will not be deleted // else copy it from the jar and delete it when finished processing. if (!(jsviewer.exists())) { //System.out.println("Path directory creation " + jsapp.getAbsolutePath()); jsviewer.mkdirs(); cd.CopyJarFiles(this.getClass(), "ViewerApplication", jsviewer.getAbsolutePath()); } else { jsviewer = null; } //check if the directory exists if it does use it and set the file object to null so it will not be deleted // else copy it from the jar and delete it when finished processing. xsldir = new File(System.getProperty("user.dir") + File.separator + "xsl"); if (!(xsldir.exists())) { //System.out.println("jsviewer directory creation " + jsviewer.getAbsolutePath()); xsldir.mkdirs(); cd.CopyJarFiles(this.getClass(), "xsl", xsldir.getAbsolutePath()); } else { xsldir = null; } XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat()); FileWriter writer; writer = new FileWriter(js); outputter.output(urn_map, writer); writer.flush(); writer.close(); } catch (IOException e) { System.out.println(MOBILEBUILDER_FAILED); e.printStackTrace(); return PROCESSING_COMPLETE; } String outputPath = ""; if (ctx.get(Keys.OUTPUT_DIRECTORY) != null) { outputPath = (String) ctx.get(Keys.OUTPUT_DIRECTORY); if (outputPath.length() > 0) { outputPath = outputPath + File.separator; } } //create new directory and folder for mobile_output File newMobApp = createOutputLocation(outputPath); //transform SCPM to main index.htm file try { transformSCPM(newMobApp, ctx.get(Keys.OUTPUT_TYPE)); } catch (FileNotFoundException e) { System.out.println(MOBILEBUILDER_FAILED); e.printStackTrace(); return PROCESSING_COMPLETE; } catch (TransformerConfigurationException e1) { System.out.println(MOBILEBUILDER_FAILED); e1.printStackTrace(); return PROCESSING_COMPLETE; } catch (TransformerException e) { System.out.println(MOBILEBUILDER_FAILED); e.printStackTrace(); return PROCESSING_COMPLETE; } //parse SCPM for list of files in each scoEntry to create the individual mobile app pages try { generateMobilePages(newMobApp, (String) ctx.get(Keys.OUTPUT_TYPE)); } catch (TransformerConfigurationException e2) { System.out.println(MOBILEBUILDER_FAILED); e2.printStackTrace(); return PROCESSING_COMPLETE; } catch (FileNotFoundException e2) { System.out.println(MOBILEBUILDER_FAILED); e2.printStackTrace(); return PROCESSING_COMPLETE; } catch (JDOMException e2) { System.out.println(MOBILEBUILDER_FAILED); e2.printStackTrace(); return PROCESSING_COMPLETE; } catch (IOException e2) { System.out.println(MOBILEBUILDER_FAILED); e2.printStackTrace(); return PROCESSING_COMPLETE; } catch (TransformerFactoryConfigurationError e2) { System.out.println(MOBILEBUILDER_FAILED); e2.printStackTrace(); return PROCESSING_COMPLETE; } catch (TransformerException e2) { System.out.println(MOBILEBUILDER_FAILED); e2.printStackTrace(); return PROCESSING_COMPLETE; } //create list.js file try { generateListFile(newMobApp); } catch (IOException e1) { System.out.println(MOBILEBUILDER_FAILED); e1.printStackTrace(); return PROCESSING_COMPLETE; } catch (JDOMException e1) { System.out.println(MOBILEBUILDER_FAILED); e1.printStackTrace(); return PROCESSING_COMPLETE; } try { //copy over css and jquery mobile files File mobiApp_loc = new File(System.getProperty("user.dir") + File.separator + "mobiApp"); //check if the directory exists if it does use it else copy it from the jar if (mobiApp_loc.exists()) { cd.copyDirectory(mobiApp_loc, newMobApp); } else { cd.CopyJarFiles(this.getClass(), "mobiApp", newMobApp.getAbsolutePath()); } //copy commonmobile.js File commonmobile_js = new File(System.getProperty("user.dir") + File.separator + "xsl" + File.separator + "bridge" + File.separator + "toolkit" + File.separator + "commands" + File.separator + "commonmobile.js"); //check if the directory exists if it does use it else copy it from the jar if (commonmobile_js.exists()) { cd.copyDirectory(commonmobile_js, newMobApp); } //copy over media files File new_media_loc = new File(newMobApp.getAbsolutePath() + File.separator + "media"); new_media_loc.mkdir(); Iterator<File> srcIterator = src_files.iterator(); while (srcIterator.hasNext()) { File src = srcIterator.next(); if (!src.getName().endsWith(".xml") && !src.getName().endsWith(".XML")) { cd.copyDirectory(src, new_media_loc); } } } catch (IOException e) { System.out.println(MOBILEBUILDER_FAILED); e.printStackTrace(); return PROCESSING_COMPLETE; } //delete the urn map from the ViewerApplication location ArrayList<String> files_to_delete = new ArrayList<String>(); if (jsviewer != null) { DeleteDirectoryOnExit(jsviewer, files_to_delete); } if (js != null) { files_to_delete.add(js.getAbsolutePath()); } if (xsldir != null) { DeleteDirectoryOnExit(xsldir, files_to_delete); } ctx.put(Keys.MOBLIE_FILES_TO_DELETE, files_to_delete); System.out.println("MobileBuilder processing was successful"); } return CONTINUE_PROCESSING; }
From source file:cross.datastructures.workflow.DefaultWorkflow.java
/** * Applies a stylesheet transformation to this DefaultWorkflow to create * html with clickable links.// ww w. j ava 2 s . c o m * * @param f */ protected void saveHTML(final File f) { final TransformerFactory tf = TransformerFactory.newInstance(); try { final InputStream xsstyler = getClass().getClassLoader() .getResourceAsStream("res/xslt/maltcmsHTMLResult.xsl"); final StreamSource sstyles = new StreamSource(xsstyler); final FileInputStream xsr = new FileInputStream(f); final FileOutputStream xsw = new FileOutputStream(new File(f.getParentFile(), "workflow.html")); final StreamSource sts = new StreamSource(xsr); final StreamResult str = new StreamResult(xsw); final Transformer t = tf.newTransformer(sstyles); t.transform(sts, str); } catch (final TransformerConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (final FileNotFoundException | TransformerException e) { // TODO Auto-generated catch block e.printStackTrace(); } }