List of usage examples for javax.xml.transform TransformerException printStackTrace
@Override public void printStackTrace()
From source file:org.apache.metron.dataloads.taxii.TaxiiHandler.java
public String getStringFromDocument(Document doc) { try {// ww w . j a v a2 s . c om DOMSource domSource = new DOMSource(doc); StringWriter writer = new StringWriter(); StreamResult result = new StreamResult(writer); TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); transformer.transform(domSource, result); return writer.toString(); } catch (TransformerException ex) { ex.printStackTrace(); return null; } }
From source file:org.opencastproject.loadtest.impl.IngestJob.java
/** * Parse and change the manifest.xml's id to match the mediapackage id we will be ingesting. * // w ww.j a va2 s. c o m * @param filepath * The path to the manifest.xml file. */ private void changeManifestID(String filepath) { try { logger.info("Filepath for changing the manifest id is " + filepath); DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); Document doc = docBuilder.parse(filepath); // Get the mediapackage XPath xPath = XPathFactory.newInstance().newXPath(); Node mediapackage = ((NodeList) xPath.evaluate("//*[local-name() = 'mediapackage']", doc, XPathConstants.NODESET)).item(0); // update mediapackage attribute NamedNodeMap attr = mediapackage.getAttributes(); Node nodeAttr = attr.getNamedItem("id"); nodeAttr.setTextContent(id); // write the content into xml file TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(new File(filepath)); transformer.transform(source, result); } catch (ParserConfigurationException pce) { pce.printStackTrace(); } catch (TransformerException tfe) { tfe.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } catch (SAXException sae) { sae.printStackTrace(); } catch (XPathExpressionException xpe) { xpe.printStackTrace(); } }
From source file:com.seajas.search.bridge.contender.metadata.SeajasEntry.java
/** * Set the textual description as html//from w ww . j a v a 2 s . c o m * * @param value */ public void setDescriptionHtml(final Node value) { SyndContent description = new SyndContentImpl(); StringWriter writer = new StringWriter(); Transformer transformer = null; try { transformer = TransformerFactory.newInstance().newTransformer(); transformer.transform(new DOMSource(value), new StreamResult(writer)); } catch (TransformerException e) { e.printStackTrace(); } description.setValue(writer.toString()); description.setType(MediaType.TEXT_HTML_VALUE); super.setDescription(description); }
From source file:curam.molsa.test.customfunctions.MOLSADOMReader.java
/** * Transforms an inbound DOM document according to a specific stylesheet. * /*ww w . j a va2 s .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:com.hydroLibCreator.action.Creator.java
private void buildDrumKitXML() { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); try {/* w ww. j av a 2 s.c om*/ DocumentBuilder builder = factory.newDocumentBuilder(); document = builder.newDocument(); } catch (ParserConfigurationException parserException) { parserException.printStackTrace(); } Element drumkit_info = document.createElement("drumkit_info"); document.appendChild(drumkit_info); Attr xmlns = document.createAttribute("xmlns"); xmlns.setValue("http://www.hydrogen-music.org/drumkit"); Attr xmlns_xsi = document.createAttribute("xmlns:xsi"); xmlns_xsi.setValue("http://www.w3.org/2001/XMLSchema-instance"); drumkit_info.setAttributeNode(xmlns); drumkit_info.setAttributeNode(xmlns_xsi); Node nameNode = createNameNode(document); drumkit_info.appendChild(nameNode); Node authorNode = createAuthorNode(document); drumkit_info.appendChild(authorNode); Node infoNode = createInfoNode(document); drumkit_info.appendChild(infoNode); Node licenseNode = createLicenseNode(document); drumkit_info.appendChild(licenseNode); Node instrumentListNode = createInstrumentListNode(document); drumkit_info.appendChild(instrumentListNode); // write the XML document to disk try { // create DOMSource for source XML document Source xmlSource = new DOMSource(document); // create StreamResult for transformation result Result result = new StreamResult(new FileOutputStream(destinationPath + "/drumkit.xml")); // create TransformerFactory TransformerFactory transformerFactory = TransformerFactory.newInstance(); // create Transformer for transformation Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); // transform and deliver content to client transformer.transform(xmlSource, result); } // handle exception creating TransformerFactory catch (TransformerFactoryConfigurationError factoryError) { System.err.println("Error creating " + "TransformerFactory"); factoryError.printStackTrace(); } catch (TransformerException transformerError) { System.err.println("Error transforming document"); transformerError.printStackTrace(); } catch (IOException ioException) { ioException.printStackTrace(); } }
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//from w ww . j a v a 2 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:de.ifgi.lodum.sparqlfly.SparqlFly.java
/** * executes an sparql query and writes the query solution to the servlet response * @param queryString// ww w. j a va2 s . c o 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:Interface.MainJFrame.java
private void btnXMLActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnXMLActionPerformed // TODO add your handling code here: try {//from ww w .j a v a 2 s. c om DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); // root elements Document doc = docBuilder.newDocument(); Element rootElement = doc.createElement("Employees"); doc.appendChild(rootElement); // staff elements String empTitle = txtEmployeeType.getText().trim(); empTitle = empTitle.replace(" ", ""); Element staff = doc.createElement(empTitle); rootElement.appendChild(staff); // set attribute to staff element Attr attr = doc.createAttribute("ID"); attr.setValue(txtEmployeeID.getText().trim()); staff.setAttributeNode(attr); // shorten way // staff.setAttribute("id", "1"); // FullName elements Element FulllName = doc.createElement("FulllName"); FulllName.appendChild(doc.createTextNode(txtFullName.getText().trim())); staff.appendChild(FulllName); // Phone elements Element Phone = doc.createElement("PhoneNumber"); Phone.appendChild(doc.createTextNode(txtPhoneNumber.getText().trim())); staff.appendChild(Phone); // Address elements Element Address = doc.createElement("Address"); Address.appendChild(doc.createTextNode(txtAddress.getText().trim())); staff.appendChild(Address); // Title elements Element Title = doc.createElement("Tile"); Title.appendChild(doc.createTextNode(txtEmployeeType.getText().trim())); staff.appendChild(Title); // PayCategory elements Element PayCategory = doc.createElement("PayCategory"); PayCategory.appendChild(doc.createTextNode(txtPayCategory.getText().trim())); staff.appendChild(PayCategory); // Salary elements Element Salary = doc.createElement("Salary"); Salary.appendChild(doc.createTextNode(txtSalary.getText().trim())); staff.appendChild(Salary); // Hours elements String hours = txtHours.getText().trim(); if (txtHours.getText().equalsIgnoreCase("") || hours == null) { hours = "null"; } Element Hours = doc.createElement("Hours"); Hours.appendChild(doc.createTextNode(hours)); staff.appendChild(Hours); // Bonus elements Element Bonus = doc.createElement("Bonus"); Bonus.appendChild(doc.createTextNode(txtBonuses.getText().trim())); staff.appendChild(Bonus); // Total elements Element Total = doc.createElement("Total"); Total.appendChild(doc.createTextNode(txtTotal.getText().trim())); staff.appendChild(Total); // write the content into xml file TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(new File("XMLOutput")); // Output to console for testing // StreamResult result = new StreamResult(System.out); transformer.transform(source, result); } catch (ParserConfigurationException pce) { pce.printStackTrace(); } catch (TransformerException tfe) { tfe.printStackTrace(); } }
From source file:bridge.toolkit.commands.PreProcess.java
/** * The unit of processing work to be performed for the PreProcess module. * @see org.apache.commons.chain.Command#execute(org.apache.commons.chain.Context) *///from w ww . j a v a 2 s.co m @SuppressWarnings("unchecked") public boolean execute(Context ctx) { System.out.println("Executing PreProcess"); if ((ctx.get(Keys.SCPM_FILE) != null) && (ctx.get(Keys.RESOURCE_PACKAGE) != null)) { src_dir = (String) ctx.get(Keys.RESOURCE_PACKAGE); List<File> src_files = new ArrayList<File>(); try { src_files = URNMapper.getSourceFiles(src_dir); } catch (NullPointerException npe) { System.out.println(CONVERSION_FAILED); System.out.println("The 'Resource Package' is empty."); return PROCESSING_COMPLETE; } catch (JDOMException e) { System.out.println(CONVERSION_FAILED); e.printStackTrace(); return PROCESSING_COMPLETE; } catch (IOException e) { System.out.println(CONVERSION_FAILED); e.printStackTrace(); return PROCESSING_COMPLETE; } urn_map = URNMapper.writeURNMap(src_files, ""); transform = this.getClass().getResourceAsStream(TRANSFORM_FILE); try { doTransform((String) ctx.get(Keys.SCPM_FILE)); addResources(urn_map); processDeps(mapDependencies()); } catch (ResourceMapException e) { System.out.println(CONVERSION_FAILED); e.printTrace(); return PROCESSING_COMPLETE; } catch (JDOMException jde) { System.out.println(CONVERSION_FAILED); jde.printStackTrace(); return PROCESSING_COMPLETE; } catch (TransformerException te) { System.out.println(CONVERSION_FAILED); te.printStackTrace(); return PROCESSING_COMPLETE; } catch (IOException e1) { System.out.println(CONVERSION_FAILED); e1.printStackTrace(); return PROCESSING_COMPLETE; } ctx.put(Keys.URN_MAP, urn_map); ctx.put(Keys.XML_SOURCE, manifest); System.out.println("Conversion of SCPM to IMS Manifest was successful"); } else { System.out.println(CONVERSION_FAILED); System.out.println("One of the required Context entries for the " + this.getClass().getSimpleName() + " command to be executed was null"); return PROCESSING_COMPLETE; } return CONTINUE_PROCESSING; }