List of usage examples for javax.xml.transform TransformerException getMessage
public String getMessage()
From source file:org.kitodo.production.editor.XMLEditor.java
/** * Save the String 'xmlConfigurationString' to the XML file denoted by * 'configurationFile'./* ww w . j a v a 2s. c o m*/ */ public void saveXMLConfiguration() { logger.info("Saving configuration to file {}", currentConfigurationFile); try { Document document = documentBuilder .parse(new InputSource(new StringReader(this.xmlConfigurationString))); TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource domSource = new DOMSource(document); try (FileOutputStream outputStream = new FileOutputStream(configurationFile.getFile(), false); PrintWriter printWriter = new PrintWriter(outputStream)) { StreamResult streamResult = new StreamResult(printWriter); transformer.transform(domSource, streamResult); } catch (TransformerException e) { logger.error("ERROR: transformation failed: " + e.getMessage()); } } catch (TransformerConfigurationException e) { logger.error("ERROR: transformer configuration exception: " + e.getMessage()); } catch (FileNotFoundException e) { logger.error("ERROR: file not found: " + e.getMessage()); } catch (IOException e) { logger.error("ERROR: could not save XML configuration: " + e.getMessage()); } catch (SAXException e) { logger.error("ERROR: error parsing given XML string: " + e.getMessage()); } }
From source file:org.ncbo.stanford.service.xml.impl.XMLSerializationServiceImpl.java
/** * Generates XML response then apply XSL transformation. This is useful to * filter huge XML response such as findAll() Ontologies. * // www. jav a 2 s . c o m * If SUCCESS - Entity info is displayed. else - Error info is displayed. * * @param request * @param response * @param data * @param xsltFile */ public void generateXMLResponse(Request request, Response response, Object data, String xsltFile) { if (response.getStatus().isError()) { generateStatusXMLResponse(request, response); } else { MediaType prefMediaType = getPreferredMediaType(request); if (prefMediaType.equals(MediaType.APPLICATION_JSON)) { generateXMLResponse(request, response, data); } else { try { RequestUtils.setHttpServletResponse(response, Status.SUCCESS_OK, prefMediaType, applyXSL(request, data, xsltFile)); } catch (TransformerException e) { // XML parse ERROR response.setStatus(Status.SERVER_ERROR_INTERNAL, e.getMessage()); generateStatusXMLResponse(request, response); e.printStackTrace(); log.error(e); } } } }
From source file:org.obm.push.impl.ResponderImpl.java
@Override public void sendXMLResponse(String defaultNamespace, Document doc) { domDumper.dumpXml(doc);//w w w. j a va 2 s. c om try { ByteArrayOutputStream out = new ByteArrayOutputStream(); DOMUtils.serialize(doc, out); byte[] ret = out.toByteArray(); writeData(ret, "text/xml"); } catch (TransformerException e) { logger.error(e.getMessage(), e); } catch (IOException e) { logger.warn(e.getMessage(), e); } }
From source file:org.obm.push.mail.ReplyEmail.java
private TextBody appendRepliedMailToHtml(Reader partReader, Charset partCharset, String repliedEmail) throws NotQuotableEmailException { try {//from ww w . j a va 2 s .co m final InputSource replySource = new InputSource(partReader); final InputSource originalSource = new InputSource(new StringReader(repliedEmail)); final Document replyHtmlDoc = DOMUtils.parseHtmlAsDocument(replySource); final Node originalHtmlNode = DOMUtils.parseHtmlAsFragment(originalSource); final Element quoteBlock = insertIntoQuoteblock(replyHtmlDoc, originalHtmlNode); final Element bodyNode = DOMUtils.getUniqueElement(replyHtmlDoc.getDocumentElement(), "BODY"); bodyNode.appendChild(quoteBlock); StringReader replyHtmlDocReader = new StringReader(DOMUtils.serializeHtmlDocument(replyHtmlDoc)); BasicBodyFactory basicBodyFactory = new BasicBodyFactory(); return basicBodyFactory.textBody(cleanLineBreaks(replyHtmlDocReader), partCharset); } catch (TransformerException e) { logger.error(e.getMessage(), e); throw new NotQuotableEmailException("Html part isn't quotable", e); } catch (SAXException e) { logger.error(e.getMessage(), e); throw new NotQuotableEmailException("Html part isn't quotable", e); } catch (IOException e) { logger.error(e.getMessage(), e); throw new NotQuotableEmailException("Html part isn't quotable", e); } }
From source file:org.ofbiz.content.data.DataResourceWorker.java
public static void renderDataResourceAsText(Delegator delegator, String dataResourceId, Appendable out, Map<String, Object> templateContext, Locale locale, String targetMimeTypeId, boolean cache, List<GenericValue> webAnalytics) throws GeneralException, IOException { if (dataResourceId == null) { throw new GeneralException("Cannot lookup data resource with for a null dataResourceId"); }// w w w .j ava 2 s . co m if (templateContext == null) { templateContext = FastMap.newInstance(); } if (UtilValidate.isEmpty(targetMimeTypeId)) { targetMimeTypeId = "text/html"; } if (locale == null) { locale = Locale.getDefault(); } // check for a cached template if (cache) { String disableCache = EntityUtilProperties.getPropertyValue("content", "disable.ftl.template.cache", delegator); if (disableCache == null || !disableCache.equalsIgnoreCase("true")) { try { Template cachedTemplate = FreeMarkerWorker.getTemplate("DataResource:" + dataResourceId); if (cachedTemplate != null) { String subContentId = (String) templateContext.get("subContentId"); if (UtilValidate.isNotEmpty(subContentId)) { templateContext.put("contentId", subContentId); templateContext.put("subContentId", null); templateContext.put("globalNodeTrail", null); // Force getCurrentContent to query for subContent } FreeMarkerWorker.renderTemplate(cachedTemplate, templateContext, out); } } catch (TemplateException e) { Debug.logError("Error rendering FTL template. " + e.getMessage(), module); throw new GeneralException("Error rendering FTL template", e); } return; } } // if the target mimeTypeId is not a text type, throw an exception if (!targetMimeTypeId.startsWith("text/")) { throw new GeneralException( "The desired mime-type is not a text type, cannot render as text: " + targetMimeTypeId); } // get the data resource object GenericValue dataResource = EntityQuery.use(delegator).from("DataResource") .where("dataResourceId", dataResourceId).cache(cache).queryOne(); if (dataResource == null) { throw new GeneralException( "No data resource object found for dataResourceId: [" + dataResourceId + "]"); } // a data template attached to the data resource String dataTemplateTypeId = dataResource.getString("dataTemplateTypeId"); // no template; or template is NONE; render the data if (UtilValidate.isEmpty(dataTemplateTypeId) || "NONE".equals(dataTemplateTypeId)) { DataResourceWorker.writeDataResourceText(dataResource, targetMimeTypeId, locale, templateContext, delegator, out, true); } else { // a template is defined; render the template first templateContext.put("mimeTypeId", targetMimeTypeId); // FTL template if ("FTL".equals(dataTemplateTypeId)) { try { // get the template data for rendering String templateText = getDataResourceText(dataResource, targetMimeTypeId, locale, templateContext, delegator, cache); // if use web analytics. if (UtilValidate.isNotEmpty(webAnalytics)) { StringBuffer newTemplateText = new StringBuffer(templateText); String webAnalyticsCode = "<script language=\"JavaScript\" type=\"text/javascript\">"; for (GenericValue webAnalytic : webAnalytics) { StringWrapper wrapString = StringUtil .wrapString((String) webAnalytic.get("webAnalyticsCode")); webAnalyticsCode += wrapString.toString(); } webAnalyticsCode += "</script>"; newTemplateText.insert(templateText.lastIndexOf("</head>"), webAnalyticsCode); templateText = newTemplateText.toString(); } // render the FTL template FreeMarkerWorker.renderTemplate("DataResource:" + dataResourceId, templateText, templateContext, out); } catch (TemplateException e) { throw new GeneralException("Error rendering FTL template", e); } } else if ("XSLT".equals(dataTemplateTypeId)) { File sourceFileLocation = null; File targetFileLocation = new File( System.getProperty("ofbiz.home") + "/runtime/tempfiles/docbook.css"); if (templateContext.get("visualThemeId") != null) { Map<String, Object> layoutSettings = UtilGenerics .checkMap(templateContext.get("layoutSettings")); List<String> docbookStyleSheets = UtilGenerics .checkList(layoutSettings.get("VT_DOCBOOKSTYLESHEET")); String docbookStyleLocation = docbookStyleSheets.get(0); sourceFileLocation = new File( System.getProperty("ofbiz.home") + "/themes" + docbookStyleLocation); } if (sourceFileLocation != null && sourceFileLocation.exists()) { UtilMisc.copyFile(sourceFileLocation, targetFileLocation); } else { String defaultVisualThemeId = EntityUtilProperties.getPropertyValue("general", "VISUAL_THEME", delegator); if (defaultVisualThemeId != null) { GenericValue themeValue = EntityQuery.use(delegator).from("VisualThemeResource") .where("visualThemeId", defaultVisualThemeId, "resourceTypeEnumId", "VT_DOCBOOKSTYLESHEET", "sequenceId", "01") .cache().queryOne(); sourceFileLocation = new File( System.getProperty("ofbiz.home") + "/themes" + themeValue.get("resourceValue")); UtilMisc.copyFile(sourceFileLocation, targetFileLocation); } } // get the template data for rendering String templateLocation = DataResourceWorker .getContentFile(dataResource.getString("dataResourceTypeId"), dataResource.getString("objectInfo"), (String) templateContext.get("contextRoot")) .toString(); // render the XSLT template and file String outDoc = null; try { outDoc = XslTransform.renderTemplate(templateLocation, (String) templateContext.get("docFile")); } catch (TransformerException c) { Debug.logError("XSL TransformerException: " + c.getMessage(), module); } out.append(outDoc); // Screen Widget template } else if ("SCREEN_COMBINED".equals(dataTemplateTypeId)) { try { MapStack<String> context = MapStack.create(templateContext); context.put("locale", locale); // prepare the map for preRenderedContent String textData = (String) context.get("textData"); if (UtilValidate.isNotEmpty(textData)) { Map<String, Object> prc = FastMap.newInstance(); String mapKey = (String) context.get("mapKey"); if (mapKey != null) { prc.put(mapKey, mapKey); } prc.put("body", textData); // used for default screen defs context.put("preRenderedContent", prc); } // get the screen renderer; or create a new one ScreenRenderer screens = (ScreenRenderer) context.get("screens"); if (screens == null) { // TODO: replace "screen" to support dynamic rendering of different output ScreenStringRenderer screenStringRenderer = new MacroScreenRenderer( EntityUtilProperties.getPropertyValue("widget", "screen.name", delegator), EntityUtilProperties.getPropertyValue("widget", "screen.screenrenderer", delegator)); screens = new ScreenRenderer(out, context, screenStringRenderer); screens.getContext().put("screens", screens); } // render the screen ModelScreen modelScreen = null; ScreenStringRenderer renderer = screens.getScreenStringRenderer(); String combinedName = dataResource.getString("objectInfo"); if ("URL_RESOURCE".equals(dataResource.getString("dataResourceTypeId")) && UtilValidate.isNotEmpty(combinedName) && combinedName.startsWith("component://")) { modelScreen = ScreenFactory.getScreenFromLocation(combinedName); } else { // stored in a single file, long or short text Document screenXml = UtilXml.readXmlDocument(getDataResourceText(dataResource, targetMimeTypeId, locale, templateContext, delegator, cache), true, true); Map<String, ModelScreen> modelScreenMap = ScreenFactory.readScreenDocument(screenXml, "DataResourceId: " + dataResource.getString("dataResourceId")); if (UtilValidate.isNotEmpty(modelScreenMap)) { Map.Entry<String, ModelScreen> entry = modelScreenMap.entrySet().iterator().next(); // get first entry, only one screen allowed per file modelScreen = entry.getValue(); } } if (UtilValidate.isNotEmpty(modelScreen)) { modelScreen.renderScreenString(out, context, renderer); } else { throw new GeneralException( "The dataResource file [" + dataResourceId + "] could not be found"); } } catch (SAXException e) { throw new GeneralException("Error rendering Screen template", e); } catch (ParserConfigurationException e) { throw new GeneralException("Error rendering Screen template", e); } catch (TemplateException e) { throw new GeneralException("Error creating Screen renderer", e); } } else { throw new GeneralException( "The dataTemplateTypeId [" + dataTemplateTypeId + "] is not yet supported"); } } }
From source file:org.openadaptor.auxil.processor.xml.XsltProcessor.java
/** * Trys to load the XSLT from the file defined in the properties (will also try to find the file on the classpath if * it can)./*from w ww.java 2 s. c o m*/ * * @throws ValidationException * if the XSLT file is not defined in the properties, the file cannot be found or there was an error parsing * it */ private void loadXSLT() { if (xsltFile == null) throw new ValidationException("xsltFile property not set", this); // if the file doesn't exist try to get it via the classpath URL url = FileUtils.toURL(xsltFile); if (url == null) throw new ValidationException("File not found: " + xsltFile, this); // load the transform try { TransformerFactory factory = TransformerFactory.newInstance(); ErrorListener errorListener = new ErrorListener() { public void warning(TransformerException exception) throws TransformerException { log.warn(exception.getMessage(), exception); } public void fatalError(TransformerException exception) throws TransformerException { throw exception; } public void error(TransformerException exception) throws TransformerException { throw exception; } }; factory.setErrorListener(errorListener); transform = factory.newTransformer(new StreamSource(url.getPath())); log.info("Loaded XSLT [" + xsltFile + "] successfully"); } catch (TransformerConfigurationException e) { throw new ValidationException("Failed to load XSLT: " + e.getMessage(), this); } }
From source file:org.openadaptor.auxil.processor.xml.XsltProcessor.java
/** * Applies the transform to the Dom4J document * //from w w w . j a v a 2 s .co m * @param d * the document to transform * * @return an array containing a single XML string representing the transformed document */ private Object[] transform(Document d) { try { return new String[] { transform(transform, d) }; } catch (TransformerException e) { throw new ProcessingException("Transform failed: " + e.getMessage(), this); } }
From source file:org.openhealthtools.openatna.jaxb21.JaxbIOFactory.java
private StreamResult transform(Document doc, OutputStream out) throws IOException { TransformerFactory tf = TransformerFactory.newInstance(); Transformer t = null;/*from w ww . ja v a 2 s . c o m*/ try { t = tf.newTransformer(); t.setOutputProperty(OutputKeys.INDENT, "yes"); t.setOutputProperty(OutputKeys.METHOD, "xml"); t.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); } catch (TransformerConfigurationException tce) { assert (false); } DOMSource doms = new DOMSource(doc); StreamResult sr = new StreamResult(out); try { t.transform(doms, sr); } catch (TransformerException te) { throw new IOException(te.getMessage()); } return sr; }
From source file:org.parosproxy.paros.extension.newreport.ReportGenerator.java
public static File XMLToHtml(Document xmlDocument, String infilexsl, File outFile) { File stylesheet = null;//ww w.ja v a 2 s .com outFile = new File(outFile.getAbsolutePath()); try { stylesheet = new File(infilexsl); DOMSource source = new DOMSource(xmlDocument); // Use a Transformer for output TransformerFactory tFactory = TransformerFactory.newInstance(); StreamSource stylesource = new StreamSource(stylesheet); Transformer transformer = tFactory.newTransformer(stylesource); // Make the transformation and write to the output file StreamResult result = new StreamResult(outFile); transformer.transform(source, result); } catch (TransformerException e) { logger.error(e.getMessage(), e); } return outFile; }
From source file:org.patientview.patientview.EmailUtils.java
private static String getNodeAsString(Node node) { String nodeAsString = ""; try {/*from w w w . j av a 2 s. c o m*/ // Set up the output transformer TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer trans = transformerFactory.newTransformer(); trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); trans.setOutputProperty(OutputKeys.INDENT, "yes"); // Print the DOM node StringWriter sw = new StringWriter(); StreamResult result = new StreamResult(sw); DOMSource source = new DOMSource(node); trans.transform(source, result); String xmlString = sw.toString(); nodeAsString += xmlString; } catch (TransformerException e) { LOGGER.error("Failed to transform node because {}.", e.getMessage()); if (LOGGER.isDebugEnabled()) { e.printStackTrace(); } // Just return the blank string } return nodeAsString; }