use of org.apache.ofbiz.widget.renderer.ScreenRenderer in project ofbiz-framework by apache.
the class DataResourceWorker method renderDataResourceAsText.
public static void renderDataResourceAsText(LocalDispatcher dispatcher, Delegator delegator, String dataResourceId, Appendable out, Map<String, Object> templateContext, Locale locale, String targetMimeTypeId, boolean cache, List<GenericValue> webAnalytics) throws GeneralException, IOException {
if (delegator == null) {
delegator = dispatcher.getDelegator();
}
if (dataResourceId == null) {
throw new GeneralException("Cannot lookup data resource with for a null dataResourceId");
}
if (templateContext == null) {
templateContext = new HashMap<>();
}
if (UtilValidate.isEmpty(targetMimeTypeId)) {
targetMimeTypeId = "text/html";
}
if (locale == null) {
locale = Locale.getDefault();
}
// FIXME correctly propagate the theme, then fixes also the related FIXME below
VisualTheme visualTheme = ThemeFactory.getVisualThemeFromId("COMMON");
ModelTheme modelTheme = visualTheme.getModelTheme();
// 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, cache);
} 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
boolean useTemplateCache = cache && !UtilProperties.getPropertyAsBoolean("content", "disable.ftl.template.cache", false);
// Do not use dataResource.lastUpdatedStamp for dataResource template caching as it may use ftl file or electronicText
// If dataResource using ftl file use nowTimestamp to avoid freemarker caching
Timestamp lastUpdatedStamp = UtilDateTime.nowTimestamp();
// If dataResource is type of ELECTRONIC_TEXT then only use the lastUpdatedStamp of electronicText entity for freemarker caching
if ("ELECTRONIC_TEXT".equals(dataResource.getString("dataResourceTypeId"))) {
GenericValue electronicText = dataResource.getRelatedOne("ElectronicText", true);
if (electronicText != null) {
lastUpdatedStamp = electronicText.getTimestamp("lastUpdatedStamp");
}
}
FreeMarkerWorker.renderTemplateFromString("delegator:" + delegator.getDelegatorName() + ":DataResource:" + dataResourceId, templateText, templateContext, out, lastUpdatedStamp.getTime(), useTemplateCache);
} catch (TemplateException e) {
throw new GeneralException("Error rendering FTL template", e);
}
} else if ("XSLT".equals(dataTemplateTypeId)) {
File targetFileLocation = new File(System.getProperty("ofbiz.home") + "/runtime/tempfiles/docbook.css");
// This is related with the other FIXME above: we need to correctly propagate the theme.
String defaultVisualThemeId = EntityUtilProperties.getPropertyValue("general", "VISUAL_THEME", delegator);
visualTheme = ThemeFactory.getVisualThemeFromId(defaultVisualThemeId);
modelTheme = visualTheme.getModelTheme();
String docbookStylesheet = modelTheme.getProperty("VT_DOCBOOKSTYLESHEET").toString();
File sourceFileLocation = new File(System.getProperty("ofbiz.home") + "/themes" + docbookStylesheet.substring(1, docbookStylesheet.length() - 1));
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 = new HashMap<>();
String mapKey = (String) context.get("mapKey");
if (mapKey != null) {
prc.put(mapKey, mapKey);
}
// used for default screen defs
prc.put("body", textData);
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(modelTheme.getType("screen"), modelTheme.getScreenRendererLocation("screen"));
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)) {
// get first entry, only one screen allowed per file
Map.Entry<String, ModelScreen> entry = modelScreenMap.entrySet().iterator().next();
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 | ParserConfigurationException e) {
throw new GeneralException("Error rendering Screen template", e);
} catch (TemplateException e) {
throw new GeneralException("Error creating Screen renderer", e);
}
} else if ("FORM_COMBINED".equals(dataTemplateTypeId)) {
try {
Map<String, Object> context = UtilGenerics.checkMap(templateContext.get("globalContext"));
context.put("locale", locale);
context.put("simpleEncoder", UtilCodec.getEncoder(modelTheme.getEncoder("screen")));
HttpServletRequest request = (HttpServletRequest) context.get("request");
HttpServletResponse response = (HttpServletResponse) context.get("response");
ModelForm modelForm = null;
ModelReader entityModelReader = delegator.getModelReader();
String formText = getDataResourceText(dataResource, targetMimeTypeId, locale, templateContext, delegator, cache);
Document formXml = UtilXml.readXmlDocument(formText, true, true);
Map<String, ModelForm> modelFormMap = FormFactory.readFormDocument(formXml, entityModelReader, dispatcher.getDispatchContext(), null);
if (UtilValidate.isNotEmpty(modelFormMap)) {
// get first entry, only one form allowed per file
Map.Entry<String, ModelForm> entry = modelFormMap.entrySet().iterator().next();
modelForm = entry.getValue();
}
String formrenderer = modelTheme.getFormRendererLocation("screen");
MacroFormRenderer renderer = new MacroFormRenderer(formrenderer, request, response);
FormRenderer formRenderer = new FormRenderer(modelForm, renderer);
formRenderer.render(out, context);
} catch (SAXException | ParserConfigurationException e) {
throw new GeneralException("Error rendering Screen template", e);
} catch (TemplateException e) {
throw new GeneralException("Error creating Screen renderer", e);
} catch (Exception e) {
throw new GeneralException("Error rendering Screen template", e);
}
} else {
throw new GeneralException("The dataTemplateTypeId [" + dataTemplateTypeId + "] is not yet supported");
}
}
}
use of org.apache.ofbiz.widget.renderer.ScreenRenderer in project ofbiz-framework by apache.
the class OutputServices method createFileFromScreen.
public static Map<String, Object> createFileFromScreen(DispatchContext dctx, Map<String, ? extends Object> serviceContext) {
Locale locale = (Locale) serviceContext.get("locale");
Delegator delegator = dctx.getDelegator();
VisualTheme visualTheme = (VisualTheme) serviceContext.get("visualTheme");
String screenLocation = (String) serviceContext.remove("screenLocation");
Map<String, Object> screenContext = UtilGenerics.checkMap(serviceContext.remove("screenContext"));
String contentType = (String) serviceContext.remove("contentType");
String filePath = (String) serviceContext.remove("filePath");
String fileName = (String) serviceContext.remove("fileName");
if (UtilValidate.isEmpty(screenContext)) {
screenContext = new HashMap<>();
}
screenContext.put("locale", locale);
if (UtilValidate.isEmpty(contentType)) {
contentType = "application/pdf";
}
try {
MapStack<String> screenContextTmp = MapStack.create();
screenContextTmp.put("locale", locale);
Writer writer = new StringWriter();
// substitute the freemarker variables...
ScreenStringRenderer foScreenStringRenderer = new MacroScreenRenderer(visualTheme.getModelTheme().getType("screenfop"), visualTheme.getModelTheme().getScreenRendererLocation("screenfop"));
ScreenRenderer screensAtt = new ScreenRenderer(writer, screenContextTmp, foScreenStringRenderer);
screensAtt.populateContextForService(dctx, screenContext);
screenContextTmp.putAll(screenContext);
screensAtt.getContext().put("formStringRenderer", foFormRenderer);
screensAtt.render(screenLocation);
// create the input stream for the generation
StreamSource src = new StreamSource(new StringReader(writer.toString()));
// create the output stream for the generation
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Fop fop = ApacheFopWorker.createFopInstance(baos, MimeConstants.MIME_PDF);
ApacheFopWorker.transform(src, null, fop);
baos.flush();
baos.close();
fileName += UtilDateTime.nowAsString();
if ("application/pdf".equals(contentType)) {
fileName += ".pdf";
} else if ("application/postscript".equals(contentType)) {
fileName += ".ps";
} else if ("text/plain".equals(contentType)) {
fileName += ".txt";
}
if (UtilValidate.isEmpty(filePath)) {
filePath = EntityUtilProperties.getPropertyValue("content", "content.output.path", "/output", delegator);
}
File file = new File(filePath, fileName);
FileOutputStream fos = new FileOutputStream(file);
fos.write(baos.toByteArray());
fos.close();
} catch (IOException | TemplateException | GeneralException | SAXException | ParserConfigurationException e) {
Debug.logError(e, "Error rendering [" + contentType + "]: " + e.toString(), module);
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ContentRenderingError", UtilMisc.toMap("contentType", contentType, "errorString", e.toString()), locale));
}
return ServiceUtil.returnSuccess();
}
use of org.apache.ofbiz.widget.renderer.ScreenRenderer in project ofbiz-framework by apache.
the class OutputServices method sendPrintFromScreen.
public static Map<String, Object> sendPrintFromScreen(DispatchContext dctx, Map<String, ? extends Object> serviceContext) {
Locale locale = (Locale) serviceContext.get("locale");
VisualTheme visualTheme = (VisualTheme) serviceContext.get("visualTheme");
String screenLocation = (String) serviceContext.remove("screenLocation");
Map<String, Object> screenContext = UtilGenerics.checkMap(serviceContext.remove("screenContext"));
String contentType = (String) serviceContext.remove("contentType");
String printerContentType = (String) serviceContext.remove("printerContentType");
if (UtilValidate.isEmpty(screenContext)) {
screenContext = new HashMap<>();
}
screenContext.put("locale", locale);
if (UtilValidate.isEmpty(contentType)) {
contentType = "application/postscript";
}
if (UtilValidate.isEmpty(printerContentType)) {
printerContentType = contentType;
}
try {
MapStack<String> screenContextTmp = MapStack.create();
screenContextTmp.put("locale", locale);
Writer writer = new StringWriter();
// substitute the freemarker variables...
ScreenStringRenderer foScreenStringRenderer = new MacroScreenRenderer(visualTheme.getModelTheme().getType("screenfop"), visualTheme.getModelTheme().getScreenRendererLocation("screenfop"));
ScreenRenderer screensAtt = new ScreenRenderer(writer, screenContextTmp, foScreenStringRenderer);
screensAtt.populateContextForService(dctx, screenContext);
screenContextTmp.putAll(screenContext);
screensAtt.getContext().put("formStringRenderer", foFormRenderer);
screensAtt.render(screenLocation);
// create the input stream for the generation
StreamSource src = new StreamSource(new StringReader(writer.toString()));
// create the output stream for the generation
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Fop fop = ApacheFopWorker.createFopInstance(baos, MimeConstants.MIME_PDF);
ApacheFopWorker.transform(src, null, fop);
baos.flush();
baos.close();
// Print is sent
DocFlavor psInFormat = new DocFlavor.INPUT_STREAM(printerContentType);
InputStream bais = new ByteArrayInputStream(baos.toByteArray());
DocAttributeSet docAttributeSet = new HashDocAttributeSet();
List<Object> docAttributes = UtilGenerics.checkList(serviceContext.remove("docAttributes"));
if (UtilValidate.isNotEmpty(docAttributes)) {
for (Object da : docAttributes) {
Debug.logInfo("Adding DocAttribute: " + da, module);
docAttributeSet.add((DocAttribute) da);
}
}
Doc myDoc = new SimpleDoc(bais, psInFormat, docAttributeSet);
PrintService printer = null;
// lookup the print service for the supplied printer name
String printerName = (String) serviceContext.remove("printerName");
if (UtilValidate.isNotEmpty(printerName)) {
PrintServiceAttributeSet printServiceAttributes = new HashPrintServiceAttributeSet();
printServiceAttributes.add(new PrinterName(printerName, locale));
PrintService[] printServices = PrintServiceLookup.lookupPrintServices(null, printServiceAttributes);
if (printServices.length > 0) {
printer = printServices[0];
Debug.logInfo("Using printer: " + printer.getName(), module);
if (!printer.isDocFlavorSupported(psInFormat)) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ContentPrinterNotSupportDocFlavorFormat", UtilMisc.toMap("psInFormat", psInFormat, "printerName", printer.getName()), locale));
}
}
if (printer == null) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ContentPrinterNotFound", UtilMisc.toMap("printerName", printerName), locale));
}
} else {
// if no printer name was supplied, try to get the default printer
printer = PrintServiceLookup.lookupDefaultPrintService();
if (printer != null) {
Debug.logInfo("No printer name supplied, using default printer: " + printer.getName(), module);
}
}
if (printer == null) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ContentPrinterNotAvailable", locale));
}
PrintRequestAttributeSet praset = new HashPrintRequestAttributeSet();
List<Object> printRequestAttributes = UtilGenerics.checkList(serviceContext.remove("printRequestAttributes"));
if (UtilValidate.isNotEmpty(printRequestAttributes)) {
for (Object pra : printRequestAttributes) {
Debug.logInfo("Adding PrintRequestAttribute: " + pra, module);
praset.add((PrintRequestAttribute) pra);
}
}
DocPrintJob job = printer.createPrintJob();
job.print(myDoc, praset);
} catch (PrintException | IOException | TemplateException | GeneralException | SAXException | ParserConfigurationException e) {
Debug.logError(e, "Error rendering [" + contentType + "]: " + e.toString(), module);
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ContentRenderingError", UtilMisc.toMap("contentType", contentType, "errorString", e.toString()), locale));
}
return ServiceUtil.returnSuccess();
}
use of org.apache.ofbiz.widget.renderer.ScreenRenderer in project ofbiz-framework by apache.
the class FoPrintServerEvents method getXslFo.
public static byte[] getXslFo(DispatchContext dctx, String screen, Map<String, Object> parameters) throws GeneralException {
// run as the system user
VisualTheme visualTheme = (VisualTheme) parameters.get("visualTheme");
GenericValue system = null;
try {
system = dctx.getDelegator().findOne("UserLogin", false, "userLoginId", "system");
} catch (GenericEntityException e) {
throw new GeneralException(e.getMessage(), e);
}
parameters.put("userLogin", system);
if (!parameters.containsKey("locale")) {
parameters.put("locale", Locale.getDefault());
}
// render and obtain the XSL-FO
Writer writer = new StringWriter();
try {
ScreenStringRenderer screenStringRenderer = new MacroScreenRenderer(visualTheme.getModelTheme().getType("screen"), visualTheme.getModelTheme().getScreenRendererLocation("screen"));
ScreenRenderer screens = new ScreenRenderer(writer, null, screenStringRenderer);
screens.populateContextForService(dctx, parameters);
screens.render(screen);
} catch (Throwable t) {
throw new GeneralException("Problems rendering FOP XSL-FO", t);
}
return writer.toString().getBytes();
}
Aggregations