Performance-related enhancements..

This commit is contained in:
Jeremy Grelle
2008-03-31 19:15:24 +00:00
parent 0f86540ae2
commit 4477364417
8 changed files with 365 additions and 50 deletions

View File

@@ -10,11 +10,11 @@ import org.springframework.faces.ui.resource.ResourceHelper;
public class DojoStyleRenderer extends Renderer {
private String dijitThemePath = "/dijit/themes/";
private static final String dijitThemePath = "/dijit/themes/";
private String dijitTheme = "tundra";
private static final String dijitTheme = "tundra";
private ResourceHelper resourceHelper = new ResourceHelper();
private static final ResourceHelper resourceHelper = new ResourceHelper();
public void encodeBegin(FacesContext context, UIComponent component) throws IOException {

View File

@@ -0,0 +1,27 @@
package org.springframework.faces.ui;
import java.io.IOException;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.render.Renderer;
import org.springframework.faces.ui.resource.ResourceHelper;
public class ResourceGroupRenderer extends Renderer {
private static final ResourceHelper resourceHelper = new ResourceHelper();
public void encodeBegin(FacesContext context, UIComponent component) throws IOException {
if (component.getChildCount() > 0) {
resourceHelper.beginCombineStyles(context);
}
}
public void encodeEnd(FacesContext context, UIComponent component) throws IOException {
if (component.getChildCount() > 0) {
resourceHelper.endCombineStyles(context);
}
}
}

View File

@@ -0,0 +1,27 @@
package org.springframework.faces.ui;
import java.io.IOException;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.render.Renderer;
import org.springframework.faces.ui.resource.ResourceHelper;
import org.springframework.util.Assert;
public class ResourceRenderer extends Renderer {
private static final ResourceHelper resourceHelper = new ResourceHelper();
public void encodeEnd(FacesContext context, UIComponent component) throws IOException {
String resourcePath = (String) component.getAttributes().get("resourcePath");
Assert.hasText(resourcePath, "Resource component " + component.getClientId(context)
+ " is missing a resourcePath.");
if (!resourcePath.startsWith("/")) {
resourcePath = "/" + resourcePath;
component.getAttributes().put("resourcePath", resourcePath);
}
resourceHelper.renderResource(context, resourcePath);
}
}

View File

@@ -16,9 +16,11 @@
package org.springframework.faces.ui.resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
@@ -37,6 +39,22 @@ public class ResourceHelper {
private static final String RENDERED_RESOURCES_KEY = "org.springframework.faces.RenderedResources";
private static final String COMBINED_RESOURCES_KEY = "org.springframework.faces.CombinedResources";
/**
* Renders either a script or style resource depending on the resourcePath
* @param facesContext
* @param resourcePath
* @throws IOException
*/
public void renderResource(FacesContext facesContext, String resourcePath) throws IOException {
if (resourcePath.endsWith(".js")) {
renderScriptLink(facesContext, resourcePath);
} else if (resourcePath.endsWith(".css")) {
renderStyleLink(facesContext, resourcePath);
}
}
/**
* Render a <code><script/></code> tag for a given script resource.
* @param facesContext
@@ -81,6 +99,9 @@ public class ResourceHelper {
public void renderStyleLink(FacesContext facesContext, String cssPath) throws IOException {
if (alreadyRendered(facesContext, cssPath)) {
return;
} else if (isCombineStyles(facesContext)) {
addStyle(facesContext, cssPath);
return;
}
ResponseWriter writer = facesContext.getResponseWriter();
writer.startElement("link", null);
@@ -110,6 +131,37 @@ public class ResourceHelper {
markRendered(facesContext, module);
}
public void beginCombineStyles(FacesContext facesContext) {
List combinedResources = new ArrayList();
facesContext.getExternalContext().getRequestMap().put(COMBINED_RESOURCES_KEY, combinedResources);
}
private boolean isCombineStyles(FacesContext facesContext) {
return facesContext.getExternalContext().getRequestMap().containsKey(COMBINED_RESOURCES_KEY);
}
private void addStyle(FacesContext facesContext, String stylePath) {
List combinedResources = (List) facesContext.getExternalContext().getRequestMap().get(COMBINED_RESOURCES_KEY);
combinedResources.add(stylePath);
}
public void endCombineStyles(FacesContext facesContext) throws IOException {
List combinedResources = (List) facesContext.getExternalContext().getRequestMap()
.remove(COMBINED_RESOURCES_KEY);
StringBuffer combinedPath = new StringBuffer();
for (int i = 0; i < combinedResources.size(); i++) {
String resourcePath = (String) combinedResources.get(i);
if (i == 1) {
combinedPath.append("?appended=");
}
if (i > 1) {
combinedPath.append(",");
}
combinedPath.append(resourcePath);
}
renderStyleLink(facesContext, combinedPath.toString());
}
private void markRendered(FacesContext facesContext, String scriptPath) {
Set renderedResources = (Set) facesContext.getExternalContext().getRequestMap().get(RENDERED_RESOURCES_KEY);
if (renderedResources == null) {

View File

@@ -15,6 +15,7 @@
*/
package org.springframework.faces.ui.resource;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
@@ -22,9 +23,13 @@ import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.zip.GZIPOutputStream;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@@ -32,9 +37,10 @@ import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.util.ClassUtils;
import org.springframework.util.StringUtils;
/**
* Special action for resolving and rendering static resources from within a JAR file.
* Special resource servlet for efficiently resolving and rendering static resources from within a JAR file.
*
* @author Jeremy Grelle
*/
@@ -48,8 +54,12 @@ public class ResourceServlet extends HttpServlet {
private static final String HTTP_CACHE_CONTROL_HEADER = "Cache-Control";
private static final String GZIP_ENABLED_PARAM = "gzipEnabled";
private static final Log log = LogFactory.getLog(ResourceServlet.class);
private boolean gzipEnabled = true;
private Map defaultMimeTypes = new HashMap();
{
defaultMimeTypes.put(".css", "text/css");
@@ -61,91 +71,166 @@ public class ResourceServlet extends HttpServlet {
defaultMimeTypes.put(".png", "image/png");
}
private Set compressedMimeTypes = new HashSet();
{
compressedMimeTypes.add("text/css");
compressedMimeTypes.add("text/javascript");
}
public void init() throws ServletException {
String gzipEnabledParamValue = getServletConfig().getInitParameter(GZIP_ENABLED_PARAM);
if (StringUtils.hasText(gzipEnabledParamValue)) {
gzipEnabled = Boolean.valueOf(gzipEnabledParamValue).booleanValue();
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String localResourcePath = request.getPathInfo();
String rawResourcePath = request.getPathInfo();
if (log.isDebugEnabled()) {
log.debug("Attempting to GET resource: " + localResourcePath);
log.debug("Attempting to GET resource: " + rawResourcePath);
}
URL resource = getRequestResourceURL(localResourcePath);
URL[] resources = getRequestResourceURLs(request);
if (resource == null) {
if (resources == null || resources.length == 0) {
if (log.isDebugEnabled()) {
log.debug("Resource not found: " + localResourcePath);
log.debug("Resource not found: " + rawResourcePath);
}
response.setStatus(HttpServletResponse.SC_NOT_FOUND);
return;
}
URLConnection resourceConn = resource.openConnection();
long lastModified = resourceConn.getLastModified();
prepareResponse(response, resources, rawResourcePath);
String mimeType = getServletContext().getMimeType(resource.getPath());
if (mimeType == null) {
String extension = resource.getPath().substring(resource.getPath().lastIndexOf('.'));
mimeType = (String) defaultMimeTypes.get(extension);
}
response.setContentType(mimeType);
OutputStream out = selectOutputStream(request, response);
response.setHeader(HTTP_CONTENT_LENGTH_HEADER, Long.toString(resourceConn.getContentLength()));
response.setDateHeader(HTTP_LAST_MODIFIED_HEADER, lastModified);
configureCaching(response, 31556926);
InputStream in = resourceConn.getInputStream();
OutputStream out = response.getOutputStream();
try {
byte[] buffer = new byte[1024];
while (in.available() > 0) {
int len = in.read(buffer);
out.write(buffer, 0, len);
for (int i = 0; i < resources.length; i++) {
URLConnection resourceConn = resources[i].openConnection();
InputStream in = resourceConn.getInputStream();
try {
byte[] buffer = new byte[1024];
while (in.available() > 0) {
int len = in.read(buffer);
out.write(buffer, 0, len);
}
} finally {
in.close();
}
}
} finally {
in.close();
out.close();
}
}
private OutputStream selectOutputStream(HttpServletRequest request, HttpServletResponse response)
throws IOException {
String acceptEncoding = request.getHeader("Accept-Encoding");
String mimeType = response.getContentType();
if (gzipEnabled && StringUtils.hasText(acceptEncoding) && acceptEncoding.contains("gzip")
&& compressedMimeTypes.contains(mimeType)) {
log.debug("Enabling GZIP compression for the current response.");
return new GZIPResponseStream(response);
} else {
return response.getOutputStream();
}
}
private void prepareResponse(HttpServletResponse response, URL[] resources, String rawResourcePath)
throws IOException {
long lastModified = -1;
int contentLength = 0;
String mimeType = null;
for (int i = 0; i < resources.length; i++) {
URLConnection resourceConn = resources[i].openConnection();
if (resourceConn.getLastModified() > lastModified) {
lastModified = resourceConn.getLastModified();
}
String currentMimeType = getServletContext().getMimeType(resources[i].getPath());
if (currentMimeType == null) {
String extension = resources[i].getPath().substring(resources[i].getPath().lastIndexOf('.'));
currentMimeType = (String) defaultMimeTypes.get(extension);
}
if (mimeType == null) {
mimeType = currentMimeType;
} else if (!mimeType.equals(currentMimeType)) {
throw new MalformedURLException("Combined resource path: " + rawResourcePath
+ " is invalid. All resources in a combined resource path must be of the same mime type.");
}
contentLength += resourceConn.getContentLength();
}
response.setContentType(mimeType);
response.setHeader(HTTP_CONTENT_LENGTH_HEADER, Long.toString(contentLength));
response.setDateHeader(HTTP_LAST_MODIFIED_HEADER, lastModified);
configureCaching(response, 31556926);
}
protected long getLastModified(HttpServletRequest request) {
if (log.isDebugEnabled()) {
log.debug("Checking last modified of resource: " + request.getPathInfo());
}
URL resource;
URL[] resources;
try {
resource = getRequestResourceURL(request.getPathInfo());
resources = getRequestResourceURLs(request);
} catch (MalformedURLException e) {
return -1;
}
if (resource == null) {
if (resources == null || resources.length == 0) {
return -1;
}
URLConnection resourceConn;
try {
resourceConn = resource.openConnection();
} catch (IOException e) {
return -1;
long lastModified = -1;
for (int i = 0; i < resources.length; i++) {
URLConnection resourceConn;
try {
resourceConn = resources[i].openConnection();
} catch (IOException e) {
return -1;
}
if (resourceConn.getLastModified() > lastModified) {
lastModified = resourceConn.getLastModified();
}
}
return resourceConn.getLastModified();
return lastModified;
}
private URL getRequestResourceURL(String localResourcePath) throws MalformedURLException {
private URL[] getRequestResourceURLs(HttpServletRequest request) throws MalformedURLException {
String jarResourcePath = "META-INF" + localResourcePath;
URL resource;
resource = getServletContext().getResource(localResourcePath);
if (resource == null) {
if (log.isDebugEnabled()) {
log.debug("Searching classpath for resource: " + jarResourcePath);
}
resource = ClassUtils.getDefaultClassLoader().getResource(jarResourcePath);
String rawResourcePath = request.getPathInfo();
String appendedPaths = request.getParameter("appended");
if (StringUtils.hasText(appendedPaths)) {
rawResourcePath = rawResourcePath + "," + appendedPaths;
}
return resource;
String[] localResourcePaths = StringUtils.delimitedListToStringArray(rawResourcePath, ",");
URL[] resources = new URL[localResourcePaths.length];
for (int i = 0; i < localResourcePaths.length; i++) {
String localResourcePath = localResourcePaths[i];
URL resource = getServletContext().getResource(localResourcePath);
if (resource == null) {
String jarResourcePath = "META-INF" + localResourcePath;
if (log.isDebugEnabled()) {
log.debug("Searching classpath for resource: " + jarResourcePath);
}
resource = ClassUtils.getDefaultClassLoader().getResource(jarResourcePath);
}
if (resource == null) {
if (resources.length > 1) {
log.debug("Combined resource not found: " + localResourcePath);
}
return null;
} else {
resources[i] = resource;
}
}
return resources;
}
/**
@@ -158,4 +243,75 @@ public class ResourceServlet extends HttpServlet {
// HTTP 1.1 header
response.setHeader(HTTP_CACHE_CONTROL_HEADER, "max-age=" + seconds);
}
private class GZIPResponseStream extends ServletOutputStream {
private ByteArrayOutputStream byteStream = null;
private GZIPOutputStream gzipStream = null;
private boolean closed = false;
private HttpServletResponse response = null;
private ServletOutputStream servletStream = null;
public GZIPResponseStream(HttpServletResponse response) throws IOException {
super();
closed = false;
this.response = response;
this.servletStream = response.getOutputStream();
byteStream = new ByteArrayOutputStream();
gzipStream = new GZIPOutputStream(byteStream);
}
public void close() throws IOException {
if (closed) {
throw new IOException("This output stream has already been closed");
}
gzipStream.finish();
byte[] bytes = byteStream.toByteArray();
response.setContentLength(bytes.length);
response.addHeader("Content-Encoding", "gzip");
servletStream.write(bytes);
servletStream.flush();
servletStream.close();
closed = true;
}
public void flush() throws IOException {
if (closed) {
throw new IOException("Cannot flush a closed output stream");
}
gzipStream.flush();
}
public void write(int b) throws IOException {
if (closed) {
throw new IOException("Cannot write to a closed output stream");
}
gzipStream.write((byte) b);
}
public void write(byte b[]) throws IOException {
write(b, 0, b.length);
}
public void write(byte b[], int off, int len) throws IOException {
if (closed) {
throw new IOException("Cannot write to a closed output stream");
}
gzipStream.write(b, off, len);
}
public boolean closed() {
return (this.closed);
}
public void reset() {
// noop
}
}
}

View File

@@ -41,6 +41,16 @@
<component-type>spring.faces.DojoIncludeStyles</component-type>
<component-class>org.springframework.faces.ui.DynamicComponent</component-class>
</component>
<component>
<component-type>spring.faces.ResourceGroup</component-type>
<component-class>org.springframework.faces.ui.DynamicComponent</component-class>
</component>
<component>
<component-type>spring.faces.Resource</component-type>
<component-class>org.springframework.faces.ui.DynamicComponent</component-class>
</component>
<component>
<component-type>spring.faces.DojoClientTextValidator</component-type>
@@ -131,6 +141,18 @@
<renderer-type>spring.faces.DojoStyleRenderer</renderer-type>
<renderer-class>org.springframework.faces.ui.DojoStyleRenderer</renderer-class>
</renderer>
<renderer>
<component-family>spring.faces.DynamicComponent</component-family>
<renderer-type>spring.faces.ResourceGroupRenderer</renderer-type>
<renderer-class>org.springframework.faces.ui.ResourceGroupRenderer</renderer-class>
</renderer>
<renderer>
<component-family>spring.faces.DynamicComponent</component-family>
<renderer-type>spring.faces.ResourceRenderer</renderer-type>
<renderer-class>org.springframework.faces.ui.ResourceRenderer</renderer-class>
</renderer>
</render-kit>
</faces-config>

View File

@@ -11,6 +11,20 @@
<renderer-type>spring.faces.DojoStyleRenderer</renderer-type>
</component>
</tag>
<tag>
<tag-name>resourceGroup</tag-name>
<component>
<component-type>spring.faces.ResourceGroup</component-type>
<renderer-type>spring.faces.ResourceGroupRenderer</renderer-type>
</component>
</tag>
<tag>
<tag-name>resource</tag-name>
<component>
<component-type>spring.faces.Resource</component-type>
<renderer-type>spring.faces.ResourceRenderer</renderer-type>
</component>
</tag>
<tag>
<tag-name>commandButton</tag-name>
<component>

View File

@@ -1,5 +1,8 @@
package org.springframework.faces.ui.resource;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
@@ -31,6 +34,20 @@ public class ResourceServletTests extends TestCase {
String requestPath = "/dojo/dojo.js";
request.setPathInfo(requestPath);
servlet.doGet(request, response);
assertEquals(200, response.getStatus());
}
public final void testExecute_CombinedResources() throws Exception {
String requestPath = "/dojo/dojo.js";
request.setPathInfo(requestPath);
Map params = new HashMap();
params.put("appended", "/dijit/dijit.js,/dijit/Dialog.js");
request.setParameters(params);
servlet.doGet(request, response);
assertEquals(200, response.getStatus());
}
public final void testExecute_ResourceNotFound() throws Exception {