use of org.alfresco.service.cmr.repository.TemplateException in project acs-community-packaging by Alfresco.
the class NodeInfoBean method sendNodeInfo.
/**
* Returns information on the node identified by the 'noderef'
* parameter found in the ExternalContext. If no noderef is supplied, then the template
* is executed without context.
* <p>
* The result is the formatted HTML to show on the client.
*/
public void sendNodeInfo() throws IOException {
FacesContext context = FacesContext.getCurrentInstance();
ResponseWriter out = context.getResponseWriter();
Map<String, String> requestMap = context.getExternalContext().getRequestParameterMap();
String strNodeRef = (String) requestMap.get("noderef");
String strTemplate = (String) requestMap.get("template");
if (strTemplate == null || strTemplate.length() == 0) {
strTemplate = "node_summary_panel.ftl";
}
NodeRef nodeRef = null;
if (strNodeRef != null && strNodeRef.length() != 0) {
nodeRef = new NodeRef(strNodeRef);
if (this.getNodeService().exists(nodeRef) == false) {
out.write("<span class='errorMessage'>Node could not be found in the repository!</span>");
return;
}
}
try {
Repository.getServiceRegistry(context).getTemplateService().processTemplate("/alfresco/templates/client/" + strTemplate, getModel(nodeRef, requestMap), out);
} catch (TemplateException ex) {
// Try to catch TransformerInfoException to display it in NodeInfo pane.
// Fix bug reported in https://issues.alfresco.com/jira/browse/ETWOTWO-440
Throwable cause = ex.getCause();
while (cause != null) {
cause = cause.getCause();
if (cause instanceof TransformerInfoException) {
out.write("<tr><td colspan=\"2\"><span class='errorMessage'>" + cause.getMessage() + "</span></td></tr>");
return;
}
}
throw ex;
}
}
use of org.alfresco.service.cmr.repository.TemplateException in project acs-community-packaging by Alfresco.
the class BaseTemplateContentServlet method processTemplateRequest.
/**
* Processes the template request using the current context i.e. no
* authentication checks are made, it is presumed they have already
* been done.
*
* @param req The HTTP request
* @param res The HTTP response
* @param redirectToLogin Flag to determine whether to redirect to the login
* page if the user does not have the correct permissions
*/
protected void processTemplateRequest(HttpServletRequest req, HttpServletResponse res, boolean redirectToLogin) throws ServletException, IOException {
Log logger = getLogger();
String uri = req.getRequestURI();
if (logger.isDebugEnabled()) {
String queryString = req.getQueryString();
logger.debug("Processing URL: " + uri + ((queryString != null && queryString.length() > 0) ? ("?" + queryString) : ""));
}
uri = uri.substring(req.getContextPath().length());
StringTokenizer t = new StringTokenizer(uri, "/");
int tokenCount = t.countTokens();
// skip servlet name
t.nextToken();
NodeRef nodeRef = null;
NodeRef templateRef = null;
try {
String contentPath = req.getParameter(ARG_CONTEXT_PATH);
if (contentPath != null && contentPath.length() != 0) {
// process the name based path to resolve the NodeRef
PathRefInfo pathInfo = resolveNamePath(getServletContext(), contentPath);
nodeRef = pathInfo.NodeRef;
} else if (tokenCount > 3) {
// get NodeRef to the content from the URL elements
StoreRef storeRef = new StoreRef(t.nextToken(), t.nextToken());
nodeRef = new NodeRef(storeRef, t.nextToken());
}
// get NodeRef to the template if supplied
String templatePath = req.getParameter(ARG_TEMPLATE_PATH);
if (templatePath != null && templatePath.length() != 0) {
// process the name based path to resolve the NodeRef
PathRefInfo pathInfo = resolveNamePath(getServletContext(), templatePath);
templateRef = pathInfo.NodeRef;
} else if (tokenCount >= 7) {
StoreRef storeRef = new StoreRef(t.nextToken(), t.nextToken());
templateRef = new NodeRef(storeRef, t.nextToken());
}
} catch (AccessDeniedException err) {
if (redirectToLogin) {
if (logger.isDebugEnabled())
logger.debug("Redirecting to login page...");
redirectToLoginPage(req, res, getServletContext());
} else {
if (logger.isDebugEnabled())
logger.debug("Returning 403 Forbidden error...");
res.sendError(HttpServletResponse.SC_FORBIDDEN);
}
return;
}
// TODO: should this default to something else?
if (nodeRef == null && templateRef != null) {
nodeRef = templateRef;
}
if (nodeRef == null) {
throw new TemplateException("Not enough elements supplied in URL or no 'path' argument specified.");
}
// get the services we need to retrieve the content
ServiceRegistry serviceRegistry = getServiceRegistry(getServletContext());
NodeService nodeService = serviceRegistry.getNodeService();
TemplateService templateService = serviceRegistry.getTemplateService();
PermissionService permissionService = serviceRegistry.getPermissionService();
// check that the user has at least READ access on any nodes - else redirect to the login page
if (permissionService.hasPermission(nodeRef, PermissionService.READ) == AccessStatus.DENIED || (templateRef != null && permissionService.hasPermission(templateRef, PermissionService.READ) == AccessStatus.DENIED)) {
if (redirectToLogin) {
if (logger.isDebugEnabled())
logger.debug("Redirecting to login page...");
redirectToLoginPage(req, res, getServletContext());
} else {
if (logger.isDebugEnabled())
logger.debug("Returning 403 Forbidden error...");
res.sendError(HttpServletResponse.SC_FORBIDDEN);
}
return;
}
String mimetype = MIMETYPE_HTML;
if (req.getParameter(ARG_MIMETYPE) != null) {
mimetype = req.getParameter(ARG_MIMETYPE);
}
res.setContentType(mimetype);
try {
UserTransaction txn = null;
try {
txn = serviceRegistry.getTransactionService().getUserTransaction(true);
txn.begin();
// if template not supplied, then use the default against the node
if (templateRef == null) {
if (nodeService.hasAspect(nodeRef, ContentModel.ASPECT_TEMPLATABLE)) {
templateRef = (NodeRef) nodeService.getProperty(nodeRef, ContentModel.PROP_TEMPLATE);
}
if (templateRef == null) {
throw new TemplateException("Template reference not set against node or not supplied in URL.");
}
}
// create the model - put the supplied noderef in as space/document as appropriate
Map<String, Object> model = getModel(serviceRegistry, req, templateRef, nodeRef);
// to be streamed directly to the browser response stream.
try {
templateService.processTemplate(templateRef.toString(), model, res.getWriter());
// commit the transaction
txn.commit();
} catch (SocketException e) {
if (e.getMessage().contains("ClientAbortException")) {
// the client cut the connection - our mission was accomplished apart from a little error message
logger.error("Client aborted stream read:\n node: " + nodeRef + "\n template: " + templateRef);
try {
if (txn != null) {
txn.rollback();
}
} catch (Exception tex) {
}
} else {
throw e;
}
} finally {
res.getWriter().close();
}
} catch (Throwable txnErr) {
try {
if (txn != null) {
txn.rollback();
}
} catch (Exception tex) {
}
throw txnErr;
}
} catch (Throwable err) {
throw new AlfrescoRuntimeException("Error during template servlet processing: " + err.getMessage(), err);
}
}
use of org.alfresco.service.cmr.repository.TemplateException in project alfresco-repository by Alfresco.
the class TemplateServiceImpl method processTemplate.
/**
* @see org.alfresco.service.cmr.repository.TemplateService#processTemplate(java.lang.String, java.lang.String, java.lang.Object, java.io.Writer)
*/
public void processTemplate(String engine, String template, Object model, Writer out) throws TemplateException {
try {
// execute template processor
TemplateProcessor processor = getTemplateProcessor(engine);
processor.process(template, model, out);
} catch (TemplateException terr) {
throw terr;
} catch (Throwable err) {
throw new TemplateException(err.getMessage(), err);
}
}
use of org.alfresco.service.cmr.repository.TemplateException in project alfresco-repository by Alfresco.
the class TemplateServiceImpl method processTemplateString.
/**
* @see org.alfresco.service.cmr.repository.TemplateService#processTemplateString(java.lang.String, java.lang.String, java.lang.Object, java.io.Writer)
*/
public void processTemplateString(String engine, String template, Object model, Writer out) throws TemplateException {
try {
// execute template processor
TemplateProcessor processor = getTemplateProcessor(engine);
processor.processString(template, model, out);
} catch (TemplateException terr) {
throw terr;
} catch (Throwable err) {
throw new TemplateException(err.getMessage(), err);
}
}
use of org.alfresco.service.cmr.repository.TemplateException in project alfresco-repository by Alfresco.
the class StandardRenditionLocationResolverImpl method renderPathTemplate.
private String renderPathTemplate(String pathTemplate, NodeRef sourceNode, NodeRef tempRenditionLocation, NodeRef companyHome) {
NodeService nodeService = serviceRegistry.getNodeService();
FileFolderService fileFolderService = serviceRegistry.getFileFolderService();
final Map<String, Object> root = new HashMap<String, Object>();
List<FileInfo> sourcePathInfo;
String fullSourceName;
String cwd;
try {
// Since the root of the store is typically not a folder, we use company home as the root of this tree
sourcePathInfo = fileFolderService.getNamePath(companyHome, sourceNode);
// Remove the last element (the actual source file name)
FileInfo sourceFileInfo = sourcePathInfo.remove(sourcePathInfo.size() - 1);
fullSourceName = sourceFileInfo.getName();
StringBuilder cwdBuilder = new StringBuilder("/");
for (FileInfo file : sourcePathInfo) {
cwdBuilder.append(file.getName());
cwdBuilder.append('/');
}
cwd = cwdBuilder.toString();
} catch (FileNotFoundException e) {
log.warn("Failed to resolve path to source node: " + sourceNode + ". Default to Company Home");
fullSourceName = nodeService.getPrimaryParent(sourceNode).getQName().getLocalName();
cwd = "/";
}
String trimmedSourceName = fullSourceName;
String sourceExtension = "";
int extensionIndex = fullSourceName.lastIndexOf('.');
if (extensionIndex != -1) {
trimmedSourceName = (extensionIndex == 0) ? "" : fullSourceName.substring(0, extensionIndex);
sourceExtension = (extensionIndex == fullSourceName.length() - 1) ? "" : fullSourceName.substring(extensionIndex + 1);
}
root.put("name", trimmedSourceName);
root.put("extension", sourceExtension);
root.put("date", new SimpleDate(new Date(), SimpleDate.DATETIME));
root.put("cwd", cwd);
TemplateNode companyHomeNode = new TemplateNode(companyHome, serviceRegistry, null);
root.put("companyHome", companyHomeNode);
// Added this to be consistent with the script API
root.put("companyhome", companyHomeNode);
root.put("sourceNode", new TemplateNode(sourceNode, serviceRegistry, null));
root.put("sourceContentType", nodeService.getType(sourceNode).getLocalName());
root.put("renditionContentType", nodeService.getType(tempRenditionLocation).getLocalName());
NodeRef person = serviceRegistry.getPersonService().getPerson(AuthenticationUtil.getFullyAuthenticatedUser());
root.put("person", new TemplateNode(person, serviceRegistry, null));
if (sourceNodeIsXml(sourceNode)) {
try {
Document xml = XMLUtil.parse(sourceNode, serviceRegistry.getContentService());
pathTemplate = buildNamespaceDeclaration(xml) + pathTemplate;
root.put("xml", NodeModel.wrap(xml));
} catch (Exception ex) {
log.warn("Failed to parse XML content into path template model: Node = " + sourceNode);
}
}
if (log.isDebugEnabled()) {
log.debug("Path template model: " + root);
}
String result = null;
try {
if (log.isDebugEnabled()) {
log.debug("Processing " + pathTemplate + " using source node " + cwd + fullSourceName);
}
result = serviceRegistry.getTemplateService().processTemplateString("freemarker", pathTemplate, new SimpleHash(root));
} catch (TemplateException te) {
log.error("Error while trying to process rendition path template: " + pathTemplate);
log.error(te.getMessage(), te);
}
if (log.isDebugEnabled()) {
log.debug("processed pattern " + pathTemplate + " as " + result);
}
return result;
}
Aggregations