Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support for compilation on the server (much like JSP) #8

Open
wants to merge 9 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions README.markdown
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,26 @@ from the command prompt:
####command line options:
> __--bare__ - compile the javascript without top-level function safety wrapper.

####In a Web Application:
Add the following filter in your web.xml:

<pre>
&lt;filter&gt;
&lt;filter-name&gt;jcoffeescript&lt;/filter-name&gt;
&lt;filter-class&gt;org.jcoffeescript.web.CoffeeScriptFilter&lt;/filter-class&gt;
&lt;/filter&gt;
&lt;filter-mapping&gt;
&lt;filter-name&gt;jcoffeescript&lt;/filter-name&gt;
&lt;url-pattern&gt;*.js&lt;/url-pattern&gt;
&lt;/filter-mapping&gt;
</pre>

Write your CoffeeScript files inside:
> /WEB-INF/coffee

and access from the server using the following URL:
> http://&lt;your host&gt;/&lt;your context&gt;/js/&lt;coffeescript file name&gt;.js

####From java:
> String javascript = new org.jcoffeescript.JCoffeeScriptCompiler().compile("a = 1");

Expand Down
13 changes: 12 additions & 1 deletion build.xml
Original file line number Diff line number Diff line change
Expand Up @@ -28,11 +28,17 @@
<import file="${basedir}/conf/build/build-jar.xml"/>

<target name="dependencies">
<path id="compile.classpath">
<path id="inline.classpath">
<fileset dir="${basedir}/lib">
<include name="js.jar"/>
</fileset>
</path>
<path id="compile.classpath">
<path refid="inline.classpath"/>
<fileset dir="${basedir}/lib">
<include name="servlet-api-2.5.jar"/>
</fileset>
</path>
<path id="runtime.classpath">
<fileset dir="${basedir}/lib">
<include name="js.jar"/>
Expand All @@ -44,6 +50,11 @@
<fileset dir="${basedir}/lib">
<include name="hamcrest-all-1.3RC0.jar"/>
<include name="junit-dep-4.8.2.jar"/>
<include name="commons-httpclient-3.1.jar"/>
<include name="commons-codec-1.4.jar"/>
<include name="commons-logging-1.1.1.jar"/>
<include name="jetty-*.jar"/>

</fileset>
</path>
</target>
Expand Down
2 changes: 1 addition & 1 deletion conf/build/build-jar.xml
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
<project>
<target name="jar" depends="test">
<mkdir dir="${basedir}/target/dist"/>
<pathtofileset name="jars" pathrefid="compile.classpath" dir="${basedir}/lib"/>
<pathtofileset name="jars" pathrefid="inline.classpath" dir="${basedir}/lib"/>

<jar destfile="${basedir}/target/dist/${artifact.name}.jar">
<manifest><attribute name="Main-Class" value="org.jcoffeescript.Main"/></manifest>
Expand Down
Binary file added lib/commons-codec-1.4.jar
Binary file not shown.
Binary file added lib/commons-httpclient-3.1.jar
Binary file not shown.
Binary file added lib/commons-logging-1.1.1.jar
Binary file not shown.
Binary file added lib/jetty-annotations-7.2.2.v20101205.jar
Binary file not shown.
Binary file added lib/jetty-continuation-7.2.2.v20101205.jar
Binary file not shown.
Binary file added lib/jetty-http-7.2.2.v20101205.jar
Binary file not shown.
Binary file added lib/jetty-io-7.2.2.v20101205.jar
Binary file not shown.
Binary file added lib/jetty-security-7.2.2.v20101205.jar
Binary file not shown.
Binary file added lib/jetty-server-7.2.2.v20101205.jar
Binary file not shown.
Binary file added lib/jetty-servlet-7.2.2.v20101205.jar
Binary file not shown.
Binary file added lib/jetty-servlets-7.2.2.v20101205.jar
Binary file not shown.
Binary file added lib/jetty-util-7.2.2.v20101205.jar
Binary file not shown.
Binary file added lib/jetty-webapp-7.2.2.v20101205.jar
Binary file not shown.
Binary file added lib/servlet-api-2.5.jar
Binary file not shown.
50 changes: 50 additions & 0 deletions src/main/java/org/jcoffeescript/web/Binary.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
/*
* Copyright 2011 Leonardo Verissimo
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.jcoffeescript.web;

import java.io.File;
import java.net.URL;

/*default*/ class Binary {

private String content;
private long lastModified;

public Binary(URL coffeeURL, String content) {
this.lastModified = lastModified(coffeeURL);
this.content = content;
}

public boolean isOlderThan(URL coffeeURL) {
return this.lastModified < lastModified(coffeeURL);
}

public String getContent() {
return content;
}

public long getLastModified() {
return lastModified;
}

private long lastModified(URL coffeeURL) {
File file = new File(coffeeURL.getFile());
// when resource is inside WAR, file doesn't exist and
// lastModified equals zero
return file.lastModified();
}
}
178 changes: 178 additions & 0 deletions src/main/java/org/jcoffeescript/web/CoffeeScriptFilter.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,178 @@
package org.jcoffeescript.web;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.URL;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jcoffeescript.JCoffeeScriptCompileException;
import org.jcoffeescript.JCoffeeScriptCompiler;

public class CoffeeScriptFilter implements Filter {

private static final String DEFAULT_JS_PREFIX = "/js";
private static final String DEFAULT_COFFEE_PREFIX = "/WEB-INF/coffee";
private static final int BUFFER_SIZE = 4096;
private static final int MAX_COMPILED_JS = 100;

private String javascriptResourcePrefix;
private String coffeescriptFilenamePrefix;

private long startupTime = new java.util.Date().getTime() / 1000 * 1000;

@SuppressWarnings("serial")
@Override
public void init(FilterConfig config) throws ServletException {
// prefixes
String jsPrefix = config.getInitParameter("javascriptResourcePrefix");
if (jsPrefix == null || jsPrefix.equals("")) {
jsPrefix = DEFAULT_JS_PREFIX;
}
this.javascriptResourcePrefix = jsPrefix;

String csPrefix = config.getInitParameter("coffeescriptFilenamePrefix");
if (csPrefix == null || csPrefix.equals("")) {
csPrefix = DEFAULT_COFFEE_PREFIX;
}
this.coffeescriptFilenamePrefix = csPrefix;

// coffeescript compiler
JCoffeeScriptCompiler compiler = new JCoffeeScriptCompiler();
config.getServletContext().setAttribute("compiler", compiler);

// hashmap
LinkedHashMap<String, Binary> previousBinaries = new LinkedHashMap<String, Binary>() {

@Override
protected boolean removeEldestEntry(Entry<String, Binary> eldest) {
return size() > MAX_COMPILED_JS;
}
};
config.getServletContext().setAttribute("previousBinaries", Collections.synchronizedMap(previousBinaries));
}


@Override
public void destroy() {
}

@SuppressWarnings("unchecked")
@Override
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
throws IOException, ServletException {

HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) resp;
ServletContext servletContext = request.getSession().getServletContext();

JCoffeeScriptCompiler compiler = (JCoffeeScriptCompiler) servletContext.getAttribute("compiler");
Map<String, Binary> previousBinaries = (Map<String, Binary>) servletContext.getAttribute("previousBinaries");


String javascriptURI = getJavascriptURI(request);
String coffeeFilename = discoverCoffeeFilename(javascriptURI);
if (coffeeFilename == null) {
// it's not javascript
chain.doFilter(req, resp);
return;
}

URL coffeeURL = servletContext.getResource(coffeeFilename);

if (coffeeURL == null) {
// static javascript or coffe filename was deleted
previousBinaries.remove(coffeeFilename);
chain.doFilter(req, resp);
return;
}

Binary binary;
if ((binary = previousBinaries.get(coffeeFilename)) == null
|| binary.isOlderThan(coffeeURL)) {

InputStream coffeeStream = coffeeURL.openStream();
String source = getContent(coffeeStream);

try {
synchronized (compiler) {
binary = new Binary(coffeeURL, compiler.compile(source));
}
} catch (JCoffeeScriptCompileException e) {
throw new ServletException("Compilation error on file: " + coffeeFilename + " " + e.getMessage(), e);
}
}

// write in all cases to put value at the end of the linked list
previousBinaries.put(coffeeFilename, binary);

// optimizing response
long lastModified = binary.getLastModified() == 0 ? this.startupTime : (binary.getLastModified() / 1000 * 1000);
long ifModifiedSince = request.getDateHeader("If-Modified-Since");

if (lastModified > ifModifiedSince) {

// write last modified info
response.setDateHeader("Last-Modified", lastModified);
response.setContentType("text/javascript");
PrintWriter writer = resp.getWriter();
writer.write(binary.getContent());
} else {
response.setContentLength(0);
response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
}
}

private String getJavascriptURI(HttpServletRequest request) {
String javascriptURI = request.getServletPath();
if (request.getPathInfo() != null) {
javascriptURI += request.getPathInfo();
}
return javascriptURI;
}

private String discoverCoffeeFilename(String javascriptResource) {

Pattern pattern = Pattern.compile(javascriptResourcePrefix + "/(.*).js");
Matcher matcher = pattern.matcher(javascriptResource);
if (!matcher.matches()) {
return null;
}
return coffeescriptFilenamePrefix + "/" + matcher.group(1) + ".coffee";
}

private String getContent(InputStream coffeeStream) throws IOException {
InputStreamReader reader = new InputStreamReader(coffeeStream);
try {
StringWriter writer = new StringWriter();

char[] buffer = new char[BUFFER_SIZE];
int n = 0;
while (-1 != (n = reader.read(buffer))) {
writer.write(buffer, 0, n);
}
String source = writer.toString();
return source;
} finally {
reader.close();
}
}

}
2 changes: 2 additions & 0 deletions src/unit-tests/java/app/WEB-INF/coffee/error.coffee
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
list = [1,2

1 change: 1 addition & 0 deletions src/unit-tests/java/app/WEB-INF/coffee/simple.coffee
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
a = 1
1 change: 1 addition & 0 deletions src/unit-tests/java/app/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
<h1>It Works!</h1>
1 change: 1 addition & 0 deletions src/unit-tests/java/app/javascript/static.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
var test = 0;
Loading