Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  package edu.mit.simile.butterfly;
  
  import java.io.File;
 import java.io.Reader;
 import java.io.Writer;
 import java.net.URL;
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
 
 
 
This class is the base implementation of ButterflyModule and implements the basic functionality that is made available to Butterfly modules. If you want special functionality that Butterfly does not expose to your modules, it is highly suggested that you extend this class instead of implementing the ButterflyModule interface yourself
 
 public class ButterflyModuleImpl implements ButterflyModule {
 
     protected static final Logger _logger = LoggerFactory.getLogger("butterfly.module");
     
     protected ClassLoader _classLoader;
     protected Timer _timer;
     protected ServletConfig _config;
     protected File _path;
     protected MountPoint _mountPoint;
     protected ButterflyMounter _mounter;
     protected String _name;
     protected File _tempDir;
     protected ButterflyModule _extended;
     protected Set<ButterflyModule_extendedBy = new LinkedHashSet<ButterflyModule>();
     protected Set<String_implementations = new LinkedHashSet<String>();
     protected ExtendedProperties _properties;
     protected Map<String,ButterflyModule_modules;
     protected VelocityEngine _templateEngine;
     protected OrderedMap _scripts = new ListOrderedMap();
     protected Set<TimerTask_packers = new HashSet<TimerTask>();
     
     // ------------------------------------------------------------------------------------------------
     
     public void init(ServletConfig configthrows Exception {
          = config;
         
         scriptInit();
     }
     
     public void destroy() throws Exception {
         for (ButterflyScriptableObject scriptable : ) {
         	scriptable.destroy();
        }
    }
        
    public ServletConfig getServletConfig() {
    	return ;
    }
    public ServletContext getServletContext() {
    	return .getServletContext();
    }
    
    // ------------------------------------------------------------------------------------------------
    public void setClassLoader(ClassLoader classLoader) {
        .trace("{} -(classloader)-> {}"thisclassLoader);
        this. = classLoader;
    }
    
    public void setPath(File path) {
        .trace("{} -(path)-> {}"thispath);
        this. = path;
    }
    public void setName(String name) {
        .trace("{} -(name)-> {}"thisname);
        this. = name;
    }
    public void setExtended(ButterflyModule extended) {
        .trace("{} -(extends)-> {}"thisextended);
        this. = extended;
    }
    public void addExtendedBy(ButterflyModule extendedBy) {
        .trace("{} -(extended by)-> {}"thisextendedBy);
        this..add(extendedBy);
    }
    
    public void setMountPoint(MountPoint mountPoint) {
        .trace("{} -(mount point)-> {}"thismountPoint);
        this. = mountPoint;
    }
    public void setImplementation(String id) {
        .trace("{} -(implements)-> {}"thisid);
        this..add(id);
    }
    
    public void setDependency(String nameButterflyModule module) {
        if (!this..containsKey(name)) {
            .trace("{} -({})-> {}"new Object[] { thisnamemodule} );
            this..put(namemodule);
        }
    }
    public void setModules(Map<String,ButterflyModulemap) {
        this. = map;
    }
    
    @SuppressWarnings("unchecked")
    public void setScript(URL urlScript script) {
        .trace("{} -(script)-> {}"thisurl);
        this..put(url,script);
    }
    public void setScriptable(ButterflyScriptableObject scriptable) {
        .trace("{} -(scriptable)-> {}"thisscriptable.getClassName());
        this..add(scriptable);
    }
    
    public void setTemplateEngine(VelocityEngine templateEngine) {
        .trace("{} gets template engine"this);
        this. = templateEngine;
    }
        
    public void setProperties(ExtendedProperties properties) {
        .trace("{} gets loaded with properties"this);
        this. = properties;
    }
    public void setMounter(ButterflyMounter mounter) {
        .trace("{} gets the module mounter"this);
        this. = mounter;
    }
    
    public void setTemporaryDir(File tempDir) {
        .trace("{} -(tempDir)-> {}"thistempDir);
        this. = tempDir;
        try {
            FileUtils.deleteDirectory(tempDir);
            tempDir.mkdirs();
        } catch (Exception e) {
            .error("Error cleaning temporary directory"e);
        }
    }
    
    public void setTimer(Timer timer) {
        .trace("{} gets timer"this);
        this. = timer;
    }
    
    // ------------------------------------------------------------------------------------------------
    
    public String getName() {
        return this.;
    }
    public File getPath() {
        return this.;
    }
    public ExtendedProperties getProperties() {
        return this.;
    }
    
    public MountPoint getMountPoint() {
        return this.;
    }
    
    public ButterflyMounter getMounter() {
        return this.;
    }
        return this.;
    }
        return this.;
    }
    
    	return this.;
    }
    public Set<StringgetImplementations() {
    	return this.;
    }
    
    	return this.;
    }
    
    public VelocityEngine getTemplateEngine() {
    	return this.;
    }
    
    public ButterflyModule getModule(String name) {
        .trace("> getModule({}) [{}]"namethis.);
        ButterflyModule module = .get(name);
        if (module == null &&  != null) {
            module = .getModule(name);
        }
        if (module == null) {
            module = .get(name);
        }
        .trace("< getModule({}) [{}] -> {}"new Object[] { namethis.,  module });
        return module;
    }
    protected Pattern super_pattern = Pattern.compile("^@@(.*)@@$");
    
    public URL getResource(String resource) {
        .trace("> getResource({}->{},{})"new Object[] { resource });
        URL u = null;
        if ("".equals(resource)) {
            try {
                u = .toURI().toURL();
            } catch (MalformedURLException e) {
                .error("Error"e);
            }
        }
        
        if (u == null && resource.charAt(0) == '@') { // fast screening for potential matchers
            Matcher m = .matcher(resource);
            if (m.matches()) {
                resource = m.group(1);
                if ( != null) {
                    u = .getResource(resource);
                }
            }
        }
        
        if (u == null) {
            try {
                if (resource.startsWith("file:/")) {
                    u = new URL(resource);
                } else {
                    if (resource.charAt(0) == '/'resource = resource.substring(1);
                    File f = new File(resource);
                    if (f.exists()) {
                        u = f.toURI().toURL();
                    }
                }
            } catch (MalformedURLException e) {
                .error("Error"e);
            }
        }
        if (u == null &&  != null) {
            u = .getResource(resource);
        }
        
        .trace("< getResource({}->{},{}) -> {}"new Object[] { resourceu });
        return u;
    }
    public String getRelativePath(HttpServletRequest request) {
        .trace("> getRelativePath()");
        String path = request.getPathInfo();
        String mountPoint = .getMountPoint();
        if (path.startsWith(mountPoint)) {
            path = path.substring(mountPoint.length());
        }
        .trace("< getRelativePath() -> {}"path);
        return path;
    }
    
    public PrintWriter getFilteringWriter(HttpServletRequest requestHttpServletResponse responseboolean absolutethrows IOException {
        .trace("> getFilteringWriter() [{},absolute='{}']"this , absolute);
        LinkRewriter rewriter =  new LinkRewriter(response.getWriter(), thisgetContextPath(requestabsolute));
        .trace("< getFilteringWriter() [{},absolute='{}']"this , absolute);
        return rewriter;
    }
    public String getContextPath(HttpServletRequest requestboolean absolute) {
        return Butterfly.getTrueContextPath(requestabsolute);
    }
    public String getString(HttpServletRequest requestthrows IOException {
        BufferedReader reader = request.getReader();
        StringWriter writer = new StringWriter();
        IOUtils.copy(readerwriter);
        writer.close();
        reader.close();
        return writer.toString();
    }
        
    public File getTemporaryDir() {
        return this.;
    }
    
    // ------------------------------------------------------------------------------------------------
    
    protected Pattern images_pattern = Pattern.compile("^/?.*\\.(jpg|gif|png)$");
    protected Pattern mod_inf_pattern = Pattern.compile("^.*/MOD-INF/.*$");
    protected String encoding = "UTF-8";
    
    /*
     * This class encapsulates the 'context action' that Rhino executes
     * when a request comes.
     */
    class Controller implements ContextAction {
        private String _path;
        private HttpServletRequest _request;
        private HttpServletResponse _response;
        private Scriptable _scope;
        
        public Controller(String pathHttpServletRequest requestHttpServletResponse response) {
             = path;
             = request;
             = response;
        }
        
        public Object run(Context context) {
            Scriptable scope;
            try {
                scope = getScope(context);                
            } catch (Exception e) {
                throw new RuntimeException ("Error retrieving scope"e);
            }
            initScope(context,scope);
            return process(contextscope);
        }
        
        /*
         * tell whether or not the controller processed the request
         * or let it fall thru
         */
        public boolean didRespond() {
            return ((ScriptableButterfly.get("butterfly")).didRespond();
        }
        /*
         * process the request by invoking the controller "process()" function 
         */
        private Object process(Context contextScriptable scope) {
             = scope// save this for the didRespond() method above;
            Function function = getFunction("process"scopecontext);
            Object[] args = new Object[] {
                Context.javaToJS(scope),
                Context.javaToJS(scope),
                Context.javaToJS(scope)
            };
            return function.call(contextscopescopeargs);
        }
        
        /*
         * obtain a javascript function from the given scope
         */
        private Function getFunction(String nameScriptable scopeContext ctx) {
            Object fun;
            try {
                fun = ctx.compileString(namenull, 1, null).exec(ctxscope);
            } catch (EcmaError ee) {
                throw new RuntimeException ("Function '" + name + "()' not found.");
            }
            
            if (!(fun instanceof Function)) {
                throw new RuntimeException("'" + name + "' is not a function");
            } else {
                return (Functionfun;
            }
        }
    }
    
    
This method is called by Butterfly when preProcess returns false and allows modules that want to have a controller in Java instead of Javascript.
    public boolean process(String pathHttpServletRequest requestHttpServletResponse responsethrows Exception {
        if (processScript(pathrequestresponse)) {
            return true;
        }
        
        Matcher m = null;
        if (path.equals("") || path.endsWith("/")) {
            return sendText(requestresponsepath + "index.html""text/html",false);
        }
        
        if (path.endsWith(".js")) {
            return sendText(requestresponsepath"text/javascript",false);
        }
        m = .matcher(path);
        if (m.matches()) {
            return sendBinary(requestresponsepath"image/" + m.group(1));
        }
        if (path.endsWith(".css")) {
            return sendText(requestresponsepath"text/css",false);
        }
        if (path.endsWith(".less")) {
            return sendLessen(requestresponsepath"text/css",false);
        }
        if (path.endsWith(".html")) {
            return sendText(requestresponsepath"text/html",false);
        }
        if (path.endsWith(".xml")) {
            return sendText(requestresponsepath"application/xml",false);
        }
                
        m = .matcher(path);
        if (m.matches()) {
            response.sendError(.);
            return true;
        }
        
        return false;
    }
    
    // ------------------------------------------------------------------------------------------------
    
    public boolean redirect(HttpServletRequest requestHttpServletResponse responseString locationthrows Exception {
    	.trace("> redirect: {}"location);
        String redirectURL = location;
        if (!location.startsWith("http://") && !location.startsWith("https://")) {
        	String contextPath = getContextPath(request,true);
	        String servletPath = request.getServletPath();
            if ("".equals(location)) {
                location = "/";
            }
	        if (servletPath != null) {
	        	if (servletPath.startsWith("/")) servletPath = servletPath.substring(1);
		        redirectURL = contextPath + servletPath + location;
	        } else {
		        redirectURL = contextPath + location;
	        }
        }
        .info("redirecting to: {}"redirectURL);        
    	response.sendRedirect(redirectURL);
        .trace("< redirect: {}"location);
        return true;
    }
        
    public boolean sendBinary(HttpServletRequest requestHttpServletResponse responseString fileString mimeTypethrows Exception {
        return send(requestresponsegetResource(file), falsenullmimeTypenullnullfalse);
    }
    
    public boolean sendBinary(HttpServletRequest requestHttpServletResponse responseURL resourceString mimeTypethrows Exception {
        return send(requestresponseresourcefalsenullmimeTypenullnullfalse);
    }
    public boolean sendText(HttpServletRequest requestHttpServletResponse responseString fileString encodingString mimeTypeboolean absolutethrows Exception {
        return send(requestresponsegetResource(file), trueencodingmimeTypenullnullabsolute);
    }
    
    public boolean sendText(HttpServletRequest requestHttpServletResponse responseURL resourceString encodingString mimeTypeboolean absolutethrows Exception {
        return send(requestresponseresourcetrueencodingmimeTypenullnullabsolute);
    }
    
    public boolean sendWrappedText(HttpServletRequest requestHttpServletResponse responseURL resourceString encodingString mimeTypeString prologueString epilogueboolean absolutethrows Exception {
        return send(requestresponseresourcetrueencodingmimeTypeprologueepilogueabsolute);
    }
        
    public boolean sendTextFromTemplate(HttpServletRequest requestHttpServletResponse responseVelocityContext velocityString templateString encodingString mimeTypeboolean absolutethrows Exception {
        .trace("> template {} [{}|{}]"new String[] { templateencodingmimeType });
        try {
            response.setContentType(mimeType);
            .mergeTemplate(templateencodingvelocitygetFilteringWriter(requestresponseabsolute));
        } catch (ResourceNotFoundException e) {
            response.sendError(.);
        }
        .trace("< template {} [{}|{}]"new String[] { templateencodingmimeType });
        return true
    }
    
    public boolean sendLessen(HttpServletRequest requestHttpServletResponse responseString pathString encodingString mimeTypeboolean absolutethrows Exception {
        URL url = getResource(path);
        
        Map<StringStringvariables = new HashMap<StringString>();
        variables.put("module");
        
        Tokenizer tokenizer = Utilities.openLess(urlvariables);
        tokenizer = new CondensingTokenizer(tokenizerfalse);
        tokenizer = new IndentingTokenizer(tokenizer);
        
        return sendLessenTokenStream(requestresponsetokenizerencoding"text/css",false);
    }
    
    public boolean sendLessenTokenStream(HttpServletRequest requestHttpServletResponse responseTokenizer tokenizerString encodingString mimeTypeboolean absolutethrows Exception {
        try {
            response.setContentType(mimeType);
            Utilities.write(tokenizergetFilteringWriter(requestresponseabsolute));
        } catch (ResourceNotFoundException e) {
            response.sendError(.);
        }
        return true
    }
    public boolean sendString(HttpServletRequest requestHttpServletResponse responseString strString encodingString mimeTypethrows Exception {
        .trace("> string: '{}'"str);
        response.setContentType(mimeType);
        response.setCharacterEncoding(encoding);
        PrintWriter writer = response.getWriter();
        writer.write(str);
        writer.close();
        .trace("< string: '{}'"str);
        return true
    }
    public boolean sendError(HttpServletRequest requestHttpServletResponse responseint codeString strthrows Exception {
        .trace("> error: '{}' '{}'"codestr);
        response.sendError(codestr);
        .trace("< error: '{}' '{}'"codestr);
        return true
    }
    
    // ------------------------------------------------------------------------------------------------
    
    public static class Level {
        String name;
        String href;
        public Level(String nameString href) {
            this. = name;
            this. = href;
        }
        
        public String getName() {
            return ;
        }
        
        public String getHref() {
            return ;
        }
    }
    
    public List<LevelmakePath(String pathMap<String,Stringdescs) {
        LinkedList<Levells = new LinkedList<Level>();
        String[] paths = path.split("/");
        if (paths.length > 1) {
            String relativePath = (path.endsWith("/")) ? "../" : "./";
            for (int i = paths.length - 2; i >= 0; i--) {
                String p = paths[i];
                String desc = descs.get(paths[i]);
                if (desc == nulldesc = p;
                Level l = new Level(desc,relativePath);
                relativePath = "../" + relativePath;
                ls.addFirst(l);
            }
        }
        return ls;
    }
    public String toString() {
        return  + " [" + this.getClass().getName() + "]";
    }
    public void initScope(Context contextScriptable scope) {
        for (ButterflyModule m : .values()) {
            m.initScope(contextscope);
        }
        
        while (i.hasNext()) {
            URL url = (URLi.next();
            .debug("Executing script: {}"url);
            Script s = (Script.get(url);
            s.exec(contextscope);
        }
    }
    
    // ------------------------------------------------------------------------------------------------
    protected void scriptInit() throws Exception {
        Context context = ContextFactory.getGlobal().enterContext();
        Scriptable scope = new ButterflyScope(thiscontext);
        
        initScope(context,scope);
        
        String functionName = "init";
        try {
            Object fun = context.compileString(functionNamenull, 1, null).exec(contextscope);
            if (fun != null && fun instanceof Function) {
                try {
                    ((Functionfun).call(contextscopescopenew Object[] {});
                } catch (EcmaError ee) {
                    .error("Error initializing module " + getName() + " by script function init()"ee);
                }
            }
        } catch (EcmaError ee) {
            // ignore
        }
    }
    
    protected boolean processScript(String pathHttpServletRequest requestHttpServletResponse responsethrows Exception {
        boolean result = false;
        if (.size() > 0) {
            Controller controller = new Controller(pathrequestresponse);
            ContextFactory.getGlobal().call(controller);
            result = controller.didRespond();
        }
        if (!result &&  != null &&  instanceof ButterflyModuleImpl) {
            result = ((ButterflyModuleImpl).processScript(pathrequestresponse);
        }
        return result;
    }
    protected ButterflyScope getScope(Context contextHttpServletRequest requestthrows Exception {
        return new ButterflyScope(thiscontext);
    }
    
    protected boolean send(HttpServletRequest requestHttpServletResponse responseURL resourceboolean filteringString encodingString mimeTypeString prologueString epilogueboolean absolutethrows Exception {
        .trace("> send {}"resource);
        if (resource != null) {
            URLConnection urlConnection = resource.openConnection();
            
            // NOTE(SM): I've disabled the HTTP caching-related headers for now 
            //           we should introduce this back in the future once we start
            //           fine tuning the system but for now since it's hard to 
            //           understand when ajax calls are cached or not it's better
            //           to develop without worrying about the cache
            
//            long lastModified = urlConnection.getLastModified();
//
//            long ifModifiedSince = request.getDateHeader("If-Modified-Since");
//            if (lastModified == 0 || ifModifiedSince / 1000 < lastModified / 1000) {
//                response.setDateHeader("Last-Modified", lastModified);
              
                if (encoding == null) {
                    InputStream input = null;
                    OutputStream output = null;
                    try {
                        input = new BufferedInputStream(urlConnection.getInputStream()); 
                        response.setHeader("Content-Type"mimeType);
                        output = response.getOutputStream();
                        IOUtils.copy(inputoutput);
                    } catch (Exception e) {
                        .error("Error processing " + resourcee);
                    } finally {
                        if (input != nullinput.close();
                        if (output != nulloutput.close();
                    }
                } else {
                    Reader input = null;
                    Writer output = null;
                    try {
                        input = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), encoding));
                        response.setHeader("Content-Type"mimeType + ";charset=" + encoding);
                        response.setCharacterEncoding(encoding);
                        output = (filtering) ? getFilteringWriter(requestresponseabsolute) : response.getWriter();
                        
                        if (prologue != null) {
                            output.write(prologue);
                        }
                        
                        IOUtils.copy(inputoutput);
                        
                        if (epilogue != null) {
                            output.write(epilogue);
                        }
                    } catch (Exception e) {
                        .error("Error processing " + resourcee);
                    } finally {
                        if (input != nullinput.close();
                        if (output != nulloutput.close();
                    }
                }
//            } else {
//                response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
//            }
        } else {
            response.sendError(."Couldn't find the specified resource");
        }
        .trace("< send {}"resource);
        return true;
    }
New to GrepCode? Check out our FAQ X