use of org.apache.ofbiz.webapp.view.ViewHandlerException in project ofbiz-framework by apache.
the class ScreenFopViewHandler method render.
/**
* @see org.apache.ofbiz.webapp.view.ViewHandler#render(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
*/
@Override
public void render(String name, String page, String info, String contentType, String encoding, HttpServletRequest request, HttpServletResponse response) throws ViewHandlerException {
Delegator delegator = (Delegator) request.getAttribute("delegator");
VisualTheme visualTheme = UtilHttp.getVisualTheme(request);
ModelTheme modelTheme = visualTheme.getModelTheme();
// render and obtain the XSL-FO
Writer writer = new StringWriter();
try {
ScreenStringRenderer screenStringRenderer = new MacroScreenRenderer(modelTheme.getType(getName()), modelTheme.getScreenRendererLocation(getName()));
FormStringRenderer formStringRenderer = new MacroFormRenderer(modelTheme.getFormRendererLocation(getName()), request, response);
// TODO: uncomment these lines when the renderers are implemented
// TreeStringRenderer treeStringRenderer = new MacroTreeRenderer(modelTheme.getTreeRendererLocation(getName()), writer);
// MenuStringRenderer menuStringRenderer = new MacroMenuRenderer(modelTheme.getMenuRendererLocation(getName()), writer);
ScreenRenderer screens = new ScreenRenderer(writer, null, screenStringRenderer);
screens.populateContextForRequest(request, response, servletContext);
// this is the object used to render forms from their definitions
screens.getContext().put("formStringRenderer", formStringRenderer);
screens.getContext().put("simpleEncoder", UtilCodec.getEncoder(modelTheme.getEncoder(getName())));
screens.render(page);
} catch (IOException | GeneralException | SAXException | ParserConfigurationException | TemplateException e) {
renderError("Problems with the response writer/output stream", e, "[Not Yet Rendered]", request, response);
return;
}
// set the input source (XSL-FO) and generate the output stream of contentType
String screenOutString = writer.toString();
if (!screenOutString.startsWith("<?xml")) {
screenOutString = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + screenOutString;
}
if (Debug.verboseOn())
Debug.logVerbose("XSL:FO Screen Output: " + screenOutString, module);
if (UtilValidate.isEmpty(contentType)) {
contentType = modelTheme.getContentType(getName());
}
// get encryption related parameters
FOUserAgent foUserAgent = null;
String userPassword = request.getParameter("userPassword");
String ownerPassword = request.getParameter("ownerPassword");
boolean allowPrint = Boolean.parseBoolean(UtilValidate.isEmpty(request.getParameter("allowPrint")) ? ApacheFopWorker.getAllowPrintDefault() : request.getParameter("allowPrint"));
boolean allowCopyContent = Boolean.parseBoolean(UtilValidate.isEmpty(request.getParameter("allowCopyContent")) ? ApacheFopWorker.getAllowCopyContentDefault() : request.getParameter("allowCopyContent"));
boolean allowEditContent = Boolean.parseBoolean(UtilValidate.isEmpty(request.getParameter("allowEditContent")) ? ApacheFopWorker.getAllowEditContentDefault() : request.getParameter("allowEditContent"));
boolean allowEditAnnotations = Boolean.parseBoolean(UtilValidate.isEmpty(request.getParameter("allowEditAnnotations")) ? ApacheFopWorker.getAllowEditAnnotationsDefault() : request.getParameter("allowEditAnnotations"));
if (UtilValidate.isNotEmpty(userPassword) || UtilValidate.isNotEmpty(ownerPassword) || !allowPrint || !allowCopyContent || allowEditContent || !allowEditAnnotations) {
int encryptionLength = 128;
try {
encryptionLength = Integer.parseInt(request.getParameter("encryption-length"));
} catch (NumberFormatException e) {
try {
encryptionLength = Integer.parseInt(ApacheFopWorker.getEncryptionLengthDefault());
} catch (NumberFormatException e1) {
// ignore
}
}
boolean encryptMetadata = Boolean.parseBoolean(UtilValidate.isEmpty(request.getParameter("encrypt-metadata")) ? ApacheFopWorker.getEncryptMetadataDefault() : request.getParameter("encrypt-metadata"));
boolean allowFillInForms = Boolean.parseBoolean(UtilValidate.isEmpty(request.getParameter("allowFillInForms")) ? ApacheFopWorker.getAllowFillInFormsDefault() : request.getParameter("allowFillInForms"));
boolean allowAccessContent = Boolean.parseBoolean(UtilValidate.isEmpty(request.getParameter("allowAccessContent")) ? ApacheFopWorker.getAllowAccessContentDefault() : request.getParameter("allowAccessContent"));
boolean allowAssembleDocument = Boolean.parseBoolean(UtilValidate.isEmpty(request.getParameter("allowAssembleDocument")) ? ApacheFopWorker.getAllowAssembleDocumentDefault() : request.getParameter("allowAssembleDocument"));
boolean allowPrintHq = Boolean.parseBoolean(UtilValidate.isEmpty(request.getParameter("allowPrintHq")) ? ApacheFopWorker.getAllowPrintHqDefault() : request.getParameter("allowPrintHq"));
FopFactory fopFactory = ApacheFopWorker.getFactoryInstance();
foUserAgent = fopFactory.newFOUserAgent();
PDFEncryptionParams pdfEncryptionParams = new PDFEncryptionParams(userPassword, ownerPassword, allowPrint, allowCopyContent, allowEditContent, allowEditAnnotations, encryptMetadata);
pdfEncryptionParams.setAllowFillInForms(allowFillInForms);
pdfEncryptionParams.setAllowAccessContent(allowAccessContent);
pdfEncryptionParams.setAllowAssembleDocument(allowAssembleDocument);
pdfEncryptionParams.setAllowPrintHq(allowPrintHq);
pdfEncryptionParams.setEncryptionLengthInBits(encryptionLength);
foUserAgent.getRendererOptions().put(PDFEncryptionOption.ENCRYPTION_PARAMS, pdfEncryptionParams);
}
Reader reader = new StringReader(screenOutString);
StreamSource src = new StreamSource(reader);
ByteArrayOutputStream out = new ByteArrayOutputStream();
/* Debug area, uncomment this to view the xml file generate before analyse by fop
try {
java.io.FileWriter fw = new java.io.FileWriter(new java.io.File("/tmp/temp.xsl.fo"));
fw.write(screenOutString);
fw.close();
} catch (IOException e) {
Debug.logError(e, "Couldn't save xls debug file: " + e.toString(), module);
}
*/
try {
Fop fop = ApacheFopWorker.createFopInstance(out, contentType, foUserAgent);
ApacheFopWorker.transform(src, null, fop);
} catch (Exception e) {
renderError("Unable to transform FO file", e, screenOutString, request, response);
return;
}
// set the content type and length
response.setContentType(contentType);
response.setContentLength(out.size());
// write to the browser
try {
out.writeTo(response.getOutputStream());
response.getOutputStream().flush();
} catch (IOException e) {
renderError("Unable to write to OutputStream", e, screenOutString, request, response);
}
}
use of org.apache.ofbiz.webapp.view.ViewHandlerException in project ofbiz-framework by apache.
the class ScreenFopViewHandler method renderError.
protected void renderError(String msg, Exception e, String screenOutString, HttpServletRequest request, HttpServletResponse response) throws ViewHandlerException {
Debug.logError(msg + ": " + e + "; Screen XSL:FO text was:\n" + screenOutString, module);
try {
Delegator delegator = (Delegator) request.getAttribute("delegator");
Writer writer = new StringWriter();
VisualTheme visualTheme = UtilHttp.getVisualTheme(request);
ModelTheme modelTheme = visualTheme.getModelTheme();
ScreenStringRenderer screenStringRenderer = new MacroScreenRenderer(modelTheme.getType("screen"), modelTheme.getScreenRendererLocation("screen"));
ScreenRenderer screens = new ScreenRenderer(writer, null, screenStringRenderer);
screens.populateContextForRequest(request, response, servletContext);
screens.getContext().put("errorMessage", msg + ": " + e);
screens.render(DEFAULT_ERROR_TEMPLATE);
response.setContentType("text/html");
response.getWriter().write(writer.toString());
writer.close();
} catch (IOException | GeneralException | SAXException | ParserConfigurationException | TemplateException x) {
Debug.logError("Multiple errors rendering FOP", module);
throw new ViewHandlerException("Multiple errors rendering FOP", x);
}
}
use of org.apache.ofbiz.webapp.view.ViewHandlerException in project ofbiz-framework by apache.
the class MacroScreenViewHandler method render.
public void render(String name, String page, String info, String contentType, String encoding, HttpServletRequest request, HttpServletResponse response) throws ViewHandlerException {
try {
Writer writer = response.getWriter();
VisualTheme visualTheme = UtilHttp.getVisualTheme(request);
ModelTheme modelTheme = visualTheme.getModelTheme();
Delegator delegator = (Delegator) request.getAttribute("delegator");
// compress output if configured to do so
if (UtilValidate.isEmpty(encoding)) {
encoding = modelTheme.getEncoding(getName());
}
boolean compressOutput = "compressed".equals(encoding);
if (!compressOutput) {
compressOutput = "true".equals(modelTheme.getCompress(getName()));
}
if (!compressOutput && this.servletContext != null) {
compressOutput = "true".equals(this.servletContext.getAttribute("compressHTML"));
}
if (compressOutput) {
// StandardCompress defaults to a 2k buffer. That could be increased
// to speed up output.
writer = new StandardCompress().getWriter(writer, null);
}
MapStack<String> context = MapStack.create();
ScreenRenderer.populateContextForRequest(context, null, request, response, servletContext);
ScreenStringRenderer screenStringRenderer = loadRenderers(request, response, context, writer);
ScreenRenderer screens = new ScreenRenderer(writer, context, screenStringRenderer);
context.put("screens", screens);
context.put("simpleEncoder", UtilCodec.getEncoder(visualTheme.getModelTheme().getEncoder(getName())));
screenStringRenderer.renderScreenBegin(writer, context);
screens.render(page);
screenStringRenderer.renderScreenEnd(writer, context);
writer.flush();
} catch (TemplateException e) {
Debug.logError(e, "Error initializing screen renderer", module);
throw new ViewHandlerException(e.getMessage());
} catch (IOException e) {
throw new ViewHandlerException("Error in the response writer/output stream: " + e.toString(), e);
} catch (SAXException | ParserConfigurationException e) {
throw new ViewHandlerException("XML Error rendering page: " + e.toString(), e);
} catch (GeneralException e) {
throw new ViewHandlerException("Lower level error rendering page: " + e.toString(), e);
}
}
use of org.apache.ofbiz.webapp.view.ViewHandlerException in project ofbiz-framework by apache.
the class FreeMarkerViewHandler method render.
public void render(String name, String page, String info, String contentType, String encoding, HttpServletRequest request, HttpServletResponse response) throws ViewHandlerException {
if (UtilValidate.isEmpty(page))
throw new ViewHandlerException("Invalid template source");
// make the root context (data model) for freemarker
MapStack<String> context = MapStack.create();
prepOfbizRoot(context, request, response);
// process the template & flush the output
try {
if (page.startsWith("component://")) {
FreeMarkerWorker.renderTemplate(page, context, response.getWriter());
} else {
// backwards compatibility
Template template = config.getTemplate(page);
FreeMarkerWorker.renderTemplate(template, context, response.getWriter());
}
response.flushBuffer();
} catch (TemplateException te) {
throw new ViewHandlerException("Problems processing Freemarker template", te);
} catch (IOException ie) {
throw new ViewHandlerException("Problems writing to output stream", ie);
}
}
use of org.apache.ofbiz.webapp.view.ViewHandlerException in project ofbiz-framework by apache.
the class SimpleContentViewHandler method render.
/**
* @see org.apache.ofbiz.webapp.view.ViewHandler#render(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
*/
public void render(String name, String page, String info, String contentType, String encoding, HttpServletRequest request, HttpServletResponse response) throws ViewHandlerException {
LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
HttpSession session = request.getSession();
GenericValue userLogin = (GenericValue) session.getAttribute("userLogin");
String contentId = request.getParameter("contentId");
String rootContentId = request.getParameter("rootContentId");
String mapKey = request.getParameter("mapKey");
String contentAssocTypeId = request.getParameter("contentAssocTypeId");
String fromDateStr = request.getParameter("fromDate");
String dataResourceId = request.getParameter("dataResourceId");
String contentRevisionSeqId = request.getParameter("contentRevisionSeqId");
String mimeTypeId = request.getParameter("mimeTypeId");
Locale locale = UtilHttp.getLocale(request);
String webSiteId = WebSiteWorker.getWebSiteId(request);
try {
if (Debug.verboseOn())
Debug.logVerbose("dataResourceId:" + dataResourceId, module);
Delegator delegator = (Delegator) request.getAttribute("delegator");
if (UtilValidate.isEmpty(dataResourceId)) {
if (UtilValidate.isEmpty(contentRevisionSeqId)) {
if (UtilValidate.isEmpty(mapKey) && UtilValidate.isEmpty(contentAssocTypeId)) {
if (UtilValidate.isNotEmpty(contentId)) {
GenericValue content = EntityQuery.use(delegator).from("Content").where("contentId", contentId).cache().queryOne();
dataResourceId = content.getString("dataResourceId");
}
if (Debug.verboseOn())
Debug.logVerbose("dataResourceId:" + dataResourceId, module);
} else {
Timestamp fromDate = null;
if (UtilValidate.isNotEmpty(fromDateStr)) {
try {
fromDate = UtilDateTime.stringToTimeStamp(fromDateStr, null, locale);
} catch (ParseException e) {
fromDate = UtilDateTime.nowTimestamp();
}
}
List<String> assocList = null;
if (UtilValidate.isNotEmpty(contentAssocTypeId)) {
assocList = UtilMisc.toList(contentAssocTypeId);
}
GenericValue content = ContentWorker.getSubContent(delegator, contentId, mapKey, null, null, assocList, fromDate);
dataResourceId = content.getString("dataResourceId");
if (Debug.verboseOn())
Debug.logVerbose("dataResourceId:" + dataResourceId, module);
}
} else {
GenericValue contentRevisionItem = EntityQuery.use(delegator).from("ContentRevisionItem").where("contentId", rootContentId, "itemContentId", contentId, "contentRevisionSeqId", contentRevisionSeqId).cache().queryOne();
if (contentRevisionItem == null) {
throw new ViewHandlerException("ContentRevisionItem record not found for contentId=" + rootContentId + ", contentRevisionSeqId=" + contentRevisionSeqId + ", itemContentId=" + contentId);
}
dataResourceId = contentRevisionItem.getString("newDataResourceId");
if (Debug.verboseOn())
Debug.logVerbose("contentRevisionItem:" + contentRevisionItem, module);
if (Debug.verboseOn())
Debug.logVerbose("contentId=" + rootContentId + ", contentRevisionSeqId=" + contentRevisionSeqId + ", itemContentId=" + contentId, module);
if (Debug.verboseOn())
Debug.logVerbose("dataResourceId:" + dataResourceId, module);
}
}
if (UtilValidate.isNotEmpty(dataResourceId)) {
GenericValue dataResource = EntityQuery.use(delegator).from("DataResource").where("dataResourceId", dataResourceId).cache().queryOne();
// DEJ20080717: why are we rendering the DataResource directly instead of rendering the content?
ByteBuffer byteBuffer = DataResourceWorker.getContentAsByteBuffer(delegator, dataResourceId, https, webSiteId, locale, rootDir);
ByteArrayInputStream bais = new ByteArrayInputStream(byteBuffer.array());
// setup character encoding and content type
String charset = dataResource.getString("characterSetId");
if (UtilValidate.isEmpty(charset)) {
charset = encoding;
}
if (UtilValidate.isEmpty(mimeTypeId)) {
mimeTypeId = DataResourceWorker.getMimeType(dataResource);
if ("text/html".equalsIgnoreCase(mimeTypeId)) {
mimeTypeId = "application/octet-stream";
}
}
// setup content type
String contentType2 = UtilValidate.isNotEmpty(mimeTypeId) ? mimeTypeId + "; charset=" + charset : contentType;
String fileName = null;
if (UtilValidate.isNotEmpty(dataResource.getString("dataResourceName"))) {
// spaces in filenames can be a problem
fileName = dataResource.getString("dataResourceName").replace(" ", "_");
}
// see if data resource is public or not
String isPublic = dataResource.getString("isPublic");
if (UtilValidate.isEmpty(isPublic)) {
isPublic = "N";
}
// get the permission service required for streaming data; default is always the genericContentPermission
String permissionService = EntityUtilProperties.getPropertyValue("content", "stream.permission.service", "genericContentPermission", delegator);
// not public check security
if (!"Y".equalsIgnoreCase(isPublic)) {
// do security check
Map<String, ? extends Object> permSvcCtx = UtilMisc.toMap("userLogin", userLogin, "locale", locale, "mainAction", "VIEW", "contentId", contentId);
Map<String, Object> permSvcResp;
try {
permSvcResp = dispatcher.runSync(permissionService, permSvcCtx);
} catch (GenericServiceException e) {
Debug.logError(e, module);
request.setAttribute("_ERROR_MESSAGE_", e.getMessage());
throw new ViewHandlerException(e.getMessage());
}
if (ServiceUtil.isError(permSvcResp)) {
String errorMsg = ServiceUtil.getErrorMessage(permSvcResp);
Debug.logError(errorMsg, module);
request.setAttribute("_ERROR_MESSAGE_", errorMsg);
throw new ViewHandlerException(errorMsg);
}
// no service errors; now check the actual response
Boolean hasPermission = (Boolean) permSvcResp.get("hasPermission");
if (!hasPermission.booleanValue()) {
String errorMsg = (String) permSvcResp.get("failMessage");
Debug.logError(errorMsg, module);
request.setAttribute("_ERROR_MESSAGE_", errorMsg);
throw new ViewHandlerException(errorMsg);
}
}
UtilHttp.streamContentToBrowser(response, bais, byteBuffer.limit(), contentType2, fileName);
}
} catch (IOException | GeneralException e) {
throw new ViewHandlerException(e.getMessage());
}
}
Aggregations