Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Aug 30th, 2012  |  syntax: None  |  size: 9.61 KB  |  hits: 8  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. package com.dotmarketing.viewtools;
  2.  
  3. import java.io.ByteArrayInputStream;
  4. import java.io.ByteArrayOutputStream;
  5. import java.io.FileInputStream;
  6. import java.io.InputStreamReader;
  7. import java.util.Date;
  8.  
  9. import javax.servlet.http.HttpServletRequest;
  10. import javax.xml.transform.Source;
  11. import javax.xml.transform.Transformer;
  12. import javax.xml.transform.TransformerConfigurationException;
  13. import javax.xml.transform.TransformerFactory;
  14. import javax.xml.transform.stream.StreamResult;
  15. import javax.xml.transform.stream.StreamSource;
  16.  
  17. import org.apache.velocity.context.Context;
  18. import org.apache.velocity.context.InternalContextAdapterImpl;
  19. import org.apache.velocity.tools.view.context.ViewContext;
  20. import org.apache.velocity.tools.view.tools.ViewTool;
  21.  
  22. import com.dotmarketing.beans.Host;
  23. import com.dotmarketing.beans.Identifier;
  24. import com.dotmarketing.business.APILocator;
  25. import com.dotmarketing.business.Role;
  26. import com.dotmarketing.business.UserAPI;
  27. import com.dotmarketing.business.web.HostWebAPI;
  28. import com.dotmarketing.business.web.UserWebAPI;
  29. import com.dotmarketing.business.web.WebAPILocator;
  30. import com.dotmarketing.exception.DotDataException;
  31. import com.dotmarketing.exception.DotSecurityException;
  32. import com.dotmarketing.portlets.contentlet.model.Contentlet;
  33. import com.dotmarketing.portlets.fileassets.business.FileAssetAPI;
  34. import com.dotmarketing.portlets.files.business.FileAPI;
  35. import com.dotmarketing.portlets.files.model.File;
  36. import com.dotmarketing.util.Config;
  37. import com.dotmarketing.util.InodeUtils;
  38. import com.dotmarketing.util.Logger;
  39. import com.dotmarketing.viewtools.bean.XSLTranformationDoc;
  40. import com.dotmarketing.viewtools.cache.XSLTransformationCache;
  41. import com.liferay.portal.PortalException;
  42. import com.liferay.portal.SystemException;
  43. import com.liferay.portal.model.User;
  44.  
  45. /**
  46.  * XSLTTransform macro methods
  47.  * @author Oswaldo
  48.  *
  49.  *
  50.  */
  51. public class XsltTool implements ViewTool {
  52.  
  53.         private static final FileAPI fileAPI = APILocator.getFileAPI();
  54.         private static final UserAPI userAPI = APILocator.getUserAPI();
  55.         private HttpServletRequest request;
  56.         private HostWebAPI hostWebAPI;
  57.         protected Host host;
  58.         Context ctx;
  59.         private InternalContextAdapterImpl ica;
  60.         protected User user = null;
  61.         protected User backuser = null;
  62.         protected boolean respectFrontendRoles = false;
  63.         protected UserWebAPI userWebAPI;
  64.         public void init(Object obj) {
  65.                 if(!Config.getBooleanProperty("ENABLE_SCRIPTING", false)){
  66.                         return;
  67.                 }
  68.                 ViewContext context = (ViewContext) obj;
  69.                
  70.                 this.request = context.getRequest();
  71.                 ctx = context.getVelocityContext();            
  72.                 try {
  73.                         host = WebAPILocator.getHostWebAPI().getCurrentHost(request);
  74.                 } catch (PortalException e1) {
  75.                         Logger.error(this,e1.getMessage(),e1);
  76.                 } catch (SystemException e1) {
  77.                         Logger.error(this,e1.getMessage(),e1);
  78.                 } catch (DotDataException e1) {
  79.                         Logger.error(this,e1.getMessage(),e1);
  80.                 } catch (DotSecurityException e1) {
  81.                         Logger.error(this,e1.getMessage(),e1);
  82.                 }
  83.                 userWebAPI = WebAPILocator.getUserWebAPI();
  84.                 try {
  85.                         user = userWebAPI.getLoggedInFrontendUser(request);
  86.                         backuser = userWebAPI.getLoggedInUser(request);
  87.                         respectFrontendRoles = true;
  88.                 } catch (Exception e) {
  89.                         Logger.error(this, "Error finding the logged in user", e);
  90.                 }
  91.  
  92.  
  93.                 this.hostWebAPI = WebAPILocator.getHostWebAPI();
  94.         }
  95.  
  96.        
  97.        
  98.         public String transform(String XMLPath, String XSLPath, int ttl) throws Exception {
  99.                 String x = XSLTTransform(XMLPath, XSLPath, ttl).getXmlTransformation();
  100.                 return x;
  101.        
  102.         }
  103.        
  104.        
  105.        
  106.        
  107.        
  108.         /**
  109.          * Transform the XML into the string according to the specification of the xsl file
  110.          * @param XMLPath Location of the XML file
  111.          * @param XSLPath Location of the XSL file
  112.          * @param ttl Time to Live
  113.          * @throws TransformerConfigurationException
  114.          * @throws DotSecurityException
  115.          * @throws DotDataException
  116.          * @throws SystemException
  117.          * @throws PortalException
  118.          */
  119.         public XSLTranformationDoc XSLTTransform(String XMLPath, String XSLPath, long ttl) throws Exception {
  120.  
  121.                         if(!canUserEvalute()){
  122.                                 Logger.error(XsltTool.class, "XSLTTool user does not have scripting access ");
  123.                                 return null;
  124.                         }
  125.                         String outputXML = null;
  126.                         Source xmlSource = null;
  127.                         XSLTranformationDoc doc = null;
  128.                         Host host = hostWebAPI.getCurrentHost(request);
  129.  
  130.                         /*Validate if in cache exists a valid version*/
  131.                         doc = XSLTransformationCache.getXSLTranformationDocByXMLPath(XMLPath,XSLPath);
  132.  
  133.                         if(doc == null){
  134.                                 /*Get the XSL source*/
  135.                                 java.io.File binFile = null;
  136.                                 Identifier xslId = APILocator.getIdentifierAPI().find(host, XSLPath);
  137.                                 if(xslId!=null && InodeUtils.isSet(xslId.getId()) && xslId.getAssetType().equals("contentlet")){
  138.                                         Contentlet cont = APILocator.getContentletAPI().findContentletByIdentifier(xslId.getId(), true, APILocator.getLanguageAPI().getDefaultLanguage().getId(), userAPI.getSystemUser(),false);
  139.                                         if(cont!=null && InodeUtils.isSet(cont.getInode())){
  140.                                                 binFile = cont.getBinary(FileAssetAPI.BINARY_FIELD);
  141.                                         }
  142.                                 }else{
  143.                                         File xslFile = fileAPI.getFileByURI(XSLPath, host, true, userAPI.getSystemUser(),false);
  144.                                         binFile = fileAPI.getAssetIOFile (xslFile);
  145.                                 }
  146.                                
  147.                                
  148.                                 /*Get the XML Source from file or from URL*/
  149.                                 if(!XMLPath.startsWith("http")){
  150.                                         Identifier xmlId = APILocator.getIdentifierAPI().find(host, XMLPath);
  151.                                         if(xmlId!=null && InodeUtils.isSet(xmlId.getId()) && xmlId.getAssetType().equals("contentlet")){
  152.                                                 Contentlet cont = APILocator.getContentletAPI().findContentletByIdentifier(xmlId.getId(), true, APILocator.getLanguageAPI().getDefaultLanguage().getId(), userAPI.getSystemUser(),false);
  153.                                                 if(cont!=null && InodeUtils.isSet(cont.getInode())){
  154.                                                         xmlSource = new StreamSource(new InputStreamReader(new FileInputStream(cont.getBinary(FileAssetAPI.BINARY_FIELD)), "UTF8"));
  155.                                                 }
  156.                                         }else{
  157.                                                 File xmlFile = fileAPI.getFileByURI(XMLPath, host, true,userAPI.getSystemUser(),false);
  158.                                                 xmlSource = new StreamSource(new InputStreamReader(new FileInputStream(fileAPI.getAssetIOFile(xmlFile)), "UTF8"));
  159.                                         }
  160.  
  161.                                 }else{
  162.                                         xmlSource = new StreamSource(XMLPath);
  163.                                 }
  164.  
  165.                                 Source xsltSource = new StreamSource(new InputStreamReader(new FileInputStream(binFile), "UTF8"));
  166.  
  167.                                 // create an instance of TransformerFactory
  168.                                 TransformerFactory transFact = TransformerFactory.newInstance();
  169.                                 StreamResult result = new StreamResult(new ByteArrayOutputStream());
  170.                                 Transformer trans = transFact.newTransformer(xsltSource);
  171.  
  172.                                 try{
  173.                                         trans.transform(xmlSource, result);
  174.                                 }catch(Exception e1){
  175.                                         Logger.error(XsltTool.class, "Error in transformation. "+e1.getMessage());
  176.                                         e1.printStackTrace();
  177.                                 }
  178.  
  179.                                 outputXML = result.getOutputStream().toString();
  180.  
  181.                                 doc = new XSLTranformationDoc();
  182.                                 doc.setIdentifier(xslId.getId());
  183.                                 doc.setInode(xslId.getInode());
  184.                                 doc.setXslPath(XSLPath);
  185.                                 doc.setXmlPath(XMLPath);
  186.                                 doc.setXmlTransformation(outputXML);
  187.                                 doc.setTtl(new Date().getTime()+ttl);
  188.  
  189.                                 XSLTransformationCache.addXSLTranformationDoc(doc);
  190.  
  191.                         }
  192.  
  193.                         return doc;
  194.  
  195.         }
  196.        
  197.         /**
  198.          * Transform the XML into the string according to the specification of the xsl file
  199.          * @param XMLString String in XML format
  200.          * @param XSLPath Location of the XSL file
  201.          * @param ttl Time to Live
  202.          */
  203.         public XSLTranformationDoc XSLTTransformXMLString(String xmlString, String XSLPath) {
  204.                 try {
  205.                         if(!canUserEvalute()){
  206.                                 Logger.error(XsltTool.class, "XSLTTool user does not have scripting access ");
  207.                                 return null;
  208.                         }
  209.                         String outputXML = null;
  210.                         Source xmlSource = null;
  211.                         XSLTranformationDoc doc = null;
  212.                         Host host = hostWebAPI.getCurrentHost(request);
  213.                        
  214.                         /*Get the XSL source*/
  215.                         File xslFile = fileAPI.getFileByURI(XSLPath, host, true, userAPI.getSystemUser(), false);
  216.                        
  217.                         if (doc == null) {
  218.                                 xmlSource = new StreamSource(new ByteArrayInputStream(xmlString.getBytes("UTF-8")));
  219.                                
  220.                                 Source xsltSource = new StreamSource(new InputStreamReader(new FileInputStream(fileAPI.getAssetIOFile (xslFile)), "UTF8"));
  221.                                
  222.                                 // create an instance of TransformerFactory
  223.                                 TransformerFactory transFact = TransformerFactory.newInstance();
  224.                                 StreamResult result = new StreamResult(new ByteArrayOutputStream());
  225.                                 Transformer trans = transFact.newTransformer(xsltSource);
  226.                                
  227.                                 try {
  228.                                         trans.transform(xmlSource, result);
  229.                                 } catch (Exception e1) {
  230.                                         Logger.error(XsltTool.class, "Error in transformation. " + e1.getMessage());
  231.                                         e1.printStackTrace();
  232.                                 }
  233.                                
  234.                                 outputXML = result.getOutputStream().toString();
  235.                                
  236.                                 doc = new XSLTranformationDoc();
  237.                                 doc.setIdentifier(xslFile.getIdentifier());
  238.                                 doc.setInode(xslFile.getInode());
  239.                                 doc.setXslPath(XSLPath);
  240.                                 doc.setXmlTransformation(outputXML);
  241.                         }
  242.                        
  243.                         return doc;
  244.                 } catch (Exception e) {
  245.                         Logger.error(XsltTool.class, "Error in transformation. " + e.getMessage());
  246.                         e.printStackTrace();
  247.                         return null;
  248.                 }
  249.         }
  250.        
  251.         protected boolean canUserEvalute() throws DotDataException, DotSecurityException{
  252.                 if(!Config.getBooleanProperty("ENABLE_SCRIPTING", false)){
  253.                         Logger.warn(this.getClass(), "Scripting called and ENABLE_SCRIPTING set to false");
  254.                         return false;
  255.                 }
  256.                 try{
  257.                
  258.                         ica = new InternalContextAdapterImpl(ctx);
  259.                         String fieldResourceName = ica.getCurrentTemplateName();
  260.                         String conInode = fieldResourceName.substring(fieldResourceName.indexOf("/") + 1, fieldResourceName.indexOf("_"));
  261.                        
  262.                         Contentlet con = APILocator.getContentletAPI().find(conInode, APILocator.getUserAPI().getSystemUser(), true);
  263.                        
  264.                        
  265.                         User mu = userAPI.loadUserById(con.getModUser(), APILocator.getUserAPI().getSystemUser(), true);
  266.                         Role scripting =APILocator.getRoleAPI().loadRoleByKey("Scripting Developer");
  267.                         return APILocator.getRoleAPI().doesUserHaveRole(mu, scripting);
  268.                 }
  269.                 catch(Exception e){
  270.                         Logger.warn(this.getClass(), "Scripting called with error" + e);
  271.                         return false;  
  272.                        
  273.                 }
  274.         }
  275.        
  276. }