JBoss Ajax4JSF SVN: r99 - in trunk/cdk/generator/src/main: resources/META-INF/templates and 1 other directory.
by ajax4jsf-svn-commits@lists.jboss.org
Author: nbelaevski
Date: 2007-04-18 06:44:19 -0400 (Wed, 18 Apr 2007)
New Revision: 99
Modified:
trunk/cdk/generator/src/main/java/org/ajax4jsf/builder/generator/ResourceConfigGeneratorBean.java
trunk/cdk/generator/src/main/java/org/ajax4jsf/builder/generator/ResourcesConfigGenerator.java
trunk/cdk/generator/src/main/resources/META-INF/templates/resources-config.vm
Log:
Leading '/' in package name handling fixed
Modified: trunk/cdk/generator/src/main/java/org/ajax4jsf/builder/generator/ResourceConfigGeneratorBean.java
===================================================================
--- trunk/cdk/generator/src/main/java/org/ajax4jsf/builder/generator/ResourceConfigGeneratorBean.java 2007-04-18 10:17:34 UTC (rev 98)
+++ trunk/cdk/generator/src/main/java/org/ajax4jsf/builder/generator/ResourceConfigGeneratorBean.java 2007-04-18 10:44:19 UTC (rev 99)
@@ -49,6 +49,10 @@
this.contentType = contentType;
}
public String getClassName() {
+ if (DEFAULT_CLASS_NAME.equals(className)) {
+ return null;
+ }
+
return className;
}
public void setClassName(String className) {
Modified: trunk/cdk/generator/src/main/java/org/ajax4jsf/builder/generator/ResourcesConfigGenerator.java
===================================================================
--- trunk/cdk/generator/src/main/java/org/ajax4jsf/builder/generator/ResourcesConfigGenerator.java 2007-04-18 10:17:34 UTC (rev 98)
+++ trunk/cdk/generator/src/main/java/org/ajax4jsf/builder/generator/ResourcesConfigGenerator.java 2007-04-18 10:44:19 UTC (rev 99)
@@ -84,15 +84,11 @@
private String resolveResourcePath(String name, String packageName) {
if (name.contains("/")) {
- String resolvedName = name;
+ String resolvedName;
if (!name.startsWith("/")) {
//need to resolve
StringBuffer normalizedName = new StringBuffer();
- if (!packageName.startsWith("/")) {
- normalizedName.append('/');
- }
-
normalizedName.append(packageName.replace('.', '/'));
if (!packageName.endsWith("/")) {
@@ -102,6 +98,12 @@
normalizedName.append(name);
resolvedName = normalizedName.toString();
+ } else {
+ if (name.length() > 0) {
+ resolvedName = name.substring(1);
+ } else {
+ resolvedName = null;
+ }
}
return resolvedName;
Modified: trunk/cdk/generator/src/main/resources/META-INF/templates/resources-config.vm
===================================================================
--- trunk/cdk/generator/src/main/resources/META-INF/templates/resources-config.vm 2007-04-18 10:17:34 UTC (rev 98)
+++ trunk/cdk/generator/src/main/resources/META-INF/templates/resources-config.vm 2007-04-18 10:44:19 UTC (rev 99)
@@ -1,13 +1,15 @@
<?xml version="1.0" encoding="UTF-8"?>
<resource-config>
-
#foreach( $resource in ${resources})
-<resource class="${resource.className}">
- <name>${resource.key}</name>
- #if(! ${resource.className})
- <path>${resource.path}</path>
+ #if(${resource.className})
+ <resource class="${resource.className}">
+ <name>${resource.key}</name>
+ </resource>
+ #else
+ <resource>
+ <name>${resource.key}</name>
+ <path>${resource.path}</path>
+ </resource>
#end
-</resource>
#end
-
</resource-config>
17 years, 8 months
JBoss Ajax4JSF SVN: r98 - in trunk: cdk/generator/src/main/resources/META-INF/templates and 1 other directories.
by ajax4jsf-svn-commits@lists.jboss.org
Author: nbelaevski
Date: 2007-04-18 06:17:34 -0400 (Wed, 18 Apr 2007)
New Revision: 98
Modified:
trunk/cdk/generator/src/main/java/org/ajax4jsf/builder/generator/ResourcesConfigGenerator.java
trunk/cdk/generator/src/main/resources/META-INF/templates/resources-config.vm
trunk/framework/src/main/java/org/ajax4jsf/framework/resource/ResourceBuilderImpl.java
Log:
Framework: resource builder sets renderer when configuring
Generator: class resources support added
Modified: trunk/cdk/generator/src/main/java/org/ajax4jsf/builder/generator/ResourcesConfigGenerator.java
===================================================================
--- trunk/cdk/generator/src/main/java/org/ajax4jsf/builder/generator/ResourcesConfigGenerator.java 2007-04-18 09:56:56 UTC (rev 97)
+++ trunk/cdk/generator/src/main/java/org/ajax4jsf/builder/generator/ResourcesConfigGenerator.java 2007-04-18 10:17:34 UTC (rev 98)
@@ -64,7 +64,14 @@
ResourceConfigGeneratorBean resourceConfig = new ResourceConfigGeneratorBean();
String name = resourceTemplateElement.getName();
resourceConfig.setKey(name);
- resourceConfig.setPath(resolvePath(name, packageName));
+
+ String resolvedPath = resolveResourcePath(name, packageName);
+ if (resolvedPath != null) {
+ resourceConfig.setPath(resolvedPath);
+ } else {
+ //couldn't resolve, treat as class name
+ resourceConfig.setClassName(name);
+ }
resources.add(resourceConfig);
}
@@ -75,27 +82,32 @@
}
}
- private String resolvePath(String name, String packageName) {
- String resolvedName = name;
- if (!name.startsWith("/") && name.contains("/")) {
- //need to resolve
- StringBuffer normalizedName = new StringBuffer();
- if (!packageName.startsWith("/")) {
- normalizedName.append('/');
- }
+ private String resolveResourcePath(String name, String packageName) {
+ if (name.contains("/")) {
+ String resolvedName = name;
- normalizedName.append(packageName.replace('.', '/'));
-
- if (!packageName.endsWith("/")) {
- normalizedName.append('/');
+ if (!name.startsWith("/")) {
+ //need to resolve
+ StringBuffer normalizedName = new StringBuffer();
+ if (!packageName.startsWith("/")) {
+ normalizedName.append('/');
+ }
+
+ normalizedName.append(packageName.replace('.', '/'));
+
+ if (!packageName.endsWith("/")) {
+ normalizedName.append('/');
+ }
+
+ normalizedName.append(name);
+
+ resolvedName = normalizedName.toString();
}
- normalizedName.append(name);
-
- resolvedName = normalizedName.toString();
+ return resolvedName;
}
- return resolvedName;
+ return null;
}
private void addResources(List<ResourceConfigGeneratorBean> resources, RendererBean renderer, BuilderConfig builderConfig) throws CompilationException, IOException, ClassNotFoundException {
Modified: trunk/cdk/generator/src/main/resources/META-INF/templates/resources-config.vm
===================================================================
--- trunk/cdk/generator/src/main/resources/META-INF/templates/resources-config.vm 2007-04-18 09:56:56 UTC (rev 97)
+++ trunk/cdk/generator/src/main/resources/META-INF/templates/resources-config.vm 2007-04-18 10:17:34 UTC (rev 98)
@@ -3,13 +3,10 @@
#foreach( $resource in ${resources})
<resource class="${resource.className}">
- <!-- renderer class="${resource.renderer.className}">
- <content-type>${resource.renderer.contentType}</content-type>
- </renderer -->
<name>${resource.key}</name>
+ #if(! ${resource.className})
<path>${resource.path}</path>
- <!-- content-type>${resource.contentType}</content-type -->
-
+ #end
</resource>
#end
Modified: trunk/framework/src/main/java/org/ajax4jsf/framework/resource/ResourceBuilderImpl.java
===================================================================
--- trunk/framework/src/main/java/org/ajax4jsf/framework/resource/ResourceBuilderImpl.java 2007-04-18 09:56:56 UTC (rev 97)
+++ trunk/framework/src/main/java/org/ajax4jsf/framework/resource/ResourceBuilderImpl.java 2007-04-18 10:17:34 UTC (rev 98)
@@ -42,8 +42,6 @@
import javax.faces.context.FacesContext;
import javax.imageio.ImageIO;
import javax.servlet.ServletContext;
-import javax.servlet.ServletException;
-import javax.servlet.http.HttpServletRequest;
import org.ajax4jsf.framework.util.base64.Codec;
import org.ajax4jsf.framework.util.config.WebXml;
@@ -375,6 +373,10 @@
public void addResource(InternetResource resource) {
resources.put(resource.getKey(), resource);
+ ResourceRenderer renderer = resource.getRenderer(null);
+ if (renderer == null) {
+ setRenderer(resource, resource.getKey());
+ }
}
public void addResource(String key, InternetResource resource) {
@@ -423,7 +425,7 @@
Messages.STATIC_RESOURCE_NOT_FOUND_ERROR, path));
}
- private void setRenderer(InternetResourceBase res, String path)
+ private void setRenderer(InternetResource res, String path)
throws FacesException {
int lastPoint = path.lastIndexOf('.');
if (lastPoint > 0) {
17 years, 8 months
JBoss Ajax4JSF SVN: r97 - in trunk: framework/src/main/config/component and 1 other directory.
by ajax4jsf-svn-commits@lists.jboss.org
Author: vkukharchuk
Date: 2007-04-18 05:56:56 -0400 (Wed, 18 Apr 2007)
New Revision: 97
Modified:
trunk/cdk/generator/src/main/resources/META-INF/schema/entities/html_anchor_attributes.ent
trunk/framework/src/main/config/component/commandButton.xml
trunk/framework/src/main/config/component/commandLink.xml
trunk/framework/src/main/config/component/form.xml
trunk/framework/src/main/config/component/poll.xml
Log:
Modified: trunk/cdk/generator/src/main/resources/META-INF/schema/entities/html_anchor_attributes.ent
===================================================================
--- trunk/cdk/generator/src/main/resources/META-INF/schema/entities/html_anchor_attributes.ent 2007-04-18 09:08:15 UTC (rev 96)
+++ trunk/cdk/generator/src/main/resources/META-INF/schema/entities/html_anchor_attributes.ent 2007-04-18 09:56:56 UTC (rev 97)
@@ -70,7 +70,7 @@
<property>
<name>onfocus</name>
<classname>java.lang.String</classname>
- <description>JavaScript code</description>
+ <description>JavaScript code. The onfocus event occurs when an element gets focus.</description>
</property>
<property>
Modified: trunk/framework/src/main/config/component/commandButton.xml
===================================================================
--- trunk/framework/src/main/config/component/commandButton.xml 2007-04-18 09:08:15 UTC (rev 96)
+++ trunk/framework/src/main/config/component/commandButton.xml 2007-04-18 09:56:56 UTC (rev 97)
@@ -93,6 +93,7 @@
<property>
<name>ignoreDupResponses</name>
<classname>boolean</classname>
+ <description>If true, unfinished request will be aborted on new event.</description>
</property>
<property>
<name>timeout</name>
Modified: trunk/framework/src/main/config/component/commandLink.xml
===================================================================
--- trunk/framework/src/main/config/component/commandLink.xml 2007-04-18 09:08:15 UTC (rev 96)
+++ trunk/framework/src/main/config/component/commandLink.xml 2007-04-18 09:56:56 UTC (rev 97)
@@ -73,6 +73,7 @@
<property>
<name>ignoreDupResponses</name>
<classname>boolean</classname>
+ <description>If true, unfinished request will be aborted on new event.</description>
</property>
<property>
<name>timeout</name>
Modified: trunk/framework/src/main/config/component/form.xml
===================================================================
--- trunk/framework/src/main/config/component/form.xml 2007-04-18 09:08:15 UTC (rev 96)
+++ trunk/framework/src/main/config/component/form.xml 2007-04-18 09:56:56 UTC (rev 97)
@@ -41,10 +41,12 @@
<property>
<name>ajaxSubmit</name>
<classname>boolean</classname>
+ <description>If true, it becomes possible to set AJAX submission way for any components inside .</description>
</property>
<property>
<name>ignoreDupResponses</name>
<classname>boolean</classname>
+ <description>If true, unfinished request will be aborted on new event.</description>
</property>
<property>
<name>timeout</name>
Modified: trunk/framework/src/main/config/component/poll.xml
===================================================================
--- trunk/framework/src/main/config/component/poll.xml 2007-04-18 09:08:15 UTC (rev 96)
+++ trunk/framework/src/main/config/component/poll.xml 2007-04-18 09:56:56 UTC (rev 97)
@@ -88,6 +88,7 @@
<property>
<name>ignoreDupResponses</name>
<classname>boolean</classname>
+ <description>If true, unfinished request will be aborted on new event.</description>
</property>
<property>
<name>timeout</name>
17 years, 8 months
JBoss Ajax4JSF SVN: r96 - trunk/cdk/maven-cdk-plugin/src/main/java/org/ajax4jsf/builder/mojo.
by ajax4jsf-svn-commits@lists.jboss.org
Author: nbelaevski
Date: 2007-04-18 05:08:15 -0400 (Wed, 18 Apr 2007)
New Revision: 96
Modified:
trunk/cdk/maven-cdk-plugin/src/main/java/org/ajax4jsf/builder/mojo/GenerateMojo.java
Log:
Conditional resources-config.xml generation switched on
Modified: trunk/cdk/maven-cdk-plugin/src/main/java/org/ajax4jsf/builder/mojo/GenerateMojo.java
===================================================================
--- trunk/cdk/maven-cdk-plugin/src/main/java/org/ajax4jsf/builder/mojo/GenerateMojo.java 2007-04-18 02:30:08 UTC (rev 95)
+++ trunk/cdk/maven-cdk-plugin/src/main/java/org/ajax4jsf/builder/mojo/GenerateMojo.java 2007-04-18 09:08:15 UTC (rev 96)
@@ -178,14 +178,18 @@
+ ".taglib.xml"));
faceletsTaglibGenerator.createFiles(config);
}
- // Generate resources configuration file resources-config.xml
- // for all images/scripts/css...
- ResourcesConfigGenerator resourcesConfigGenerator = new ResourcesConfigGenerator(resourcesConfiguration, mavenLogger);
- resourcesConfigGenerator.setTemplates(templatesDirectory);
- resourcesConfigGenerator.setResourcesConfig(new File(
- outputResourcesDirectory, "META-INF/resources-config.xml"));
- resourcesConfigGenerator.createFiles(config);
+ if (Boolean.getBoolean("generateResourcesConfig")) {
+
+ // Generate resources configuration file resources-config.xml
+ // for all images/scripts/css...
+ ResourcesConfigGenerator resourcesConfigGenerator = new ResourcesConfigGenerator(resourcesConfiguration, mavenLogger);
+ resourcesConfigGenerator.setTemplates(templatesDirectory);
+ resourcesConfigGenerator.setResourcesConfig(new File(
+ outputResourcesDirectory, "META-INF/resources-config.xml"));
+ resourcesConfigGenerator.createFiles(config);
+ }
+
// Add generated sources and resources to project
project.addCompileSourceRoot(outputJavaDirectory.getPath());
// project.addCompileSourceRoot(outputTestsDirectory.getPath());
17 years, 8 months
JBoss Ajax4JSF SVN: r95 - in trunk: framework/src/main/java/org/ajax4jsf/framework/resource and 3 other directories.
by ajax4jsf-svn-commits@lists.jboss.org
Author: alexsmirnov
Date: 2007-04-17 22:30:08 -0400 (Tue, 17 Apr 2007)
New Revision: 95
Modified:
trunk/framework/src/main/java/org/ajax4jsf/framework/ajax/xmlfilter/CacheContent.java
trunk/framework/src/main/java/org/ajax4jsf/framework/resource/InternetResourceBase.java
trunk/test/src/main/java/org/ajax4jsf/tests/AbstractAjax4JsfTestCase.java
trunk/test/src/test/java/org/ajax4jsf/framework/util/config/WebXmlTest.java
trunk/test/src/test/resources/log4j.xml
Log:
Fix unit tests
Modified: trunk/framework/src/main/java/org/ajax4jsf/framework/ajax/xmlfilter/CacheContent.java
===================================================================
--- trunk/framework/src/main/java/org/ajax4jsf/framework/ajax/xmlfilter/CacheContent.java 2007-04-18 00:59:13 UTC (rev 94)
+++ trunk/framework/src/main/java/org/ajax4jsf/framework/ajax/xmlfilter/CacheContent.java 2007-04-18 02:30:08 UTC (rev 95)
@@ -35,213 +35,251 @@
import org.ajax4jsf.io.FastBufferOutputStream;
import org.ajax4jsf.io.FastBufferWriter;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
/**
* @author shura (latest modification by $Author: alexsmirnov $)
* @version $Revision: 1.1.2.1 $ $Date: 2007/01/09 18:58:20 $
- *
+ *
*/
public class CacheContent implements Serializable {
- /**
- *
- */
- private static final long serialVersionUID = 8120940486890871177L;
-// private transient ByteArrayOutputStream outputStream ;
- private transient FastBufferOutputStream outputStream ;
- private transient FastBufferWriter stringOutputWriter;
- private transient PrintWriter servletWriter;
- private transient ServletOutputStream servletStream;
- // content to send.
- private byte[] content = null;
- private String writerContent = null;
+ /**
+ *
+ */
+ private static final long serialVersionUID = 8120940486890871177L;
+
+ private static final Log _log = LogFactory.getLog(CacheContent.class);
- boolean filledOutputStream = false;
- boolean filledOutputWriter = false;
- private Map headers = new HashMap();
- private String contentType;
-
- /**
- * Send saved content to http responce
- * @param response
- * @throws IOException
- */
- public void send(HttpServletResponse response) throws IOException{
- if (filledOutputStream) {
- OutputStream out = response.getOutputStream();
- if(content != null) {
- out.write(content);
- } else {
- this.outputStream.writeTo(out);
- }
-// out.flush();
-// out.close();
- } else if (filledOutputWriter) {
- Writer out = response.getWriter();
- if (null != writerContent) {
- out.write(writerContent);
- } else {
- stringOutputWriter.writeTo(out);
- }
-// out.flush();
-// out.close();
- }
+ // private transient ByteArrayOutputStream outputStream ;
+ private transient FastBufferOutputStream outputStream;
+
+ private transient FastBufferWriter stringOutputWriter;
+
+ private transient PrintWriter servletWriter;
+
+ private transient ServletOutputStream servletStream;
+
+ // content to send.
+ private byte[] content = null;
+
+ private String writerContent = null;
+
+ boolean filledOutputStream = false;
+
+ boolean filledOutputWriter = false;
+
+ private Map headers = new HashMap();
+
+ private String contentType;
+
+ /**
+ * Send saved content to http responce
+ *
+ * @param response
+ * @throws IOException
+ */
+ public void send(HttpServletResponse response) throws IOException {
+ if (filledOutputStream) {
+ OutputStream out = response.getOutputStream();
+ if (content != null) {
+ out.write(content);
+ } else {
+ this.outputStream.writeTo(out);
+ }
+ // out.flush();
+ // out.close();
+ } else if (filledOutputWriter) {
+ Writer out = response.getWriter();
+ if (null != writerContent) {
+ out.write(writerContent);
+ } else {
+ stringOutputWriter.writeTo(out);
+ }
+ // out.flush();
+ // out.close();
}
-
- /**
- * Send saved headers to http responce.
- * @param response
- */
- public void sendHeaders(HttpServletResponse response){
- for (Iterator iter = headers.entrySet().iterator(); iter.hasNext();) {
- Map.Entry element = (Map.Entry) iter.next();
- String header = (String) element.getKey();
- if (element.getValue() instanceof Long) {
- Long time = (Long) element.getValue();
- response.setDateHeader(header,time.longValue());
- } else if (element.getValue() instanceof Integer) {
- Integer value = (Integer) element.getValue();
- response.setIntHeader(header,value.intValue());
- } else {
- response.setHeader(header,(String) element.getValue());
- }
- // set real content-length.
-
-/// if (null != content) {
- if (filledOutputStream) {
-/// response.setIntHeader("Content-Length", content.length);
- response.setIntHeader("Content-Length", outputStream.getLength());
- } // TODO - calculate content-lenght for writer ?
- if( null != contentType){
- response.setContentType(this.contentType);
- }
+ }
+
+ /**
+ * Send saved headers to http responce.
+ *
+ * @param response
+ */
+ public void sendHeaders(HttpServletResponse response) {
+ for (Iterator iter = headers.entrySet().iterator(); iter.hasNext();) {
+ Map.Entry element = (Map.Entry) iter.next();
+ String header = (String) element.getKey();
+ Object headerValue = element.getValue();
+ try {
+ if (headerValue instanceof Long) {
+ Long time = (Long) headerValue;
+ response.setDateHeader(header, time.longValue());
+ } else if (headerValue instanceof Integer) {
+ Integer value = (Integer) headerValue;
+ response.setIntHeader(header, value.intValue());
+ } else {
+ response.setHeader(header, (String) headerValue);
}
- }
-
- public void setDateHeader(String name, long value) {
- // Expires not stored in cache - must be re-calculated for every response.
- if(!"Expires".equals(name)){
- headers.put(name, new Long(value));
- }
- }
- /* (non-Javadoc)
- * @see org.ajax4jsf.framework.resource.ResourceContext#setHeader(java.lang.String, java.lang.String)
- */
- public void setHeader(String name, String value) {
- headers.put(name,value);
+ } catch (Exception e) {
+ _log.error("Error set response header "+header+"for value "+headerValue, e);
+ }
+ // set real content-length.
+ // / if (null != content) {
+ if (filledOutputStream) {
+ // / response.setIntHeader("Content-Length", content.length);
+ response.setIntHeader("Content-Length", outputStream
+ .getLength());
+ } // TODO - calculate content-lenght for writer ?
+ if (null != contentType) {
+ response.setContentType(this.contentType);
+ }
}
+ }
- /* (non-Javadoc)
- * @see org.ajax4jsf.framework.resource.ResourceContext#setIntHeader(java.lang.String, int)
- */
- public void setIntHeader(String name, int value) {
- headers.put(name, new Integer(value));
+ public void setDateHeader(String name, long value) {
+ // Expires not stored in cache - must be re-calculated for every
+ // response.
+ if (!"Expires".equals(name)) {
+ headers.put(name, new Long(value));
}
+ }
- /**
- * Create UNIX command 'tee' like stream - send all data to servlet
- * @param responseStream
- * @return
- */
- public OutputStream getOutputStream(final OutputStream responseStream){
- if (null == servletStream) {
- outputStream = new FastBufferOutputStream(1024);
- servletStream = new ServletOutputStream(){
-
- /* (non-Javadoc)
- * @see java.io.OutputStream#close()
- */
- public void close() throws IOException {
- filledOutputStream = true;
-/// content = outputStream.toByteArray();
- responseStream.close();
- content = null;
- }
-
- /* (non-Javadoc)
- * @see java.io.OutputStream#flush()
- */
- public void flush() throws IOException {
- responseStream.flush();
- }
-
- /* (non-Javadoc)
- * @see java.io.OutputStream#write(byte[], int, int)
- */
- public void write(byte[] b, int off, int len) throws IOException {
- outputStream.write(b, off, len);
- responseStream.write(b, off, len);
- }
-
- /* (non-Javadoc)
- * @see java.io.OutputStream#write(byte[])
- */
- public void write(byte[] b) throws IOException {
- outputStream.write(b);
- responseStream.write(b);
- }
-
- public void write(int b) throws IOException {
- outputStream.write(b);
- responseStream.write(b);
- }
-
- };
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.ajax4jsf.framework.resource.ResourceContext#setHeader(java.lang.String,
+ * java.lang.String)
+ */
+ public void setHeader(String name, String value) {
+ headers.put(name, value);
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.ajax4jsf.framework.resource.ResourceContext#setIntHeader(java.lang.String,
+ * int)
+ */
+ public void setIntHeader(String name, int value) {
+ headers.put(name, new Integer(value));
+ }
+
+ /**
+ * Create UNIX command 'tee' like stream - send all data to servlet
+ *
+ * @param responseStream
+ * @return
+ */
+ public OutputStream getOutputStream(final OutputStream responseStream) {
+ if (null == servletStream) {
+ outputStream = new FastBufferOutputStream(1024);
+ servletStream = new ServletOutputStream() {
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see java.io.OutputStream#close()
+ */
+ public void close() throws IOException {
+ filledOutputStream = true;
+ // / content = outputStream.toByteArray();
+ responseStream.close();
+ content = null;
}
- return servletStream;
- }
-
- public PrintWriter getWriter( final Writer responseWriter) {
- if (null == servletWriter) {
- stringOutputWriter = new FastBufferWriter(1024);
- Writer out = new Writer() {
- public void write(char[] cbuf, int off, int len)
- throws IOException {
- responseWriter.write(cbuf, off, len);
- stringOutputWriter.write(cbuf, off, len);
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see java.io.OutputStream#flush()
+ */
+ public void flush() throws IOException {
+ responseStream.flush();
+ }
- public void flush() throws IOException {
- responseWriter.flush();
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see java.io.OutputStream#write(byte[], int, int)
+ */
+ public void write(byte[] b, int off, int len)
+ throws IOException {
+ outputStream.write(b, off, len);
+ responseStream.write(b, off, len);
+ }
- public void close() throws IOException {
- responseWriter.close();
-/// writerContent = stringOutputWriter.toString();
- filledOutputWriter = true;
- writerContent = null;
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see java.io.OutputStream#write(byte[])
+ */
+ public void write(byte[] b) throws IOException {
+ outputStream.write(b);
+ responseStream.write(b);
+ }
- };
- servletWriter = new PrintWriter(out);
+ public void write(int b) throws IOException {
+ outputStream.write(b);
+ responseStream.write(b);
}
- return servletWriter;
+
+ };
}
+ return servletStream;
+ }
- public void setContentType(String contentType) {
- this.contentType = contentType;
-
+ public PrintWriter getWriter(final Writer responseWriter) {
+ if (null == servletWriter) {
+ stringOutputWriter = new FastBufferWriter(1024);
+ Writer out = new Writer() {
+
+ public void write(char[] cbuf, int off, int len)
+ throws IOException {
+ responseWriter.write(cbuf, off, len);
+ stringOutputWriter.write(cbuf, off, len);
+ }
+
+ public void flush() throws IOException {
+ responseWriter.flush();
+ }
+
+ public void close() throws IOException {
+ responseWriter.close();
+ // / writerContent = stringOutputWriter.toString();
+ filledOutputWriter = true;
+ writerContent = null;
+ }
+
+ };
+ servletWriter = new PrintWriter(out);
}
+ return servletWriter;
+ }
- /**
- * @return Returns the contentType.
- */
- public String getContentType() {
- return contentType;
+ public void setContentType(String contentType) {
+ this.contentType = contentType;
+
+ }
+
+ /**
+ * @return Returns the contentType.
+ */
+ public String getContentType() {
+ return contentType;
+ }
+
+ private void writeObject(java.io.ObjectOutputStream s) throws IOException {
+ if (filledOutputStream) {
+ if (outputStream != null) {
+ content = outputStream.toByteArray();
+ }
+ } else if (filledOutputWriter) {
+ if (stringOutputWriter != null) {
+ char[] cs = stringOutputWriter.toCharArray();
+ writerContent = new String(cs);
+ }
}
-
- private void writeObject(java.io.ObjectOutputStream s) throws IOException {
- if(filledOutputStream) {
- if(outputStream != null) {
- content = outputStream.toByteArray();
- }
- } else if(filledOutputWriter) {
- if(stringOutputWriter != null) {
- char[] cs = stringOutputWriter.toCharArray();
- writerContent = new String(cs);
- }
- }
- s.defaultWriteObject();
- }
+ s.defaultWriteObject();
+ }
}
Modified: trunk/framework/src/main/java/org/ajax4jsf/framework/resource/InternetResourceBase.java
===================================================================
--- trunk/framework/src/main/java/org/ajax4jsf/framework/resource/InternetResourceBase.java 2007-04-18 00:59:13 UTC (rev 94)
+++ trunk/framework/src/main/java/org/ajax4jsf/framework/resource/InternetResourceBase.java 2007-04-18 02:30:08 UTC (rev 95)
@@ -391,8 +391,9 @@
} else {
// context.setHeader("Transfer-Encoding", "chunked");
}
- if (getLastModified(null) != null) {
- context.setDateHeader("Last-Modified", getLastModified(null).getTime());
+ Date lastModified = getLastModified(context);
+ if (lastModified != null) {
+ context.setDateHeader("Last-Modified", lastModified.getTime());
}
if (cached) {
Date expired = getExpired(context);
Modified: trunk/test/src/main/java/org/ajax4jsf/tests/AbstractAjax4JsfTestCase.java
===================================================================
--- trunk/test/src/main/java/org/ajax4jsf/tests/AbstractAjax4JsfTestCase.java 2007-04-18 00:59:13 UTC (rev 94)
+++ trunk/test/src/main/java/org/ajax4jsf/tests/AbstractAjax4JsfTestCase.java 2007-04-18 02:30:08 UTC (rev 95)
@@ -168,11 +168,12 @@
}
try {
- InternetResourceBuilder.getInstance().init(servletContext, "A4J");
- } catch (ServletException e) {
+ InternetResourceBuilder.getInstance().init();
+ } catch (FacesException e) {
InternetResourceBuilder.setInstance(null);
}
-// setupWebClient();
+ webXml = new WebXml();
+ webXml.init(servletContext, "A4J");
ConfigParser parser = new ConfigParser();
parser.parse(parser.getPlatformURLs());
@@ -471,4 +472,6 @@
// Thread context class loader saved and restored after each test
private ClassLoader threadContextClassLoader = null;
+ protected WebXml webXml;
+
}
Modified: trunk/test/src/test/java/org/ajax4jsf/framework/util/config/WebXmlTest.java
===================================================================
--- trunk/test/src/test/java/org/ajax4jsf/framework/util/config/WebXmlTest.java 2007-04-18 00:59:13 UTC (rev 94)
+++ trunk/test/src/test/java/org/ajax4jsf/framework/util/config/WebXmlTest.java 2007-04-18 02:30:08 UTC (rev 95)
@@ -69,7 +69,8 @@
* Test method for 'org.ajax4jsf.framework.util.config.WebXml.init(ServletContext, String)'
*/
public void testInit() throws ServletException {
- WebXml webXml = new WebXml(context,"ajax4jsf");
+ WebXml webXml = new WebXml();
+ webXml.init(context,"ajax4jsf");
assertFalse(webXml.isPrefixMapping());
assertNull(webXml.getFacesFilterPrefix());
assertNotNull(webXml.getFacesFilterSuffix());
@@ -87,7 +88,8 @@
* Test method for 'org.ajax4jsf.framework.util.config.WebXml.getFacesResourceURL(FacesContext, String)'
*/
public void testGetFacesResourceURL() throws ServletException {
- WebXml webXml = new WebXml(context,"ajax4jsf");
+ WebXml webXml = new WebXml();
+ webXml.init(context,"ajax4jsf");
String resourceURL = webXml.getFacesResourceURL(facesContext,"foo.Bar");
System.out.println(resourceURL);
assertEquals("/testContext/"+WebXml.RESOURCE_URI_PREFIX+"foo.Bar.jsf",resourceURL);
Modified: trunk/test/src/test/resources/log4j.xml
===================================================================
--- trunk/test/src/test/resources/log4j.xml 2007-04-18 00:59:13 UTC (rev 94)
+++ trunk/test/src/test/resources/log4j.xml 2007-04-18 02:30:08 UTC (rev 95)
@@ -43,12 +43,12 @@
</appender>
-->
<category name="com.sun.faces">
- <priority value="DEBUG" />
+ <priority value="INFO" />
<appender-ref ref="DEFAULT"/>
</category>
<category name="org.apache.myfaces">
- <priority value="DEBUG" />
+ <priority value="INFO" />
<appender-ref ref="DEFAULT"/>
</category>
@@ -63,13 +63,13 @@
</category>
<category name="com.exadel.vcp">
- <priority value="DEBUG" />
+ <priority value="INFO" />
<appender-ref ref="DEFAULT"/>
</category>
<category name="org.ajax4jsf">
- <priority value="DEBUG" />
+ <priority value="INFO" />
<appender-ref ref="DEFAULT"/>
</category>
17 years, 8 months
JBoss Ajax4JSF SVN: r94 - in trunk: framework/src/main/java/org/ajax4jsf/framework and 7 other directories.
by ajax4jsf-svn-commits@lists.jboss.org
Author: alexsmirnov
Date: 2007-04-17 20:59:13 -0400 (Tue, 17 Apr 2007)
New Revision: 94
Modified:
trunk/a4j-portlet/src/main/java/org/ajax4jsf/portlet/application/PortletViewHandler.java
trunk/framework/src/main/java/org/ajax4jsf/framework/DebugLifecycleFactory.java
trunk/framework/src/main/java/org/ajax4jsf/framework/ajax/AjaxScript.java
trunk/framework/src/main/java/org/ajax4jsf/framework/ajax/AjaxViewHandler.java
trunk/framework/src/main/java/org/ajax4jsf/framework/ajax/xmlfilter/BaseFilter.java
trunk/framework/src/main/java/org/ajax4jsf/framework/ajax/xmlfilter/BaseXMLFilter.java
trunk/framework/src/main/java/org/ajax4jsf/framework/renderer/ChameleonRenderKitFactory.java
trunk/framework/src/main/java/org/ajax4jsf/framework/resource/InternetResourceBuilder.java
trunk/framework/src/main/java/org/ajax4jsf/framework/resource/InternetResourceService.java
trunk/framework/src/main/java/org/ajax4jsf/framework/resource/ResourceBuilderImpl.java
trunk/framework/src/main/java/org/ajax4jsf/framework/resource/cached/CachedResourceBuilder.java
trunk/framework/src/main/java/org/ajax4jsf/framework/util/base64/Codec.java
trunk/framework/src/main/java/org/ajax4jsf/framework/util/config/WebXml.java
Log:
First start of portlet sample.
Modified: trunk/a4j-portlet/src/main/java/org/ajax4jsf/portlet/application/PortletViewHandler.java
===================================================================
--- trunk/a4j-portlet/src/main/java/org/ajax4jsf/portlet/application/PortletViewHandler.java 2007-04-17 21:04:13 UTC (rev 93)
+++ trunk/a4j-portlet/src/main/java/org/ajax4jsf/portlet/application/PortletViewHandler.java 2007-04-18 00:59:13 UTC (rev 94)
@@ -34,4 +34,8 @@
return super.getActionURL(context, url);
}
}
+
+ protected synchronized void fillChain(FacesContext context) {
+ // Do nothing - chain must be filled in AjaxViewHandler
+ }
}
Modified: trunk/framework/src/main/java/org/ajax4jsf/framework/DebugLifecycleFactory.java
===================================================================
--- trunk/framework/src/main/java/org/ajax4jsf/framework/DebugLifecycleFactory.java 2007-04-17 21:04:13 UTC (rev 93)
+++ trunk/framework/src/main/java/org/ajax4jsf/framework/DebugLifecycleFactory.java 2007-04-18 00:59:13 UTC (rev 94)
@@ -26,12 +26,18 @@
import javax.faces.lifecycle.Lifecycle;
import javax.faces.lifecycle.LifecycleFactory;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
/**
* @author shura (latest modification by $Author: alexsmirnov $)
* @version $Revision: 1.1.2.1 $ $Date: 2007/01/09 18:57:12 $
*
*/
public class DebugLifecycleFactory extends LifecycleFactory {
+
+ private static final Log _log = LogFactory
+ .getLog(DebugLifecycleFactory.class);
private LifecycleFactory _defaultFactory;
@@ -46,7 +52,6 @@
if (_debugLifecycle == null) {
_debugLifecycle = new DebugLifecycle(_defaultFactory);
}
-
return _debugLifecycle;
}
@@ -56,13 +61,19 @@
public DebugLifecycleFactory(LifecycleFactory defaultFactory) {
super();
this._defaultFactory = defaultFactory;
+ if (_log.isDebugEnabled()) {
+ _log.debug("Created Lifecycle instance");
+ }
}
/* (non-Javadoc)
* @see javax.faces.lifecycle.LifecycleFactory#addLifecycle(java.lang.String, javax.faces.lifecycle.Lifecycle)
*/
- public void addLifecycle(String arg0, Lifecycle arg1) {
- this._defaultFactory.addLifecycle(arg0, arg1);
+ public void addLifecycle(String lifecycleId, Lifecycle lifecycle) {
+ this._defaultFactory.addLifecycle(lifecycleId, lifecycle);
+ if (_log.isDebugEnabled()) {
+ _log.debug("Added lifecycle with ID "+lifecycleId);
+ }
}
/* (non-Javadoc)
Modified: trunk/framework/src/main/java/org/ajax4jsf/framework/ajax/AjaxScript.java
===================================================================
--- trunk/framework/src/main/java/org/ajax4jsf/framework/ajax/AjaxScript.java 2007-04-17 21:04:13 UTC (rev 93)
+++ trunk/framework/src/main/java/org/ajax4jsf/framework/ajax/AjaxScript.java 2007-04-18 00:59:13 UTC (rev 94)
@@ -21,6 +21,9 @@
package org.ajax4jsf.framework.ajax;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
import org.ajax4jsf.framework.resource.ClientScript;
/**
@@ -30,15 +33,18 @@
*
*/
public class AjaxScript extends ClientScript {
+
+ private static final Log _log = LogFactory.getLog(AjaxScript.class);
/**
* Set JavaScript renderer and modification time to application-startup time.
*/
public AjaxScript() {
super();
-// setRenderer(new ScriptRenderer());
-// setLastModified(new Date(InternetResourceBuilder.getInstance().getStartTime()));
+ if (_log.isDebugEnabled()) {
+ _log.debug("AjaxScript() - Created instance of AjaxScript resource"); //$NON-NLS-1$
}
+ }
/**
Modified: trunk/framework/src/main/java/org/ajax4jsf/framework/ajax/AjaxViewHandler.java
===================================================================
--- trunk/framework/src/main/java/org/ajax4jsf/framework/ajax/AjaxViewHandler.java 2007-04-17 21:04:13 UTC (rev 93)
+++ trunk/framework/src/main/java/org/ajax4jsf/framework/ajax/AjaxViewHandler.java 2007-04-18 00:59:13 UTC (rev 94)
@@ -63,6 +63,9 @@
*/
public AjaxViewHandler(ViewHandler parent) {
super(parent);
+ if (_log.isDebugEnabled()) {
+ _log.debug("Create instance of Ajax ViewHandler");
+ }
}
/*
Modified: trunk/framework/src/main/java/org/ajax4jsf/framework/ajax/xmlfilter/BaseFilter.java
===================================================================
--- trunk/framework/src/main/java/org/ajax4jsf/framework/ajax/xmlfilter/BaseFilter.java 2007-04-17 21:04:13 UTC (rev 93)
+++ trunk/framework/src/main/java/org/ajax4jsf/framework/ajax/xmlfilter/BaseFilter.java 2007-04-18 00:59:13 UTC (rev 94)
@@ -24,6 +24,7 @@
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Date;
+import java.util.Enumeration;
import javax.faces.application.ViewHandler;
import javax.servlet.Filter;
@@ -44,282 +45,316 @@
import org.apache.commons.logging.LogFactory;
/**
- * Base class for request processing filters, with convert Htmp content to
- * XML for ajax requests, and serve request to application off-page resources
+ * Base class for request processing filters, with convert Htmp content to XML
+ * for ajax requests, and serve request to application off-page resources
+ *
* @author shura (latest modification by $Author: alexsmirnov $)
* @version $Revision: 1.1.2.1 $ $Date: 2007/01/09 18:58:21 $
- *
+ *
*/
public abstract class BaseFilter implements Filter {
- private static final Log log = LogFactory.getLog(BaseFilter.class);
- public static final boolean DEBUG = true;
- private FilterConfig filterConfig;
- private static final String FUNCTION_NAME_PARAMETER = "function";
- private String function = "alert('Data received');JSHttpRequest.dataReady";
- private String attributesNames;
- private boolean rewriteid = false;
- private static final String REWRITEID_PARAMETER = "rewriteid";
- private static final String STYLESHEET_PARAMETER = "xsl";
- private static final String ABSOLUTE_TAGS_PARAMETER = "absolute-attributes";
-// private WebXml webXml;
-// private String xsl;
-// private Templates xslTemplates;
- /**
- *
- */
- private static final long serialVersionUID = -2295534611886142935L;
- public static final String DATA_PARAMETER = "DATA";
- public static final String DEFAULT_SERVLET_PATH = "/resource";
- public static final String RENDERER_PREFIX = "/renderer";
- public static final String CACHEABLE_PREFIX = "/cache";
-// private static final Pattern rendererPattern = Pattern.compile(RENDERER_PREFIX+"/([^/]+)/([^/]+)/([^/]+)/(.*)");
-// private static final Pattern builderPattern = Pattern.compile(CACHEABLE_PREFIX+"/(.*)");
- public static final String FILTER_PERFORMED = "com.exade.vcp.Filter.done";
- public static final String RESPONSE_WRAPPER_ATTRIBUTE = "com.exade.vcp.Filter.ResponseWrapper";
-
- protected BaseXMLFilter xmlFilter = null;
- InternetResourceService resourceService = null;
+ private static final Log log = LogFactory.getLog(BaseFilter.class);
+ public static final boolean DEBUG = true;
- /**
- * Initialize the filter.
- */
- public void init(FilterConfig config) throws ServletException {
- // Save config
- filterConfig = config;
- setFunction((String) nz(filterConfig.getInitParameter(FUNCTION_NAME_PARAMETER),getFunction()));
- setAttributesNames(filterConfig.getInitParameter(ABSOLUTE_TAGS_PARAMETER));
- // if( null != attributesNames){
- // this.absoluteAttributes = attributesNames.split(",");
- // }
- xmlFilter.init(config);
-// xsl = config.getInitParameter(STYLESHEET_PARAMETER);
- if("true".equalsIgnoreCase(filterConfig.getInitParameter(REWRITEID_PARAMETER))){
- this.setRewriteid(true);
- }
-
- // TODO - make all parameters configurable ...
- // Get Nekko parser features & properties.
- // Configure faces variables and log.
-// renderKitFactory = (RenderKitFactory) FactoryFinder.getFactory(FactoryFinder.RENDER_KIT_FACTORY);
- // InternetResourceBuilder.getInstance().setServletContext(getServletContext());
- // Log4J configuration. TODO - test for already configured logging.
-
- String prefix = filterConfig.getServletContext().getRealPath("/");
- String file = filterConfig.getInitParameter("log4j-init-file");
- // if the log4j-init-file is not set, then no point in trying
- if (file != null) {
- Log4JConfigurator log4jconfig = new Log4JConfigurator(prefix);
- log4jconfig.doConfigure(file);
- }
- // init webXml configuration.
-// WebXml.init(config.getServletContext(),config.getFilterName());
-// this.webXml = WebXml.getInstance();
- }
+ private FilterConfig filterConfig;
- /**
- * @param httpServletRequest
- * @throws UnsupportedEncodingException
- */
- protected void setupRequestEncoding(HttpServletRequest httpServletRequest) throws UnsupportedEncodingException {
- String contentType = httpServletRequest.getHeader("Content-Type");
-
- String characterEncoding = lookupCharacterEncoding(contentType);
-
- if (characterEncoding == null) {
- HttpSession session = httpServletRequest.getSession(false);
-
- if (session != null) {
- characterEncoding = (String) session.getAttribute(ViewHandler.CHARACTER_ENCODING_KEY);
- }
-
- if (characterEncoding != null) {
- httpServletRequest.setCharacterEncoding(characterEncoding);
- }
- }
- }
+ private static final String FUNCTION_NAME_PARAMETER = "function";
- /**
- * Detect request encoding from Content-Type header
- * @param contentType
- * @return - charset, if present.
- */
- private String lookupCharacterEncoding(String contentType) {
- String characterEncoding = null;
-
- if (contentType != null)
- {
- int charsetFind = contentType.indexOf("charset=");
- if (charsetFind != -1)
- {
- if (charsetFind == 0)
- {
- //charset at beginning of Content-Type, curious
- characterEncoding = contentType.substring(8);
- }
- else
- {
- char charBefore = contentType.charAt(charsetFind - 1);
- if (charBefore == ';' || Character.isWhitespace(charBefore))
- {
- //Correct charset after mime type
- characterEncoding = contentType.substring(charsetFind + 8);
- }
- }
- if (log.isDebugEnabled()) log.debug(Messages.getMessage(Messages.CONTENT_TYPE_ENCODING, characterEncoding));
- }
- else
- {
- if (log.isDebugEnabled()) log.debug(Messages.getMessage(Messages.CONTENT_TYPE_NO_ENCODING, contentType));
- }
+ private String function = "alert('Data received');JSHttpRequest.dataReady";
+
+ private String attributesNames;
+
+ private boolean rewriteid = false;
+
+ private static final String REWRITEID_PARAMETER = "rewriteid";
+
+ private static final String STYLESHEET_PARAMETER = "xsl";
+
+ private static final String ABSOLUTE_TAGS_PARAMETER = "absolute-attributes";
+
+ // private WebXml webXml;
+ // private String xsl;
+ // private Templates xslTemplates;
+ /**
+ *
+ */
+ private static final long serialVersionUID = -2295534611886142935L;
+
+ public static final String DATA_PARAMETER = "DATA";
+
+ public static final String DEFAULT_SERVLET_PATH = "/resource";
+
+ public static final String RENDERER_PREFIX = "/renderer";
+
+ public static final String CACHEABLE_PREFIX = "/cache";
+
+ // private static final Pattern rendererPattern =
+ // Pattern.compile(RENDERER_PREFIX+"/([^/]+)/([^/]+)/([^/]+)/(.*)");
+ // private static final Pattern builderPattern =
+ // Pattern.compile(CACHEABLE_PREFIX+"/(.*)");
+ public static final String FILTER_PERFORMED = "com.exade.vcp.Filter.done";
+
+ public static final String RESPONSE_WRAPPER_ATTRIBUTE = "com.exade.vcp.Filter.ResponseWrapper";
+
+ protected BaseXMLFilter xmlFilter = null;
+
+ InternetResourceService resourceService = null;
+
+ /**
+ * Initialize the filter.
+ */
+ public void init(FilterConfig config) throws ServletException {
+ if(log.isDebugEnabled()){
+ log.debug("Init ajax4jsf filter with nane: "+config.getFilterName());
+ Enumeration parameterNames = config.getInitParameterNames();
+ StringBuffer parameters = new StringBuffer("Init parameters :\n");
+ while (parameterNames.hasMoreElements()) {
+ String name = (String) parameterNames.nextElement();
+ parameters.append(name).append(" : '").append(config.getInitParameter(name)).append('\n');
}
- return characterEncoding;
+ log.debug(parameters);
+ log.debug("Stack Trace", new Exception());
}
+ // Save config
+ filterConfig = config;
+ setFunction((String) nz(filterConfig
+ .getInitParameter(FUNCTION_NAME_PARAMETER), getFunction()));
+ setAttributesNames(filterConfig
+ .getInitParameter(ABSOLUTE_TAGS_PARAMETER));
+ xmlFilter.init(config);
+ if ("true".equalsIgnoreCase(filterConfig
+ .getInitParameter(REWRITEID_PARAMETER))) {
+ this.setRewriteid(true);
+ }
- /**
- * @param initParameter
- * @param function2
- * @return
- */
- private Object nz(Object param, Object def) {
- return param != null?param:def;
+ String prefix = filterConfig.getServletContext().getRealPath("/");
+ String file = filterConfig.getInitParameter("log4j-init-file");
+ // if the log4j-init-file is not set, then no point in trying
+ if (file != null) {
+ Log4JConfigurator log4jconfig = new Log4JConfigurator(prefix);
+ log4jconfig.doConfigure(file);
}
+ resourceService = new InternetResourceService();
+ // Caching initialization.
+ resourceService.init(filterConfig);
+ }
- /**
- * Execute the filter.
- */
- public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
- long startTimeMills =0;
- // Detect case of request - normal, AJAX, AJAX - JavaScript
- // TODO - detect first processing in filter.
- HttpServletRequest httpServletRequest =(HttpServletRequest) request;
- HttpServletResponse httpServletResponse = (HttpServletResponse) response;
- if (log.isDebugEnabled()) {
- startTimeMills = System.currentTimeMillis();
- log.debug(Messages.getMessage(Messages.FILTER_START_INFO, new Date(startTimeMills), httpServletRequest.getRequestURI()));
- }
+ /**
+ * @param httpServletRequest
+ * @throws UnsupportedEncodingException
+ */
+ protected void setupRequestEncoding(HttpServletRequest httpServletRequest)
+ throws UnsupportedEncodingException {
+ String contentType = httpServletRequest.getHeader("Content-Type");
- if ( request.getAttribute(FILTER_PERFORMED) != Boolean.TRUE) {
- // mark - and not processing same request twice.
- request.setAttribute(FILTER_PERFORMED,Boolean.TRUE);
- // check for resource request
- if ( ! getResourceService().serviceResource( httpServletRequest,
- httpServletResponse) ) {
- // Not request to resource - perform filtering.
- // first stage - detect/set encoding of request. Same as in Myfaces External Context.
- setupRequestEncoding(httpServletRequest);
- // check ajax request parameter
- // TODO - check for JSF page.
- if (true) {
- if (log.isDebugEnabled()) {
- log.debug(Messages.getMessage(Messages.FILTER_XML_OUTPUT));
- }
+ String characterEncoding = lookupCharacterEncoding(contentType);
- // Execute the rest of the filter chain, including the JSP
- xmlFilter.doXmlFilter(chain, httpServletRequest, httpServletResponse);
- } else {
- // normal request, execute chain ...
- if (log.isDebugEnabled()) {
- log.debug(Messages.getMessage(Messages.FILTER_NO_XML_CHAIN));
- }
- chain.doFilter(request, response);
+ if (characterEncoding == null) {
+ HttpSession session = httpServletRequest.getSession(false);
- }
- }
- } else {
- if (log.isDebugEnabled()) {
- log.debug(Messages.getMessage(Messages.FILTER_NO_XML_CHAIN_2));
- }
- chain.doFilter(request, response);
+ if (session != null) {
+ characterEncoding = (String) session
+ .getAttribute(ViewHandler.CHARACTER_ENCODING_KEY);
+ }
- }
- if (log.isDebugEnabled()) {
- startTimeMills = System.currentTimeMillis()-startTimeMills;
- log.debug(Messages.getMessage(Messages.FILTER_STOP_INFO, "" + startTimeMills, httpServletRequest.getRequestURI()));
- }
+ if (characterEncoding != null) {
+ httpServletRequest.setCharacterEncoding(characterEncoding);
+ }
}
+ }
- /**
- * @param request
- * @return
- */
- protected boolean isAjaxRequest(ServletRequest request) {
- try {
- return null != request
- .getParameter(AjaxContainerRenderer.AJAX_PARAMETER_NAME);
- } catch (Exception e) {
- // OCJ 10 - throw exception for static resources.
- return false;
+ /**
+ * Detect request encoding from Content-Type header
+ *
+ * @param contentType
+ * @return - charset, if present.
+ */
+ private String lookupCharacterEncoding(String contentType) {
+ String characterEncoding = null;
+
+ if (contentType != null) {
+ int charsetFind = contentType.indexOf("charset=");
+ if (charsetFind != -1) {
+ if (charsetFind == 0) {
+ // charset at beginning of Content-Type, curious
+ characterEncoding = contentType.substring(8);
+ } else {
+ char charBefore = contentType.charAt(charsetFind - 1);
+ if (charBefore == ';' || Character.isWhitespace(charBefore)) {
+ // Correct charset after mime type
+ characterEncoding = contentType
+ .substring(charsetFind + 8);
+ }
}
+ if (log.isDebugEnabled())
+ log.debug(Messages.getMessage(
+ Messages.CONTENT_TYPE_ENCODING, characterEncoding));
+ } else {
+ if (log.isDebugEnabled())
+ log.debug(Messages.getMessage(
+ Messages.CONTENT_TYPE_NO_ENCODING, contentType));
+ }
}
+ return characterEncoding;
+ }
- /**
- * Destroy the filter.
- */
- public void destroy() {
- }
+ /**
+ * @param initParameter
+ * @param function2
+ * @return
+ */
+ private Object nz(Object param, Object def) {
+ return param != null ? param : def;
+ }
- /**
- * @return Returns the servletContext.
- */
- ServletContext getServletContext() {
- return filterConfig.getServletContext();
+ /**
+ * Execute the filter.
+ */
+ public void doFilter(ServletRequest request, ServletResponse response,
+ FilterChain chain) throws IOException, ServletException {
+ long startTimeMills = 0;
+ // Detect case of request - normal, AJAX, AJAX - JavaScript
+ // TODO - detect first processing in filter.
+ HttpServletRequest httpServletRequest = (HttpServletRequest) request;
+ HttpServletResponse httpServletResponse = (HttpServletResponse) response;
+ if (log.isDebugEnabled()) {
+ startTimeMills = System.currentTimeMillis();
+ log.debug(Messages.getMessage(Messages.FILTER_START_INFO, new Date(
+ startTimeMills), httpServletRequest.getRequestURI()));
}
- /**
- * @return the resourceService
- * @throws ServletException
- */
- protected synchronized InternetResourceService getResourceService() throws ServletException {
- if (resourceService == null) {
- resourceService = new InternetResourceService();
- // Caching initialization.
- resourceService.init(filterConfig);
-
+ if (request.getAttribute(FILTER_PERFORMED) != Boolean.TRUE) {
+ // mark - and not processing same request twice.
+ request.setAttribute(FILTER_PERFORMED, Boolean.TRUE);
+ // check for resource request
+ if (!getResourceService().serviceResource(httpServletRequest,
+ httpServletResponse)) {
+ // Not request to resource - perform filtering.
+ // first stage - detect/set encoding of request. Same as in
+ // Myfaces External Context.
+ setupRequestEncoding(httpServletRequest);
+ // check ajax request parameter
+ // TODO - check for JSF page.
+ if (true) {
+ if (log.isDebugEnabled()) {
+ log.debug(Messages
+ .getMessage(Messages.FILTER_XML_OUTPUT));
+ }
+
+ // Execute the rest of the filter chain, including the
+ // JSP
+ xmlFilter.doXmlFilter(chain, httpServletRequest,
+ httpServletResponse);
+ } else {
+ // normal request, execute chain ...
+ if (log.isDebugEnabled()) {
+ log.debug(Messages
+ .getMessage(Messages.FILTER_NO_XML_CHAIN));
+ }
+ chain.doFilter(request, response);
+
}
- return resourceService;
- }
+ }
+ } else {
+ if (log.isDebugEnabled()) {
+ log.debug(Messages.getMessage(Messages.FILTER_NO_XML_CHAIN_2));
+ }
+ chain.doFilter(request, response);
- /**
- * @param function The function to set.
- */
- protected void setFunction(String function) {
- this.function = function;
}
-
- /**
- * @return Returns the function.
- */
- protected String getFunction() {
- return function;
+ if (log.isDebugEnabled()) {
+ startTimeMills = System.currentTimeMillis() - startTimeMills;
+ log.debug(Messages.getMessage(Messages.FILTER_STOP_INFO, ""
+ + startTimeMills, httpServletRequest.getRequestURI()));
}
+ }
- /**
- * @param rewriteid The rewriteid to set.
- */
- protected void setRewriteid(boolean rewriteid) {
- this.rewriteid = rewriteid;
+ /**
+ * @param request
+ * @return
+ */
+ protected boolean isAjaxRequest(ServletRequest request) {
+ try {
+ return null != request
+ .getParameter(AjaxContainerRenderer.AJAX_PARAMETER_NAME);
+ } catch (Exception e) {
+ // OCJ 10 - throw exception for static resources.
+ return false;
}
+ }
- /**
- * @return Returns the rewriteid.
- */
- protected boolean isRewriteid() {
- return rewriteid;
- }
+ /**
+ * Destroy the filter.
+ */
+ public void destroy() {
+ }
- /**
- * @param attributesNames The attributesNames to set.
- */
- protected void setAttributesNames(String attributesNames) {
- this.attributesNames = attributesNames;
- }
+ /**
+ * @return Returns the servletContext.
+ */
+ ServletContext getServletContext() {
+ return filterConfig.getServletContext();
+ }
- /**
- * @return Returns the attributesNames.
- */
- protected String getAttributesNames() {
- return attributesNames;
- }
+ /**
+ * @return the resourceService
+ * @throws ServletException
+ */
+ protected synchronized InternetResourceService getResourceService()
+ throws ServletException {
+// if (resourceService == null) {
+// resourceService = new InternetResourceService();
+// // Caching initialization.
+// resourceService.init(filterConfig);
+//
+// }
+ return resourceService;
+ }
+
+ /**
+ * @param function
+ * The function to set.
+ */
+ protected void setFunction(String function) {
+ this.function = function;
+ }
+
+ /**
+ * @return Returns the function.
+ */
+ protected String getFunction() {
+ return function;
+ }
+
+ /**
+ * @param rewriteid
+ * The rewriteid to set.
+ */
+ protected void setRewriteid(boolean rewriteid) {
+ this.rewriteid = rewriteid;
+ }
+
+ /**
+ * @return Returns the rewriteid.
+ */
+ protected boolean isRewriteid() {
+ return rewriteid;
+ }
+
+ /**
+ * @param attributesNames
+ * The attributesNames to set.
+ */
+ protected void setAttributesNames(String attributesNames) {
+ this.attributesNames = attributesNames;
+ }
+
+ /**
+ * @return Returns the attributesNames.
+ */
+ protected String getAttributesNames() {
+ return attributesNames;
+ }
}
Modified: trunk/framework/src/main/java/org/ajax4jsf/framework/ajax/xmlfilter/BaseXMLFilter.java
===================================================================
--- trunk/framework/src/main/java/org/ajax4jsf/framework/ajax/xmlfilter/BaseXMLFilter.java 2007-04-17 21:04:13 UTC (rev 93)
+++ trunk/framework/src/main/java/org/ajax4jsf/framework/ajax/xmlfilter/BaseXMLFilter.java 2007-04-18 00:59:13 UTC (rev 94)
@@ -45,304 +45,366 @@
import org.apache.commons.logging.LogFactory;
public abstract class BaseXMLFilter {
- private static final Log log = LogFactory.getLog(BaseXMLFilter.class);
- public static final String RESPONSE_WRAPPER_ATTRIBUTE = "com.exade.vcp.Filter.ResponseWrapper";
+ private static final Log log = LogFactory.getLog(BaseXMLFilter.class);
- private String mimetype = "text/xml";
- private String publicid = "-//W3C//DTD XHTML 1.0 Transitional//EN";
- private String systemid = "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd";
- private String namespace = "http://www.w3.org/1999/xhtml";
+ public static final String RESPONSE_WRAPPER_ATTRIBUTE = "com.exade.vcp.Filter.ResponseWrapper";
- private static final String MIME_TYPE_PARAMETER = "mime-type";
- private static final String PUBLICID_PARAMETER = "publicid";
- private static final String SYSTEMID_PARAMETER = "systemid";
- private static final String NAMESPACE_PARAMETER = "namespace";
-
- private boolean forcexml = false;
- private static final String FORCEXML_PARAMETER = "forceparser";
- public BaseFilter filter;
-
- public void setFilter(BaseFilter filter) {
- this.filter = filter;
- }
+ private String mimetype = "text/xml";
- public void init(FilterConfig config) throws ServletException {
- if("false".equalsIgnoreCase(config.getInitParameter(FORCEXML_PARAMETER))){
- this.forcexml = false;
- }
- if("true".equalsIgnoreCase(config.getInitParameter(FORCEXML_PARAMETER))){
- this.forcexml = true;
- }
- setMimetype((String) nz(config.getInitParameter(MIME_TYPE_PARAMETER),"text/xml"));
- setPublicid((String) nz(config.getInitParameter(PUBLICID_PARAMETER),getPublicid()));
- setSystemid((String) nz(config.getInitParameter(SYSTEMID_PARAMETER),getSystemid()));
- setNamespace((String) nz(config.getInitParameter(NAMESPACE_PARAMETER),getNamespace()));
- }
+ private String publicid = "-//W3C//DTD XHTML 1.0 Transitional//EN";
- /**
- * Perform filter chain with xml parsing and transformation. Subclasses must implement
- * concrete HTML to XML parsing, nesseasary transformations and serialization.
- * @param chain
- * @param httpServletRequest
- * @param httpServletResponse
- * @throws ServletException
- * @throws IOException
- */
- protected void doXmlFilter(FilterChain chain, HttpServletRequest request, final HttpServletResponse response) throws IOException, ServletException {
- FilterServletResponseWrapper servletResponseWrapper = getWrapper(response);
- // HACK - to avoid MyFaces <f:view> incompabilites and bypass intermediaty filters
- // in chain, self-rendered region write directly to wrapper stored in request-scope attribute.
- request.setAttribute(RESPONSE_WRAPPER_ATTRIBUTE,servletResponseWrapper);
- chain.doFilter(request, servletResponseWrapper);
- // TidyParser parser = getParser(servletResponseWrapper.getCharacterEncoding());
- HtmlParser parser = null;
- // setup response
- // Redirect in AJAX request - convert to special response recognized by client.
- String redirectLocation = servletResponseWrapper.getRedirectLocation();
- String characterEncoding = servletResponseWrapper.getCharacterEncoding();
- Writer output;
- if(null != redirectLocation){
- if (isAjaxRequest(request)) {
- // Special handling of redirect - client-side script must
- // Check for response and perform redirect by window.location
- if(log.isDebugEnabled()){
- log.debug("Create AJAX redirect response to url: "+redirectLocation);
- }
- response.reset();
- // Copy response headers
- Map headers = servletResponseWrapper.getHeaders();
- for (Iterator iter = headers.entrySet().iterator(); iter.hasNext();) {
- Map.Entry header = (Map.Entry) iter.next();
- response.setHeader((String)header.getKey(), (String)header.getValue());
- }
- response.setHeader(AjaxContainerRenderer.AJAX_FLAG_HEADER,"redirect");
- // Not caching AJAX request
- response.setHeader("Cache-Control",
- "no-cache, must-revalidate, max_age=0, no-store");
- response.setHeader("Expires", "0");
- response.setHeader("Pragma", "no-cache");
- response.setContentType(getMimetype() + ";charset=UTF-8");
- response.setHeader(AjaxContainerRenderer.AJAX_LOCATION_HEADER,redirectLocation);
- output = createResponseWriter(response, "UTF-8");
- // For buggy XmlHttpRequest realisations repeat headers in <meta>
- output.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
- "<html xmlns=\"http://www.w3.org/1999/xhtml\"><head>"+
- "<meta name=\""+AjaxContainerRenderer.AJAX_FLAG_HEADER+"\" content=\"redirect\" />"+
- "<meta name=\""+AjaxContainerRenderer.AJAX_LOCATION_HEADER+"\" content=\""+redirectLocation+"\" />"+
- "</head></html>"
- );
- output.flush();
- response.flushBuffer();
- } else {
- response.sendRedirect(redirectLocation);
- }
- return;
- } else if ("true".equals(servletResponseWrapper.getHeaders().get(AjaxContainerRenderer.AJAX_FLAG_HEADER))) {
- if(log.isDebugEnabled()){
- log.debug("Process response to well-formed XML for AJAX XMLHttpRequest parser");
- }
- // Not caching AJAX request
- response.setHeader("Cache-Control",
- "no-cache, must-revalidate, max_age=0, no-store");
- response.setHeader("Expires", "0");
- response.setHeader("Pragma", "no-cache");
- //response.setCharacterEncoding(servletResponseWrapper
- //.getCharacterEncoding()); // JSContentHandler.DEFAULT_ENCODING);
- // Set the content-type. For AJAX responses default encoding - UTF8.
- // TODO - for null encoding, setup only Output encoding for filter ?
- String outputEncoding = "UTF-8";
- String contentType = getMimetype() + ";charset=" + outputEncoding;
- response.setContentType(contentType);
- parser = getParser(getMimetype(),true);
- if(null == parser){
- throw new ServletException(Messages.getMessage(Messages.PARSER_NOT_INSTANTIATED_ERROR, contentType));
- }
- output = createResponseWriter(response, outputEncoding);
- parser.setDoctype(getPublicid());
- parser.setInputEncoding(characterEncoding);
- parser.setOutputEncoding(outputEncoding);
- parser.setViewState((String) request.getAttribute(AjaxViewHandler.SERIALIZED_STATE_KEY));
- } else {
- // setup conversion reules for output contentType, send directly if content not
- // supported by tidy.
- String contentType = servletResponseWrapper.getContentType();
- if(log.isDebugEnabled()){
- log.debug("create HTML/XML parser for content type: "+contentType);
- }
-// if(contentType == null){
-// contentType = request.getContentType();
-// }
- if(contentType != null){
- if (contentType.indexOf("charset")<0 && null != characterEncoding) {
- contentType += ";charset=" + characterEncoding;
- }
- parser = getParser(contentType,false);
- response.setContentType(contentType);
- }
- // null or unsupported content type
- if(null == parser) {
- if(log.isDebugEnabled()){
- log.debug("Parser not have support for the such content type, send response as-is");
- }
- try {
- if (servletResponseWrapper.isUseWriter()) {
- output = createResponseWriter(response, characterEncoding);
- servletResponseWrapper.sendContent(output);
- } else if (servletResponseWrapper.isUseStream()) {
- ServletOutputStream out = response.getOutputStream();
- servletResponseWrapper.sendContent(out);
- }
- } finally {
- // reuseWrapper(servletResponseWrapper);
- }
- return;
- }
- output = createResponseWriter(response, characterEncoding);
+ private String systemid = "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd";
- parser.setInputEncoding(characterEncoding);
- parser.setOutputEncoding(characterEncoding);
- }
-
- try {
- // Setup scripts and styles
- parser.setScripts((Set) request.getAttribute(AjaxContext.SCRIPTS_PARAMETER));
- parser.setStyles((Set) request.getAttribute(AjaxContext.STYLES_PARAMETER));
- // Process parsing.
- long startTimeMills =System.currentTimeMillis();
- servletResponseWrapper.parseContent(output,parser);
- if (log.isDebugEnabled()) {
- startTimeMills = System.currentTimeMillis()-startTimeMills;
- log.debug(Messages.getMessage(Messages.PARSING_TIME_INFO, "" + startTimeMills));
- }
- } catch (Exception e) {
- throw new ServletException(Messages.getMessage(Messages.JTIDY_PARSING_ERROR), e);
- } finally {
- reuseParser(parser);
- }
- }
+ private String namespace = "http://www.w3.org/1999/xhtml";
- /**
- * @param response
- * @return
- * @throws ServletException
- */
- protected FilterServletResponseWrapper getWrapper(HttpServletResponse response) throws ServletException{
- return new FilterServletResponseWrapper(response);
+ private static final String MIME_TYPE_PARAMETER = "mime-type";
+
+ private static final String PUBLICID_PARAMETER = "publicid";
+
+ private static final String SYSTEMID_PARAMETER = "systemid";
+
+ private static final String NAMESPACE_PARAMETER = "namespace";
+
+ private boolean forcexml = false;
+
+ private static final String FORCEXML_PARAMETER = "forceparser";
+
+ public BaseFilter filter;
+
+ public void setFilter(BaseFilter filter) {
+ this.filter = filter;
+ }
+
+ public void init(FilterConfig config) throws ServletException {
+ if (log.isDebugEnabled()) {
+ log.debug("init XML filter service with class "
+ + this.getClass().getName());
}
-
- /**
- * @param request
- * @return
- */
- protected boolean isAjaxRequest(ServletRequest request) {
- try {
- return null != request
- .getParameter(AjaxContainerRenderer.AJAX_PARAMETER_NAME);
- } catch (Exception e) {
- // OCJ 10 - throw exception for static resources.
- return false;
- }
+ if ("false".equalsIgnoreCase(config
+ .getInitParameter(FORCEXML_PARAMETER))) {
+ this.forcexml = false;
}
+ if ("true"
+ .equalsIgnoreCase(config.getInitParameter(FORCEXML_PARAMETER))) {
+ this.forcexml = true;
+ }
+ setMimetype((String) nz(config.getInitParameter(MIME_TYPE_PARAMETER),
+ "text/xml"));
+ setPublicid((String) nz(config.getInitParameter(PUBLICID_PARAMETER),
+ getPublicid()));
+ setSystemid((String) nz(config.getInitParameter(SYSTEMID_PARAMETER),
+ getSystemid()));
+ setNamespace((String) nz(config.getInitParameter(NAMESPACE_PARAMETER),
+ getNamespace()));
+ }
- /**
- * @param response
- * @param characterEncoding
- * @return
- * @throws IOException
- * @throws UnsupportedEncodingException
- */
- private Writer createResponseWriter(final HttpServletResponse response, String characterEncoding) throws IOException, UnsupportedEncodingException {
- Writer output;
+ /**
+ * Perform filter chain with xml parsing and transformation. Subclasses
+ * must implement concrete HTML to XML parsing, nesseasary
+ * transformations and serialization.
+ *
+ * @param chain
+ * @param httpServletRequest
+ * @param httpServletResponse
+ * @throws ServletException
+ * @throws IOException
+ */
+ protected void doXmlFilter(FilterChain chain, HttpServletRequest request,
+ final HttpServletResponse response) throws IOException,
+ ServletException {
+ if (log.isDebugEnabled()) {
+ log.debug("XML filter service start processing request");
+ }
+ FilterServletResponseWrapper servletResponseWrapper = getWrapper(response);
+ // HACK - to avoid MyFaces <f:view> incompabilites and bypass
+ // intermediaty filters
+ // in chain, self-rendered region write directly to wrapper stored in
+ // request-scope attribute.
+ request
+ .setAttribute(RESPONSE_WRAPPER_ATTRIBUTE,
+ servletResponseWrapper);
+ chain.doFilter(request, servletResponseWrapper);
+ HtmlParser parser = null;
+ // setup response
+ // Redirect in AJAX request - convert to special response recognized by
+ // client.
+ String redirectLocation = servletResponseWrapper.getRedirectLocation();
+ String characterEncoding = servletResponseWrapper
+ .getCharacterEncoding();
+ Writer output;
+ if (null != redirectLocation) {
+ if (isAjaxRequest(request)) {
+ // Special handling of redirect - client-side script must
+ // Check for response and perform redirect by window.location
+ if (log.isDebugEnabled()) {
+ log.debug("Create AJAX redirect response to url: "
+ + redirectLocation);
+ }
+ response.reset();
+ // Copy response headers
+ Map headers = servletResponseWrapper.getHeaders();
+ for (Iterator iter = headers.entrySet().iterator(); iter
+ .hasNext();) {
+ Map.Entry header = (Map.Entry) iter.next();
+ response.setHeader((String) header.getKey(),
+ (String) header.getValue());
+ }
+ response.setHeader(AjaxContainerRenderer.AJAX_FLAG_HEADER,
+ "redirect");
+ // Not caching AJAX request
+ response.setHeader("Cache-Control",
+ "no-cache, must-revalidate, max_age=0, no-store");
+ response.setHeader("Expires", "0");
+ response.setHeader("Pragma", "no-cache");
+ response.setContentType(getMimetype() + ";charset=UTF-8");
+ response.setHeader(AjaxContainerRenderer.AJAX_LOCATION_HEADER,
+ redirectLocation);
+ output = createResponseWriter(response, "UTF-8");
+ // For buggy XmlHttpRequest realisations repeat headers in
+ // <meta>
+ output.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
+ + "<html xmlns=\"http://www.w3.org/1999/xhtml\"><head>"
+ + "<meta name=\""
+ + AjaxContainerRenderer.AJAX_FLAG_HEADER
+ + "\" content=\"redirect\" />" + "<meta name=\""
+ + AjaxContainerRenderer.AJAX_LOCATION_HEADER
+ + "\" content=\"" + redirectLocation + "\" />"
+ + "</head></html>");
+ output.flush();
+ response.flushBuffer();
+ } else {
+ response.sendRedirect(redirectLocation);
+ }
+ return;
+ } else if ("true".equals(servletResponseWrapper.getHeaders().get(
+ AjaxContainerRenderer.AJAX_FLAG_HEADER))) {
+ if (log.isDebugEnabled()) {
+ log
+ .debug("Process response to well-formed XML for AJAX XMLHttpRequest parser");
+ }
+ // Not caching AJAX request
+ response.setHeader("Cache-Control",
+ "no-cache, must-revalidate, max_age=0, no-store");
+ response.setHeader("Expires", "0");
+ response.setHeader("Pragma", "no-cache");
+ // response.setCharacterEncoding(servletResponseWrapper
+ // .getCharacterEncoding()); //
+ // JSContentHandler.DEFAULT_ENCODING);
+ // Set the content-type. For AJAX responses default encoding -
+ // UTF8.
+ // TODO - for null encoding, setup only Output encoding for
+ // filter ?
+ String outputEncoding = "UTF-8";
+ String contentType = getMimetype() + ";charset=" + outputEncoding;
+ response.setContentType(contentType);
+ parser = getParser(getMimetype(), true);
+ if (null == parser) {
+ throw new ServletException(Messages.getMessage(
+ Messages.PARSER_NOT_INSTANTIATED_ERROR, contentType));
+ }
+ output = createResponseWriter(response, outputEncoding);
+ parser.setDoctype(getPublicid());
+ parser.setInputEncoding(characterEncoding);
+ parser.setOutputEncoding(outputEncoding);
+ parser.setViewState((String) request
+ .getAttribute(AjaxViewHandler.SERIALIZED_STATE_KEY));
+ } else {
+ // setup conversion reules for output contentType, send directly
+ // if content not
+ // supported by tidy.
+ String contentType = servletResponseWrapper.getContentType();
+ if (log.isDebugEnabled()) {
+ log.debug("create HTML/XML parser for content type: "
+ + contentType);
+ }
+ // if(contentType == null){
+ // contentType = request.getContentType();
+ // }
+ if (contentType != null) {
+ if (contentType.indexOf("charset") < 0
+ && null != characterEncoding) {
+ contentType += ";charset=" + characterEncoding;
+ }
+ parser = getParser(contentType, false);
+ response.setContentType(contentType);
+ }
+ // null or unsupported content type
+ if (null == parser) {
+ if (log.isDebugEnabled()) {
+ log
+ .debug("Parser not have support for the such content type, send response as-is");
+ }
try {
- output = response.getWriter();
- } catch (IllegalStateException e) {
- if (null != characterEncoding) {
- output = new OutputStreamWriter(response.getOutputStream(),
- characterEncoding);
- } else {
- output = new OutputStreamWriter(response.getOutputStream());
- }
+ if (servletResponseWrapper.isUseWriter()) {
+ output = createResponseWriter(response,
+ characterEncoding);
+ servletResponseWrapper.sendContent(output);
+ } else if (servletResponseWrapper.isUseStream()) {
+ ServletOutputStream out = response.getOutputStream();
+ servletResponseWrapper.sendContent(out);
+ }
+ } finally {
+ // reuseWrapper(servletResponseWrapper);
}
- return output;
+ return;
+ }
+ output = createResponseWriter(response, characterEncoding);
+
+ parser.setInputEncoding(characterEncoding);
+ parser.setOutputEncoding(characterEncoding);
}
- protected abstract void reuseParser(HtmlParser parser);
+ try {
+ // Setup scripts and styles
+ parser.setScripts((Set) request
+ .getAttribute(AjaxContext.SCRIPTS_PARAMETER));
+ parser.setStyles((Set) request
+ .getAttribute(AjaxContext.STYLES_PARAMETER));
+ // Process parsing.
+ long startTimeMills = System.currentTimeMillis();
+ servletResponseWrapper.parseContent(output, parser);
+ if (log.isDebugEnabled()) {
+ startTimeMills = System.currentTimeMillis() - startTimeMills;
+ log.debug(Messages.getMessage(Messages.PARSING_TIME_INFO, ""
+ + startTimeMills));
+ }
+ } catch (Exception e) {
+ throw new ServletException(Messages
+ .getMessage(Messages.JTIDY_PARSING_ERROR), e);
+ } finally {
+ reuseParser(parser);
+ }
+ }
- protected abstract HtmlParser getParser(String mimetype, boolean isAjax);
+ /**
+ * @param response
+ * @return
+ * @throws ServletException
+ */
+ protected FilterServletResponseWrapper getWrapper(
+ HttpServletResponse response) throws ServletException {
+ return new FilterServletResponseWrapper(response);
+ }
- /**
- * @param publicid The publicid to set.
- */
- protected void setPublicid(String publicid) {
- this.publicid = publicid;
+ /**
+ * @param request
+ * @return
+ */
+ protected boolean isAjaxRequest(ServletRequest request) {
+ try {
+ return null != request
+ .getParameter(AjaxContainerRenderer.AJAX_PARAMETER_NAME);
+ } catch (Exception e) {
+ // OCJ 10 - throw exception for static resources.
+ return false;
}
+ }
- /**
- * @return Returns the publicid.
- */
- public String getPublicid() {
- return publicid;
+ /**
+ * @param response
+ * @param characterEncoding
+ * @return
+ * @throws IOException
+ * @throws UnsupportedEncodingException
+ */
+ private Writer createResponseWriter(final HttpServletResponse response,
+ String characterEncoding) throws IOException,
+ UnsupportedEncodingException {
+ Writer output;
+ try {
+ output = response.getWriter();
+ } catch (IllegalStateException e) {
+ if (null != characterEncoding) {
+ output = new OutputStreamWriter(response.getOutputStream(),
+ characterEncoding);
+ } else {
+ output = new OutputStreamWriter(response.getOutputStream());
+ }
}
+ return output;
+ }
- /**
- * @param systemid The systemid to set.
- */
- protected void setSystemid(String systemid) {
- this.systemid = systemid;
- }
+ protected abstract void reuseParser(HtmlParser parser);
- /**
- * @return Returns the systemid.
- */
- public String getSystemid() {
- return systemid;
- }
+ protected abstract HtmlParser getParser(String mimetype, boolean isAjax);
- /**
- * @param namespace The namespace to set.
- */
- protected void setNamespace(String namespace) {
- this.namespace = namespace;
- }
+ /**
+ * @param publicid
+ * The publicid to set.
+ */
+ protected void setPublicid(String publicid) {
+ this.publicid = publicid;
+ }
- /**
- * @return Returns the namespace.
- */
- public String getNamespace() {
- return namespace;
- }
+ /**
+ * @return Returns the publicid.
+ */
+ public String getPublicid() {
+ return publicid;
+ }
- /**
- * @param mimetype The mimetype to set.
- */
- protected void setMimetype(String mimetype) {
- this.mimetype = mimetype;
- }
+ /**
+ * @param systemid
+ * The systemid to set.
+ */
+ protected void setSystemid(String systemid) {
+ this.systemid = systemid;
+ }
- /**
- * @return Returns the mimetype.
- */
- protected String getMimetype() {
- return mimetype;
- }
+ /**
+ * @return Returns the systemid.
+ */
+ public String getSystemid() {
+ return systemid;
+ }
- /**
- * @return Returns the forcexml.
- */
- public boolean isForcexml() {
- return this.forcexml;
- }
+ /**
+ * @param namespace
+ * The namespace to set.
+ */
+ protected void setNamespace(String namespace) {
+ this.namespace = namespace;
+ }
- /**
- * @param forcexml The forcexml to set.
- */
- protected void setForcexml(boolean forcexml) {
- this.forcexml = forcexml;
- }
+ /**
+ * @return Returns the namespace.
+ */
+ public String getNamespace() {
+ return namespace;
+ }
+ /**
+ * @param mimetype
+ * The mimetype to set.
+ */
+ protected void setMimetype(String mimetype) {
+ this.mimetype = mimetype;
+ }
- private Object nz(Object param, Object def) {
- return param != null?param:def;
- }
+ /**
+ * @return Returns the mimetype.
+ */
+ protected String getMimetype() {
+ return mimetype;
+ }
+ /**
+ * @return Returns the forcexml.
+ */
+ public boolean isForcexml() {
+ return this.forcexml;
+ }
+
+ /**
+ * @param forcexml
+ * The forcexml to set.
+ */
+ protected void setForcexml(boolean forcexml) {
+ this.forcexml = forcexml;
+ }
+
+ private Object nz(Object param, Object def) {
+ return param != null ? param : def;
+ }
+
}
Modified: trunk/framework/src/main/java/org/ajax4jsf/framework/renderer/ChameleonRenderKitFactory.java
===================================================================
--- trunk/framework/src/main/java/org/ajax4jsf/framework/renderer/ChameleonRenderKitFactory.java 2007-04-17 21:04:13 UTC (rev 93)
+++ trunk/framework/src/main/java/org/ajax4jsf/framework/renderer/ChameleonRenderKitFactory.java 2007-04-18 00:59:13 UTC (rev 94)
@@ -29,78 +29,103 @@
import javax.faces.render.RenderKit;
import javax.faces.render.RenderKitFactory;
+import org.ajax4jsf.framework.resource.InternetResourceBuilder;
import org.ajax4jsf.framework.util.message.Messages;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
-
/**
* @author shura (latest modification by $Author: alexsmirnov $)
* @version $Revision: 1.1.2.1 $ $Date: 2007/01/09 18:58:50 $
- *
+ *
*/
public class ChameleonRenderKitFactory extends RenderKitFactory {
RenderKitFactory defaultFactory;
-// private static final String AJAX_BASE_RENDER_KIT_PARAMETER = "AJAX_BASE_RENDERKIT_ID";
-// private static final String AJAX_RENDER_KIT_PARAMETER = "AJAX_RENDER_KIT_ID";
- private static final Log _log = LogFactory.getLog(ChameleonRenderKitFactory.class);
+ // private static final String AJAX_BASE_RENDER_KIT_PARAMETER =
+ // "AJAX_BASE_RENDERKIT_ID";
+ // private static final String AJAX_RENDER_KIT_PARAMETER =
+ // "AJAX_RENDER_KIT_ID";
+
+ private static final Log _log = LogFactory
+ .getLog(ChameleonRenderKitFactory.class);
+
/**
- * @param defaultFactory
- */
+ * @param defaultFactory
+ */
public ChameleonRenderKitFactory(RenderKitFactory defaultFactory) {
- this.defaultFactory = defaultFactory;
+ if (_log.isDebugEnabled()) {
+ _log.debug("ChameleonRenderKitFactory(RenderKitFactory) - Chameleon RenderKit factory instantiated"); //$NON-NLS-1$
+ }
+ this.defaultFactory = defaultFactory;
+ // Init resources builder before use.
+ InternetResourceBuilder.getInstance().init();
}
+
/**
- * @param renderKitId
- * @param renderKit
- */
+ * @param renderKitId
+ * @param renderKit
+ */
public void addRenderKit(String renderKitId, RenderKit renderKit) {
- if (renderKit instanceof ChameleonRenderKit) {
-// ChameleonRenderKit chameleonRenderKit = (ChameleonRenderKit) renderKit;
-// chameleonRenderKit.setConfiguration(ConfigurationFactory.getRendererConfigurationInstance(renderKitId)) ;
- }
- defaultFactory.addRenderKit(renderKitId, renderKit);
+ if (_log.isDebugEnabled()) {
+ _log.debug("addRenderKit(String, RenderKit) - Added RenderKit with id - renderKitId=" + renderKitId); //$NON-NLS-1$
+ }
+ if (renderKit instanceof ChameleonRenderKit) {
+ // ChameleonRenderKit chameleonRenderKit = (ChameleonRenderKit)
+ // renderKit;
+ // chameleonRenderKit.setConfiguration(ConfigurationFactory.getRendererConfigurationInstance(renderKitId))
+ // ;
+ }
+ defaultFactory.addRenderKit(renderKitId, renderKit);
}
+
/**
- * @param context
- * @param renderKitId
- * @return
- */
+ * @param context
+ * @param renderKitId
+ * @return
+ */
public RenderKit getRenderKit(FacesContext context, String renderKitId) {
- RenderKit renderKit = defaultFactory.getRenderKit(context, renderKitId);
- if (renderKit instanceof ChameleonRenderKit) {
- if (_log.isDebugEnabled()) {
- _log.debug(Messages.getMessage(Messages.REQUEST_CHAMELEON_RENDER_KIT_INFO, renderKitId));
- }
- String baseRenderKitId = null;
- // TODO - get DefaultRenderKitId from ViewHandler ?
- try {
- // IN JSF-RI verifications, context may be null !
- if(null != context) {
- baseRenderKitId = context.getApplication()
- .getDefaultRenderKitId();
- } else {
- ApplicationFactory appFactory =(ApplicationFactory) FactoryFinder.getFactory(FactoryFinder.APPLICATION_FACTORY);
- baseRenderKitId = appFactory.getApplication().getDefaultRenderKitId();
- }
- } catch (Exception e) {
- _log.warn(Messages.getMessage(Messages.GET_DEFAULT_RENDER_KIT_ERROR), e);
- }
- if(baseRenderKitId == null ){
- baseRenderKitId = RenderKitFactory.HTML_BASIC_RENDER_KIT;
- }
- if (_log.isDebugEnabled()) {
- _log.debug(Messages.getMessage(Messages.DEFAULT_RENDER_KIT_INFO, baseRenderKitId));
- }
- ((ChameleonRenderKit) renderKit).setDefaultRenderKit(defaultFactory.getRenderKit(context, baseRenderKitId));
- }
- return renderKit;
+ RenderKit renderKit = defaultFactory.getRenderKit(context, renderKitId);
+ if (renderKit instanceof ChameleonRenderKit) {
+ if (_log.isDebugEnabled()) {
+ _log.debug(Messages
+ .getMessage(Messages.REQUEST_CHAMELEON_RENDER_KIT_INFO,
+ renderKitId));
+ }
+ String baseRenderKitId = null;
+ // TODO - get DefaultRenderKitId from ViewHandler ?
+ try {
+ // IN JSF-RI verifications, context may be null !
+ if (null != context) {
+ baseRenderKitId = context.getApplication()
+ .getDefaultRenderKitId();
+ } else {
+ ApplicationFactory appFactory = (ApplicationFactory) FactoryFinder
+ .getFactory(FactoryFinder.APPLICATION_FACTORY);
+ baseRenderKitId = appFactory.getApplication()
+ .getDefaultRenderKitId();
+ }
+ } catch (Exception e) {
+ _log.warn(Messages
+ .getMessage(Messages.GET_DEFAULT_RENDER_KIT_ERROR), e);
+ }
+ if (baseRenderKitId == null) {
+ baseRenderKitId = RenderKitFactory.HTML_BASIC_RENDER_KIT;
+ }
+ if (_log.isDebugEnabled()) {
+ _log.debug(Messages.getMessage(
+ Messages.DEFAULT_RENDER_KIT_INFO, baseRenderKitId));
+ }
+ ((ChameleonRenderKit) renderKit).setDefaultRenderKit(defaultFactory
+ .getRenderKit(context, baseRenderKitId));
+ }
+ return renderKit;
}
+
/**
- * @return
- */
+ * @return
+ */
public Iterator getRenderKitIds() {
- return defaultFactory.getRenderKitIds();
+ return defaultFactory.getRenderKitIds();
}
}
Modified: trunk/framework/src/main/java/org/ajax4jsf/framework/resource/InternetResourceBuilder.java
===================================================================
--- trunk/framework/src/main/java/org/ajax4jsf/framework/resource/InternetResourceBuilder.java 2007-04-17 21:04:13 UTC (rev 93)
+++ trunk/framework/src/main/java/org/ajax4jsf/framework/resource/InternetResourceBuilder.java 2007-04-18 00:59:13 UTC (rev 94)
@@ -39,139 +39,137 @@
public abstract class InternetResourceBuilder {
- protected static Log log = LogFactory.getLog(InternetResourceBuilder.class);
+ private static final Log log = LogFactory.getLog(InternetResourceBuilder.class);
- /**
- * Get application start time for check resources modification time.
- * @return application start time in msec's
- */
- public abstract long getStartTime();
+ /**
+ * Get application start time for check resources modification time.
+ *
+ * @return application start time in msec's
+ */
+ public abstract long getStartTime();
- /**
- * @param cacheable
- * @param session
- * @param mime
- * @return
- * @throws FacesException
- */
- public abstract InternetResource createUserResource(boolean cacheable,
- boolean session, String mime) throws FacesException;
+ /**
+ * @param cacheable
+ * @param session
+ * @param mime
+ * @return
+ * @throws FacesException
+ */
+ public abstract InternetResource createUserResource(boolean cacheable,
+ boolean session, String mime) throws FacesException;
- /**
- * @param request
- * @return
- */
- public abstract String getFacesResourceKey(HttpServletRequest request);
+ /**
+ * @param key
+ * @param resource
+ */
+ public abstract void addResource(String key, InternetResource resource);
- /**
- * @param key
- * @param resource
- */
- public abstract void addResource(String key, InternetResource resource);
+ /**
+ * @param path
+ * @return
+ * @throws ResourceNotFoundException
+ */
+ public abstract InternetResource getResource(String path)
+ throws ResourceNotFoundException;
- /**
- * @param path
- * @return
- * @throws ResourceNotFoundException
- */
- public abstract InternetResource getResource(String path)
- throws ResourceNotFoundException;
+ /**
+ * @param key
+ * @return
+ */
+ public abstract Object getResourceDataForKey(String key);
- /**
- * @param key
- * @return
- */
- public abstract Object getResourceDataForKey(String key);
+ /**
+ * @param key
+ * @return
+ * @throws ResourceNotFoundException
+ */
+ public abstract InternetResource getResourceForKey(String key)
+ throws ResourceNotFoundException;
- /**
- * @param key
- * @return
- * @throws ResourceNotFoundException
- */
- public abstract InternetResource getResourceForKey(String key)
- throws ResourceNotFoundException;
+ /**
+ * @param resource
+ * @param context
+ * @param storeData
+ * @return
+ */
+ public abstract String getUri(InternetResource resource,
+ FacesContext context, Object storeData);
- /**
- * @param resource
- * @param context
- * @param storeData
- * @return
- */
- public abstract String getUri(InternetResource resource,
- FacesContext context, Object storeData);
+ /**
+ * @param base
+ * @param path
+ * @return
+ * @throws FacesException
+ */
+ public abstract InternetResource createResource(Object base, String path)
+ throws FacesException;
- /**
- * @param base
- * @param path
- * @return
- * @throws FacesException
- */
- public abstract InternetResource createResource(Object base, String path)
- throws FacesException;
+ /**
+ * @throws ServletException
+ */
+ public abstract void init()
+ throws FacesException;
- /**
- * @param servletContext
- * @param filterName
- * @throws ServletException
- */
- public abstract void init(ServletContext servletContext, String filterName)
- throws ServletException;
+ /**
+ * static instance variable.
+ */
+ private static Map instances = Collections.synchronizedMap(new HashMap());
- /**
- * static instance variable.
- */
- private static Map instances = Collections.synchronizedMap(new HashMap());
-
- /**
- * Get ( or create if nessesary ) instance of builder for current loader.
- * check content of file META-INF/services/org.ajax4jsf.framework.resource.InternetResourceBuilder for
- * name of class to instantiate, othrthise create {@link ResourceBuilderImpl} instance.
- * @return current builder instance.
- */
- public static InternetResourceBuilder getInstance() {
- ClassLoader loader = Thread.currentThread().getContextClassLoader();
- InternetResourceBuilder instance = (InternetResourceBuilder) instances
- .get(loader);
- if (null == instance) {
- try {
- String resource = "META-INF/services/"
- + InternetResourceBuilder.class.getName();
- InputStream in = loader.getResourceAsStream(resource);
- BufferedReader reader = new BufferedReader(
- new InputStreamReader(in));
- String serviceClassName = reader.readLine();
- reader.close();
- Class builderClass = loader.loadClass(serviceClassName);
- instance = (InternetResourceBuilder) builderClass.newInstance();
- if (log.isDebugEnabled()) {
- log.debug("Create instance of InternetBuilder from class "
- + serviceClassName);
- }
- } catch (Exception e) {
- if (log.isDebugEnabled()) {
- log
- .debug(
- "Create default implementation instance of InternetBuilder");
- }
- instance = new ResourceBuilderImpl();
- }
- instances.put(loader, instance);
+ /**
+ * Get ( or create if nessesary ) instance of builder for current
+ * loader. check content of file
+ * META-INF/services/org.ajax4jsf.framework.resource.InternetResourceBuilder
+ * for name of class to instantiate, othrthise create
+ * {@link ResourceBuilderImpl} instance.
+ *
+ * @return current builder instance.
+ */
+ public static InternetResourceBuilder getInstance() {
+ ClassLoader loader = Thread.currentThread().getContextClassLoader();
+ InternetResourceBuilder instance = (InternetResourceBuilder) instances
+ .get(loader);
+ if (null == instance) {
+ try {
+ String resource = "META-INF/services/"
+ + InternetResourceBuilder.class.getName();
+ InputStream in = loader.getResourceAsStream(resource);
+ BufferedReader reader = new BufferedReader(
+ new InputStreamReader(in));
+ String serviceClassName = reader.readLine();
+ reader.close();
+ Class builderClass = loader.loadClass(serviceClassName);
+ instance = (InternetResourceBuilder) builderClass.newInstance();
+ if (log.isDebugEnabled()) {
+ log.debug("Create instance of InternetBuilder from class "
+ + serviceClassName);
}
- return instance;
+ } catch (Exception e) {
+ if (log.isDebugEnabled()) {
+ log
+ .debug("Create default implementation instance of InternetBuilder");
+ }
+ instance = new ResourceBuilderImpl();
+ }
+ instances.put(loader, instance);
}
-
- /**
- * Package-wide method for reset instance in Junit tests.
- *
- * @param instance
- */
- public static void setInstance(InternetResourceBuilder instance) {
- ClassLoader loader = Thread.currentThread().getContextClassLoader();
- instances.put(loader, instance);
+ if(log.isDebugEnabled()){
+ log.debug("Return instance of internet resource builder "+instance.toString());
}
+ return instance;
+ }
- public InternetResourceBuilder() {
- super();
- }
+ /**
+ * Package-wide method for reset instance in Junit tests.
+ *
+ * @param instance
+ */
+ public static void setInstance(InternetResourceBuilder instance) {
+ ClassLoader loader = Thread.currentThread().getContextClassLoader();
+ instances.put(loader, instance);
+ }
+ public InternetResourceBuilder() {
+ super();
+ }
+
}
\ No newline at end of file
Modified: trunk/framework/src/main/java/org/ajax4jsf/framework/resource/InternetResourceService.java
===================================================================
--- trunk/framework/src/main/java/org/ajax4jsf/framework/resource/InternetResourceService.java 2007-04-17 21:04:13 UTC (rev 93)
+++ trunk/framework/src/main/java/org/ajax4jsf/framework/resource/InternetResourceService.java 2007-04-18 00:59:13 UTC (rev 94)
@@ -40,6 +40,7 @@
import org.ajax4jsf.framework.ajax.xmlfilter.BaseFilter;
import org.ajax4jsf.framework.ajax.xmlfilter.CacheContent;
+import org.ajax4jsf.framework.util.config.WebXml;
import org.ajax4jsf.framework.util.message.Messages;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@@ -49,261 +50,285 @@
import com.opensymphony.oscache.web.ServletCacheAdministrator;
public class InternetResourceService {
- private static final Log log = LogFactory
- .getLog(InternetResourceService.class);
+ private static final Log log = LogFactory
+ .getLog(InternetResourceService.class);
- static final String ENABLE_CACHING_PARAMETER = "enable-cache";
+ static final String ENABLE_CACHING_PARAMETER = "enable-cache";
- private static final String RESOURCE_LIFECYCLE_PARAMETER = "org.ajax4jsf.RESOURCE_LIFECYCLE";
+ private static final String RESOURCE_LIFECYCLE_PARAMETER = "org.ajax4jsf.RESOURCE_LIFECYCLE";
- private FilterConfig filterConfig;
+ private FilterConfig filterConfig;
- private boolean cacheEnabled = true;
+ private boolean cacheEnabled = true;
- private ServletCacheAdministrator cacheAdmin;
+ private ServletCacheAdministrator cacheAdmin;
- private FacesContextFactory contextFactory;
+ private FacesContextFactory contextFactory;
- // private RenderKitFactory renderKitFactory;
- private String lifecycleClass;
- private ResourceLifecycle lifecycle ;
-
- private InternetResourceBuilder resourceBuilder;
+ // private RenderKitFactory renderKitFactory;
+ private String lifecycleClass;
- public InternetResourceService() {
+ private ResourceLifecycle lifecycle;
+
+ private InternetResourceBuilder resourceBuilder;
+
+ private WebXml webXml;
+
+ public InternetResourceService() {
+ }
+
+ public void setCacheEnabled(boolean b) {
+ cacheEnabled = b;
+ }
+
+ public void init(FilterConfig config) throws ServletException {
+ filterConfig = config;
+ ServletContext servletContext = config.getServletContext();
+ if ("false".equalsIgnoreCase(config
+ .getInitParameter(ENABLE_CACHING_PARAMETER))) {
+ setCacheEnabled(false);
+ // this.cacheEnabled = false;
+ this.cacheAdmin = null;
+ } else {
+ // Load our implementation properties
+ Properties cacheProperties = getProperties("oscache.properties");
+ cacheProperties.putAll(getProperties("/oscache.properties"));
+ this.cacheAdmin = ServletCacheAdministrator.getInstance(
+ servletContext, cacheProperties);
}
+ // Create Resource-specific Faces Lifecycle instance.
+ lifecycleClass = servletContext
+ .getInitParameter(RESOURCE_LIFECYCLE_PARAMETER);
+ if (lifecycleClass != null) {
+ ClassLoader classLoader = Thread.currentThread()
+ .getContextClassLoader();
+ try {
+ Class clazz = classLoader.loadClass(lifecycleClass);
+ lifecycle = (ResourceLifecycle) clazz.newInstance();
+ } catch (Exception e) {
+ throw new FacesException(
+ "Error create instance of resource Lifecycle "
+ + lifecycleClass, e);
+ }
+ } else {
+ lifecycle = new ResourceLifecycle();
+ }
+ webXml = new WebXml();
+ webXml.init(servletContext,filterConfig.getFilterName());
+ if (log.isDebugEnabled()) {
+ log.debug("Resources service initialized");
+ }
+ }
- public void setCacheEnabled(boolean b) {
- cacheEnabled = b;
+ public boolean serviceResource(HttpServletRequest httpServletRequest,
+ HttpServletResponse httpServletResponse) throws ServletException,
+ IOException {
+ String resourceKey = webXml
+ .getFacesResourceKey(httpServletRequest);
+ if (null != resourceKey) {
+ serviceResource(resourceKey, httpServletRequest,
+ httpServletResponse);
+ return true;
}
+ return false;
+ }
- public void init(FilterConfig config) throws ServletException {
- filterConfig = config;
- ServletContext servletContext = config.getServletContext();
- if ("false".equalsIgnoreCase(config
- .getInitParameter(ENABLE_CACHING_PARAMETER))) {
- setCacheEnabled(false);
- // this.cacheEnabled = false;
- this.cacheAdmin = null;
- } else {
- // Load our implementation properties
- Properties cacheProperties = getProperties("oscache.properties");
- cacheProperties.putAll(getProperties("/oscache.properties"));
- this.cacheAdmin = ServletCacheAdministrator.getInstance(servletContext, cacheProperties);
+ public void serviceResource(String resourceKey, HttpServletRequest request,
+ HttpServletResponse response) throws ServletException, IOException {
+ InternetResource resource;// getInternetResource(request);
+ try {
+ resource = getResourceBuilder().getResourceForKey(resourceKey);
+ } catch (ResourceNotFoundException e) {
+ throw new ServletException(e);
+ }
+ Object resourceDataForKey = getResourceBuilder()
+ .getResourceDataForKey(resourceKey);
+ if (resource.isCacheable(null) && this.cacheEnabled) {
+ // Test for client request modification time.
+ try {
+ long ifModifiedSince = request
+ .getDateHeader("If-Modified-Since");
+ if (ifModifiedSince >= 0) {
+ // Test for modification. 1000 ms due to round
+ // modification
+ // time to seconds.
+ long lastModified = resource.getLastModified(null)
+ .getTime() - 1000;
+ if (lastModified <= ifModifiedSince) {
+ response.setStatus(304);
+ return;
+ }
}
- // Create resource builder for this filter.
- resourceBuilder = InternetResourceBuilder.getInstance();
- resourceBuilder.init(servletContext,config.getFilterName());
- // Create Resource-specific Faces Lifecycle instance.
- lifecycleClass = servletContext.getInitParameter(RESOURCE_LIFECYCLE_PARAMETER);
- if(lifecycleClass != null){
- ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
- try {
- Class clazz = classLoader.loadClass(lifecycleClass);
- lifecycle = (ResourceLifecycle) clazz.newInstance();
- } catch (Exception e) {
- throw new FacesException("Error create instance of resource Lifecycle "+lifecycleClass,e);
- }
+ } catch (IllegalArgumentException e) {
+ log
+ .warn(
+ Messages
+ .getMessage(Messages.PARSING_IF_MODIFIED_SINCE_WARNING),
+ e);
+ }
+ String cacheKey = resourceKey;// + "?" +
+ // request.getQueryString();
+ // TODO - select session/application scope.
+ Cache cache = cacheAdmin.getAppScopeCache(getServletContext());
+ try {
+ // TODO - use last modified/expires time
+ CacheContent content = (CacheContent) cache
+ .getFromCache(cacheKey);
+ if (log.isDebugEnabled()) {
+ log.debug(Messages.getMessage(
+ Messages.GET_CONTENT_FROM_CACHE_INFO, cacheKey));
+ }
+ content.sendHeaders(response);
+ // Correct expires date for resource.
+ Date expired = resource.getExpired(null);
+ if (expired != null) {
+ response.setDateHeader("Expires", expired.getTime());
} else {
- lifecycle = new ResourceLifecycle();
+ response.setDateHeader("Expires", System
+ .currentTimeMillis()
+ + InternetResource.DEFAULT_EXPIRE);
}
- contextFactory = (FacesContextFactory) FactoryFinder
- .getFactory(FactoryFinder.FACES_CONTEXT_FACTORY);
-
- }
-
- public boolean serviceResource(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException {
- String resourceKey = resourceBuilder.getFacesResourceKey(httpServletRequest);
- if(null != resourceKey){
- serviceResource(resourceKey,httpServletRequest, httpServletResponse);
- return true;
+ if (!request.getMethod().equals("HEAD")) {
+ content.send(response);
}
- return false;
- }
-
- public void serviceResource(String resourceKey, HttpServletRequest request,
- HttpServletResponse response) throws ServletException, IOException {
- InternetResource resource;// getInternetResource(request);
- try{
- resource = resourceBuilder.getResourceForKey(resourceKey);
- } catch (ResourceNotFoundException e) {
- throw new ServletException(e);
+ } catch (NeedsRefreshException e) {
+ try {
+ if (log.isDebugEnabled()) {
+ log.debug(Messages.getMessage(
+ Messages.CONTENT_NOT_FOUND_ERROR, cacheKey));
+ }
+ CachedResourceContext context = (CachedResourceContext) sendResource(
+ resource, request, response, resourceDataForKey);
+ // TODO - set refresh interval ?
+ cache.putInCache(cacheKey, context.getContent());
+ } catch (Exception ex) {
+ cache.cancelUpdate(cacheKey);
+ log.error(
+ Messages.getMessage(Messages.SEND_RESOURCE_ERROR),
+ ex);
+ throw new ServletException(Messages.getMessage(
+ Messages.SEND_RESOURCE_ERROR_2, ex.getMessage()),
+ ex);
}
- Object resourceDataForKey = resourceBuilder.getResourceDataForKey(resourceKey);
- if (resource.isCacheable(null) && this.cacheEnabled) {
- // Test for client request modification time.
- try {
- long ifModifiedSince = request
- .getDateHeader("If-Modified-Since");
- if (ifModifiedSince >= 0) {
- // Test for modification. 1000 ms due to round modification
- // time to seconds.
- long lastModified = resource.getLastModified(null).getTime() - 1000;
- if (lastModified <= ifModifiedSince) {
- response.setStatus(304);
- return;
- }
- }
- } catch (IllegalArgumentException e) {
- log
- .warn(
- Messages
- .getMessage(Messages.PARSING_IF_MODIFIED_SINCE_WARNING),
- e);
- }
- String cacheKey = resourceKey ;//+ "?" + request.getQueryString();
- // TODO - select session/application scope.
- Cache cache = cacheAdmin.getAppScopeCache(getServletContext());
- try {
- // TODO - use last modified/expires time
- CacheContent content = (CacheContent) cache
- .getFromCache(cacheKey);
- if (log.isDebugEnabled()) {
- log.debug(Messages.getMessage(
- Messages.GET_CONTENT_FROM_CACHE_INFO, cacheKey));
- }
- content.sendHeaders(response);
- // Correct expires date for resource.
- Date expired = resource.getExpired(null);
- if (expired != null) {
- response.setDateHeader("Expires", expired.getTime());
- } else {
- response.setDateHeader("Expires", System.currentTimeMillis()
- + InternetResource.DEFAULT_EXPIRE);
- }
- if (!request.getMethod().equals("HEAD")) {
- content.send(response);
- }
- } catch (NeedsRefreshException e) {
- try {
- if (log.isDebugEnabled()) {
- log.debug(Messages.getMessage(
- Messages.CONTENT_NOT_FOUND_ERROR, cacheKey));
- }
- CachedResourceContext context = (CachedResourceContext) sendResource(
- resource, request, response, resourceDataForKey);
- // TODO - set refresh interval ?
- cache.putInCache(cacheKey, context.getContent());
- } catch (Exception ex) {
- cache.cancelUpdate(cacheKey);
- log.error(
- Messages.getMessage(Messages.SEND_RESOURCE_ERROR),
- ex);
- throw new ServletException(Messages.getMessage(
- Messages.SEND_RESOURCE_ERROR_2, ex.getMessage()),
- ex);
- }
- }
- } else {
- sendResource(resource, request, response, resourceDataForKey);
- }
+ }
+ } else {
+ sendResource(resource, request, response, resourceDataForKey);
}
+ }
- /**
- * @param resource
- * @param request
- * @param response
- * @throws IOException
- */
- protected ResourceContext sendResource(InternetResource resource,
- HttpServletRequest request, HttpServletResponse response, Object data)
- throws IOException {
- ResourceContext resourceContext = getResourceContext(resource, request, response);
- resourceContext.setResourceData(data);
- getLifecycle().send(resourceContext, resource);
- resourceContext.release();
- return resourceContext;
+ /**
+ * @param resource
+ * @param request
+ * @param response
+ * @throws IOException
+ */
+ protected ResourceContext sendResource(InternetResource resource,
+ HttpServletRequest request, HttpServletResponse response,
+ Object data) throws IOException {
+ ResourceContext resourceContext = getResourceContext(resource, request,
+ response);
+ resourceContext.setResourceData(data);
+ getLifecycle().send(resourceContext, resource);
+ resourceContext.release();
+ return resourceContext;
+ }
+
+ /**
+ * @param resource
+ * @param request
+ * @param response
+ * @return
+ * @throws ServletException
+ * @throws FacesException
+ */
+ protected ResourceContext getResourceContext(InternetResource resource,
+ HttpServletRequest request, HttpServletResponse response)
+ throws FacesException {
+ FacesContext facesContext = null;
+ ResourceContext resourceContext;
+ if (resource.requireFacesContext()) {
+ facesContext = getFacesContext(request, response);
+ resourceContext = new FacesResourceContext(facesContext);
+ } else {
+ resourceContext = new ServletResourceContext(getServletContext(),
+ request, response);
}
+ if (resource.isCacheable(null) && this.cacheEnabled) {
+ resourceContext = new CachedResourceContext(resourceContext);
+ }
+ return resourceContext;
+ }
- /**
- * @param resource
- * @param request
- * @param response
- * @return
- * @throws ServletException
- * @throws FacesException
- */
- protected ResourceContext getResourceContext(InternetResource resource, HttpServletRequest request, HttpServletResponse response) throws FacesException {
- FacesContext facesContext = null;
- ResourceContext resourceContext;
- if (resource.requireFacesContext()) {
- facesContext = getFacesContext(request, response);
- resourceContext = new FacesResourceContext(facesContext);
- } else {
- resourceContext = new ServletResourceContext(getServletContext(),
- request, response);
+ /**
+ * Get properties file from classpath
+ *
+ * @param name
+ * @return
+ */
+ protected Properties getProperties(String name) {
+ Properties properties = new Properties();
+ InputStream props = BaseFilter.class.getResourceAsStream(name);
+ if (null != props) {
+ try {
+ properties.load(props);
+ } catch (IOException e) {
+ // TODO Auto-generated catch block
+ log.warn(Messages.getMessage(Messages.READING_PROPERTIES_ERROR,
+ name), e);
+ } finally {
+ try {
+ props.close();
+ } catch (IOException e) {
+ // Can be ignored
}
- if (resource.isCacheable(null) && this.cacheEnabled) {
- resourceContext = new CachedResourceContext(resourceContext);
- }
- return resourceContext;
+ }
}
+ return properties;
- /**
- * Get properties file from classpath
- *
- * @param name
- * @return
- */
- protected Properties getProperties(String name) {
- Properties properties = new Properties();
- InputStream props = BaseFilter.class.getResourceAsStream(name);
- if (null != props) {
- try {
- properties.load(props);
- } catch (IOException e) {
- // TODO Auto-generated catch block
- log.warn(Messages.getMessage(Messages.READING_PROPERTIES_ERROR,
- name), e);
- } finally {
- try {
- props.close();
- } catch (IOException e) {
- // Can be ignored
- }
- }
- }
- return properties;
+ }
- }
+ /**
+ * @return Returns the servletContext.
+ */
+ protected ServletContext getServletContext() {
+ return filterConfig.getServletContext();
+ }
- /**
- * @return Returns the servletContext.
- */
- protected ServletContext getServletContext() {
- return filterConfig.getServletContext();
- }
+ /**
+ * @return the lifecycle
+ * @throws ServletException
+ */
+ protected ResourceLifecycle getLifecycle() throws FacesException {
+ return lifecycle;
+ }
-
-
- /**
- * @return the lifecycle
- * @throws ServletException
- */
- protected ResourceLifecycle getLifecycle() throws FacesException {
- return lifecycle;
+ /**
+ * @return the contextFactory
+ */
+ protected synchronized FacesContextFactory getContextFactory() {
+ if (contextFactory == null) {
+ contextFactory = (FacesContextFactory) FactoryFinder
+ .getFactory(FactoryFinder.FACES_CONTEXT_FACTORY);
}
-
-
- /**
- * @return the contextFactory
- */
- protected FacesContextFactory getContextFactory() {
- return contextFactory;
- }
+ return contextFactory;
+ }
- protected FacesContext getFacesContext(ServletRequest request,
- ServletResponse response) throws FacesException {
- return getContextFactory().getFacesContext(getServletContext(), request,
- response, getLifecycle());
- }
+ protected FacesContext getFacesContext(ServletRequest request,
+ ServletResponse response) throws FacesException {
+ return getContextFactory().getFacesContext(getServletContext(),
+ request, response, getLifecycle());
+ }
- /**
- * @return the resourceBuilder
- */
- protected InternetResourceBuilder getResourceBuilder() {
- return resourceBuilder;
+ /**
+ * @return the resourceBuilder
+ */
+ protected InternetResourceBuilder getResourceBuilder() {
+ if (resourceBuilder == null) {
+ // Create resource builder for this filter.
+ resourceBuilder = InternetResourceBuilder.getInstance();
}
+ return resourceBuilder;
+ }
}
Modified: trunk/framework/src/main/java/org/ajax4jsf/framework/resource/ResourceBuilderImpl.java
===================================================================
--- trunk/framework/src/main/java/org/ajax4jsf/framework/resource/ResourceBuilderImpl.java 2007-04-17 21:04:13 UTC (rev 93)
+++ trunk/framework/src/main/java/org/ajax4jsf/framework/resource/ResourceBuilderImpl.java 2007-04-18 00:59:13 UTC (rev 94)
@@ -49,521 +49,534 @@
import org.ajax4jsf.framework.util.config.WebXml;
import org.ajax4jsf.framework.util.message.Messages;
import org.apache.commons.digester.Digester;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
/**
- * Produce instances of InternetResource's for any types -
- * jar resource, dynamic created image, component-incapsulated etc.
- * Realised as singleton class to support cache, configuration etc.
+ * Produce instances of InternetResource's for any types - jar resource, dynamic
+ * created image, component-incapsulated etc. Realised as singleton class to
+ * support cache, configuration etc.
*
* @author shura (latest modification by $Author: alexsmirnov $)
* @version $Revision: 1.1.2.1 $ $Date: 2007/01/09 18:56:58 $
- *
+ *
*/
public class ResourceBuilderImpl extends InternetResourceBuilder {
-
- private static final String DATA_SEPARATOR = "/DATA/";
- private static Map renderers;
- private static ResourceRenderer defaultRenderer = new MimeRenderer(null);
-
- /**
- * keep resources instances .
- * TODO - put this map to application-scope attribute, for support clastering environment.
- */
- private Map resources = Collections.synchronizedMap(new HashMap());
-
- private long _startTime;
-
- private ServletContext servletContext;
-
- private WebXml webXml;
- private Codec codec;
-
- static {
- renderers = new HashMap();
- // append known renderers for extentions.
- renderers.put(".gif",new GifRenderer());
- ResourceRenderer renderer = new JpegRenderer();
- renderers.put(".jpeg",renderer);
- renderers.put(".jpg",renderer);
- renderers.put(".png",new PngRenderer());
- renderers.put(".js",new ScriptRenderer());
- renderers.put(".css",new StyleRenderer());
- renderers.put(".log",new LogfileRenderer());
- renderers.put(".html",new HTMLRenderer());
- renderers.put(".xhtml",new MimeRenderer("application/xhtml+xml"));
- renderers.put(".xml",new MimeRenderer("text/xml"));
- renderers.put(".xcss", new TemplateCSSRenderer());
-// renderers.put(".htc",new BehaviorRenderer());
- // set in-memory caching ImageIO
- ImageIO.setUseCache(false);
- }
-
- public WebXml getWebXml() {
- if(null == webXml){
- throw new FacesException("Resources framework is not initialised, check web.xml for Filter configuration");
- }
- return webXml;
- }
+ private static final Log log = LogFactory.getLog(ResourceBuilderImpl.class);
- public void setWebXml(WebXml webXml) {
- this.webXml = webXml;
- }
-
- public ResourceBuilderImpl() {
- super();
- _startTime = System.currentTimeMillis();
- InternetResourceBuilder.setInstance(this);
- registerResources();
- }
+ private static final String DATA_SEPARATOR = "/DATA/";
- private void registerConfig(
- URL resourceConfig)
- {
- try
- {
- InputStream in = resourceConfig.openStream();
- try
- {
- Digester digester = new Digester();
- digester.setValidating(false);
- digester.setEntityResolver(new EntityResolver(){
- // Dummi resolver - alvays do nothing
- public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
- return new InputSource(new StringReader(""));
- }
- });
- digester.setNamespaceAware(false);
- digester.setUseContextClassLoader(true);
- digester.push(this);
- digester.addObjectCreate("resource-config/resource", "class", JarResource.class);
- digester.addObjectCreate("resource-config/resource/renderer", "class", HTMLRenderer.class);
- digester.addCallMethod("resource-config/resource/renderer/content-type",
- "setContentType", 0);
- digester.addSetNext("resource-config/resource/renderer", "setRenderer", ResourceRenderer.class.getName());
- digester.addCallMethod("resource-config/resource/name",
- "setKey", 0);
- digester.addCallMethod("resource-config/resource/path",
- "setPath", 0);
- digester.addCallMethod("resource-config/resource/cacheable",
- "setCacheable", 0);
- digester.addCallMethod("resource-config/resource/session-aware",
- "setSessionAware", 0);
- digester.addCallMethod("resource-config/resource/property",
- "setProperty", 2);
- digester.addCallParam("resource-config/resource/property/name", 0);
- digester.addCallParam("resource-config/resource/property/value", 1);
- digester.addCallMethod("resource-config/resource/content-type",
- "setContentType", 0);
- digester.addSetNext("resource-config/resource", "addResource", InternetResource.class.getName());
- digester.parse(in);
- }
- finally
- {
- in.close();
- }
- }
- catch (IOException e)
- {
- throw new FacesException(e);
- }
- catch (SAXException e)
- {
- throw new FacesException(e);
- }
- }
- /**
- * @param servletContext
- */
- public void init(ServletContext servletContext, String filterName) throws ServletException {
- this.servletContext = servletContext;
- setWebXml(new WebXml(servletContext,filterName));
- if ("true".equals(servletContext
- .getInitParameter(InternetResource.ENCODE_URI_PARAMETER))) {
- String random = servletContext
- .getInitParameter(InternetResource.ENCODE_PASS_PARAMETER);
- if (null == random) {
- random = "";
- for (int i = 0; i < 25; i++) {
- random += (char) (65 + 26 * Math.random());
- }
- }
- try {
- codec = new Codec(random);
- } catch (Exception e) {
- throw new ServletException("Error initialisation codec for resource data",e);
- }
- } else {
- codec = new Codec();
- }
- _startTime = System.currentTimeMillis();
+ private static Map renderers;
+
+ private static ResourceRenderer defaultRenderer = new MimeRenderer(null);
+
+ /**
+ * keep resources instances . TODO - put this map to application-scope
+ * attribute, for support clastering environment.
+ */
+ private Map resources = Collections.synchronizedMap(new HashMap());
+
+ private long _startTime;
+
+ private Codec codec;
+
+ static {
+ renderers = new HashMap();
+ // append known renderers for extentions.
+ renderers.put(".gif", new GifRenderer());
+ ResourceRenderer renderer = new JpegRenderer();
+ renderers.put(".jpeg", renderer);
+ renderers.put(".jpg", renderer);
+ renderers.put(".png", new PngRenderer());
+ renderers.put(".js", new ScriptRenderer());
+ renderers.put(".css", new StyleRenderer());
+ renderers.put(".log", new LogfileRenderer());
+ renderers.put(".html", new HTMLRenderer());
+ renderers.put(".xhtml", new MimeRenderer("application/xhtml+xml"));
+ renderers.put(".xml", new MimeRenderer("text/xml"));
+ renderers.put(".xcss", new TemplateCSSRenderer());
+ // renderers.put(".htc",new BehaviorRenderer());
+ // set in-memory caching ImageIO
+ ImageIO.setUseCache(false);
+
+ }
+
+ public WebXml getWebXml(FacesContext context) {
+ WebXml webXml = (WebXml) context.getExternalContext().getApplicationMap().get(WebXml.CONTEXT_ATTRIBUTE);
+ if (null == webXml) {
+ throw new FacesException(
+ "Resources framework is not initialised, check web.xml for Filter configuration");
}
+ return webXml;
+ }
- /**
- * @throws FacesException
- */
- protected void registerResources() throws FacesException {
- try
- {
- ClassLoader loader = Thread.currentThread().getContextClassLoader();
- Enumeration e = loader.getResources("META-INF/resources-config.xml");
- while (e.hasMoreElements())
- {
- URL resource = (URL)e.nextElement();
- registerConfig(resource);
- }
+ public ResourceBuilderImpl() {
+ super();
+ _startTime = System.currentTimeMillis();
+ codec = new Codec();
+ }
+
+ /**
+ * @throws FacesException
+ */
+ protected void registerResources() throws FacesException {
+ try {
+ ClassLoader loader = Thread.currentThread().getContextClassLoader();
+ Enumeration e = loader
+ .getResources("META-INF/resources-config.xml");
+ while (e.hasMoreElements()) {
+ URL resource = (URL) e.nextElement();
+ registerConfig(resource);
+ }
+ } catch (IOException e) {
+ throw new FacesException(e);
+ }
+ }
+
+ private void registerConfig(URL resourceConfig) {
+ try {
+ if (log.isDebugEnabled()) {
+ log.debug("Process resources configuration file "+resourceConfig.toExternalForm());
}
- catch (IOException e)
- {
- throw new FacesException(e);
+
+ InputStream in = resourceConfig.openStream();
+ try {
+ Digester digester = new Digester();
+ digester.setValidating(false);
+ digester.setEntityResolver(new EntityResolver() {
+ // Dummi resolver - alvays do nothing
+ public InputSource resolveEntity(String publicId,
+ String systemId) throws SAXException, IOException {
+ return new InputSource(new StringReader(""));
+ }
+ });
+ digester.setNamespaceAware(false);
+ digester.setUseContextClassLoader(true);
+ digester.push(this);
+ digester.addObjectCreate("resource-config/resource", "class",
+ JarResource.class);
+ digester.addObjectCreate("resource-config/resource/renderer",
+ "class", HTMLRenderer.class);
+ digester.addCallMethod(
+ "resource-config/resource/renderer/content-type",
+ "setContentType", 0);
+ digester.addSetNext("resource-config/resource/renderer",
+ "setRenderer", ResourceRenderer.class.getName());
+ digester.addCallMethod("resource-config/resource/name",
+ "setKey", 0);
+ digester.addCallMethod("resource-config/resource/path",
+ "setPath", 0);
+ digester.addCallMethod("resource-config/resource/cacheable",
+ "setCacheable", 0);
+ digester.addCallMethod(
+ "resource-config/resource/session-aware",
+ "setSessionAware", 0);
+ digester.addCallMethod("resource-config/resource/property",
+ "setProperty", 2);
+ digester.addCallParam("resource-config/resource/property/name",
+ 0);
+ digester.addCallParam(
+ "resource-config/resource/property/value", 1);
+ digester.addCallMethod("resource-config/resource/content-type",
+ "setContentType", 0);
+ digester.addSetNext("resource-config/resource", "addResource",
+ InternetResource.class.getName());
+ digester.parse(in);
+ } finally {
+ in.close();
}
+ } catch (IOException e) {
+ throw new FacesException(e);
+ } catch (SAXException e) {
+ throw new FacesException(e);
}
+ }
- /**
- * Base point for creating resource. Must detect type and build
- * appropriate instance. Currently - make static resource for ordinary
- * request, or instance of class.
- * @param base base object for resource ( resourcess in classpath will be get relative to it package )
- * @param path key - path to resource, resource class name etc.
- * @return
- * @throws FacesException
- */
- public InternetResource createResource(Object base, String path) throws FacesException {
- // TODO - detect type of resource ( for example, resources location path in Skin
- try {
- return getResource(path);
- } catch (ResourceNotFoundException e) {
- try {
- return getResource(buildKey(base,path));
- } catch (ResourceNotFoundException e1) {
- if(log.isDebugEnabled()){
- log.debug(Messages.getMessage(Messages.BUILD_RESOURCE_INFO, path));
- }
- }
- }
- // path - is class name ?
- InternetResource res;
- try {
- Class resourceClass = Class.forName(path);
- res = createDynamicResource(path,resourceClass);
- } catch (Exception e) {
- try {
- res = createJarResource(base, path);
- } catch (ResourceNotFoundException ex) {
- res = createStaticResource(path);
- }
- // TODO - if resource not found, create static ?
- }
- return res;
- }
-
-
- private String buildKey(Object base, String path) {
- if( path.startsWith("/")) {
- return path.substring(1);
- }
- if(null==base ){
- return path;
- }
- StringBuffer packageName = new StringBuffer(base.getClass().getPackage().getName().replace('.','/'));
- return packageName.append("/").append(path).toString();
- }
-
- public String getUri(InternetResource resource, FacesContext context, Object storeData){
- StringBuffer uri = new StringBuffer();// ResourceServlet.DEFAULT_SERVLET_PATH).append("/");
- uri.append(resource.getKey());
- // append serialized data as Base-64 encoded request string.
- if (storeData != null) {
- try {
- byte[] objectData;
- if( !(storeData instanceof byte[])){
- ByteArrayOutputStream dataSteram = new ByteArrayOutputStream(
- 1024);
- ObjectOutputStream objStream = new ObjectOutputStream(
- dataSteram);
- objStream.writeObject(storeData);
- objStream.flush();
- objStream.close();
- dataSteram.close();
- objectData = dataSteram.toByteArray();
- } else {
- objectData = (byte[]) storeData;
- }
- uri.append(DATA_SEPARATOR);
- byte[] dataArray = encrypt(objectData);
- uri.append(new String(dataArray, "ISO-8859-1"));
+ /**
+ */
+ public void init()
+ throws FacesException {
+ // TODO - mace codec configurable.
+ registerResources();
+ }
- // / byte[] objectData = dataSteram.toByteArray();
- // / uri.append("?").append(new
- // String(Base64.encodeBase64(objectData),
- // / "ISO-8859-1"));
- } catch (Exception e) {
- // Ignore errors, log it
- log.error(Messages
- .getMessage(Messages.QUERY_STRING_BUILDING_ERROR), e);
- }
- }
- String resourceURL = getWebXml().getFacesResourceURL(context,
- uri.toString());// context.getApplication().getViewHandler().getResourceURL(context,uri.toString());
- if (resource.isSessionAware()) {
- resourceURL = context.getExternalContext().encodeResourceURL(
- resourceURL);
- }
+ /**
+ * Base point for creating resource. Must detect type and build
+ * appropriate instance. Currently - make static resource for ordinary
+ * request, or instance of class.
+ *
+ * @param base
+ * base object for resource ( resourcess in classpath
+ * will be get relative to it package )
+ * @param path
+ * key - path to resource, resource class name etc.
+ * @return
+ * @throws FacesException
+ */
+ public InternetResource createResource(Object base, String path)
+ throws FacesException {
+ // TODO - detect type of resource ( for example, resources location path
+ // in Skin
+ try {
+ return getResource(path);
+ } catch (ResourceNotFoundException e) {
+ try {
+ return getResource(buildKey(base, path));
+ } catch (ResourceNotFoundException e1) {
if (log.isDebugEnabled()) {
- log.debug(Messages.getMessage(Messages.BUILD_RESOURCE_URI_INFO,
- resource.getKey(), resourceURL));
+ log.debug(Messages.getMessage(Messages.BUILD_RESOURCE_INFO,
+ path));
}
- return resourceURL;// context.getExternalContext().encodeResourceURL(resourceURL);
-
+ }
}
-
- /**
- * @param key
- * @return
- */
- public InternetResource getResourceForKey(String key) throws ResourceNotFoundException {
-
- int data = key.indexOf(DATA_SEPARATOR);
- if(data>=0){
- key = key.substring(0,data);
- }
- return getResource(key);
+ // path - is class name ?
+ InternetResource res;
+ try {
+ Class resourceClass = Class.forName(path);
+ res = createDynamicResource(path, resourceClass);
+ } catch (Exception e) {
+ try {
+ res = createJarResource(base, path);
+ } catch (ResourceNotFoundException ex) {
+ res = createStaticResource(path);
+ }
+ // TODO - if resource not found, create static ?
}
-
- public Object getResourceDataForKey(String key){
- Object data = null;
- String dataString = null;
- int dataStart = key.indexOf(DATA_SEPARATOR);
- if(dataStart>=0){
- dataString = key.substring(dataStart+DATA_SEPARATOR.length());
- }
- if (log.isDebugEnabled()) {
- log.debug(Messages.getMessage(
- Messages.RESTORE_DATA_FROM_RESOURCE_URI_INFO, key,
- dataString));
- }
- if (dataString != null) {
- // dataString =
- // dataString.substring(dataStart+ResourceServlet.DATA_PARAMETER.length()+1);
- byte[] objectArray = null;
- try {
- byte[] dataArray = dataString.getBytes("ISO-8859-1");
- objectArray = decrypt(dataArray);
+ return res;
+ }
- ObjectInputStream in = new ObjectInputStream(
- new ByteArrayInputStream(objectArray));
- data = in.readObject();
- } catch (StreamCorruptedException e) {
- data = objectArray;
- } catch (IOException e) {
- log.error(Messages
- .getMessage(Messages.DESERIALIZE_DATA_INPUT_ERROR), e);
- } catch (ClassNotFoundException e) {
- log.error(Messages
- .getMessage(Messages.DATA_CLASS_NOT_FOUND_ERROR), e);
- }
- }
- return data;
+ private String buildKey(Object base, String path) {
+ if (path.startsWith("/")) {
+ return path.substring(1);
}
+ if (null == base) {
+ return path;
+ }
+ StringBuffer packageName = new StringBuffer(base.getClass()
+ .getPackage().getName().replace('.', '/'));
+ return packageName.append("/").append(path).toString();
+ }
- public InternetResource getResource(String path) throws ResourceNotFoundException {
-
- InternetResource internetResource = (InternetResource)resources.get(path);
- if (null == internetResource) {
- throw new ResourceNotFoundException("Resource not registered : "+path);
+ public String getUri(InternetResource resource, FacesContext context,
+ Object storeData) {
+ StringBuffer uri = new StringBuffer();// ResourceServlet.DEFAULT_SERVLET_PATH).append("/");
+ uri.append(resource.getKey());
+ // append serialized data as Base-64 encoded request string.
+ if (storeData != null) {
+ try {
+ byte[] objectData;
+ if (!(storeData instanceof byte[])) {
+ ByteArrayOutputStream dataSteram = new ByteArrayOutputStream(
+ 1024);
+ ObjectOutputStream objStream = new ObjectOutputStream(
+ dataSteram);
+ objStream.writeObject(storeData);
+ objStream.flush();
+ objStream.close();
+ dataSteram.close();
+ objectData = dataSteram.toByteArray();
} else {
- return internetResource;
+ objectData = (byte[]) storeData;
}
+ uri.append(DATA_SEPARATOR);
+ byte[] dataArray = encrypt(objectData);
+ uri.append(new String(dataArray, "ISO-8859-1"));
+
+ // / byte[] objectData = dataSteram.toByteArray();
+ // / uri.append("?").append(new
+ // String(Base64.encodeBase64(objectData),
+ // / "ISO-8859-1"));
+ } catch (Exception e) {
+ // Ignore errors, log it
+ log.error(Messages
+ .getMessage(Messages.QUERY_STRING_BUILDING_ERROR), e);
+ }
}
-
- public void addResource(InternetResource resource){
- resources.put(resource.getKey(), resource);
+ String resourceURL = getWebXml(context).getFacesResourceURL(context,
+ uri.toString());// context.getApplication().getViewHandler().getResourceURL(context,uri.toString());
+ if (resource.isSessionAware()) {
+ resourceURL = context.getExternalContext().encodeResourceURL(
+ resourceURL);
}
-
- public void addResource(String key, InternetResource resource){
- resources.put(key,resource);
- resource.setKey(key);
- // TODO - set renderer ?
+ if (log.isDebugEnabled()) {
+ log.debug(Messages.getMessage(Messages.BUILD_RESOURCE_URI_INFO,
+ resource.getKey(), resourceURL));
}
+ return resourceURL;// context.getExternalContext().encodeResourceURL(resourceURL);
-
-
- public String getFacesResourceKey(HttpServletRequest request) {
- return getWebXml().getFacesResourceKey(request);
+ }
+
+ /**
+ * @param key
+ * @return
+ */
+ public InternetResource getResourceForKey(String key)
+ throws ResourceNotFoundException {
+
+ int data = key.indexOf(DATA_SEPARATOR);
+ if (data >= 0) {
+ key = key.substring(0, data);
}
+ return getResource(key);
+ }
- public String getFacesResourceURL(FacesContext context, String Url) {
- return getWebXml().getFacesResourceURL(context, Url);
+ public Object getResourceDataForKey(String key) {
+ Object data = null;
+ String dataString = null;
+ int dataStart = key.indexOf(DATA_SEPARATOR);
+ if (dataStart >= 0) {
+ dataString = key.substring(dataStart + DATA_SEPARATOR.length());
}
+ if (log.isDebugEnabled()) {
+ log.debug(Messages.getMessage(
+ Messages.RESTORE_DATA_FROM_RESOURCE_URI_INFO, key,
+ dataString));
+ }
+ if (dataString != null) {
+ // dataString =
+ // dataString.substring(dataStart+ResourceServlet.DATA_PARAMETER.length()+1);
+ byte[] objectArray = null;
+ try {
+ byte[] dataArray = dataString.getBytes("ISO-8859-1");
+ objectArray = decrypt(dataArray);
- /**
- * Build resource for link to static context in webapp.
- * @param path
- * @return
- * @throws FacesException
- */
- protected InternetResource createStaticResource(String path) throws ResourceNotFoundException, FacesException {
- FacesContext context = FacesContext.getCurrentInstance();
- if(null != context){
- if (context.getExternalContext().getContext() instanceof ServletContext) {
- ServletContext servletContext = (ServletContext) context.getExternalContext().getContext();
- InputStream in = servletContext.getResourceAsStream(path);
- if(null != in){
- InternetResourceBase res = new StaticResource(path);
- setRenderer(res,path);
- res.setLastModified(new Date(getStartTime()));
- addResource(path,res);
- try {
- in.close();
- } catch (IOException e) {
- }
- return res;
- }
- }
- }
- throw new ResourceNotFoundException(Messages.getMessage(Messages.STATIC_RESOURCE_NOT_FOUND_ERROR, path));
+ ObjectInputStream in = new ObjectInputStream(
+ new ByteArrayInputStream(objectArray));
+ data = in.readObject();
+ } catch (StreamCorruptedException e) {
+ data = objectArray;
+ } catch (IOException e) {
+ log.error(Messages
+ .getMessage(Messages.DESERIALIZE_DATA_INPUT_ERROR), e);
+ } catch (ClassNotFoundException e) {
+ log.error(Messages
+ .getMessage(Messages.DATA_CLASS_NOT_FOUND_ERROR), e);
+ }
}
+ return data;
+ }
- private void setRenderer(InternetResourceBase res, String path) throws FacesException {
- int lastPoint = path.lastIndexOf('.');
- if(lastPoint > 0){
- String ext = path.substring(lastPoint);
- ResourceRenderer resourceRenderer = (ResourceRenderer) renderers.get(ext);
- if(null != resourceRenderer){
- res.setRenderer(resourceRenderer);
- } else {
- if(log.isDebugEnabled()){
- log.debug(Messages.getMessage(Messages.NO_RESOURCE_REGISTERED_ERROR_2, path, renderers.keySet()));
- }
-
-// String mimeType = servletContext.getMimeType(path);
- res.setRenderer(defaultRenderer);
- }
- }
+ public InternetResource getResource(String path)
+ throws ResourceNotFoundException {
+
+ InternetResource internetResource = (InternetResource) resources
+ .get(path);
+ if (null == internetResource) {
+ throw new ResourceNotFoundException("Resource not registered : "
+ + path);
+ } else {
+ return internetResource;
}
+ }
- /**
- * Create resurce to send from classpath relative to base class.
- * @param base
- * @param path
- * @return
- * @throws FacesException
- */
- protected InternetResource createJarResource(Object base, String path) throws ResourceNotFoundException, FacesException {
- String key = buildKey(base,path);
- ClassLoader loader = Thread.currentThread().getContextClassLoader();
- if(null != loader.getResource(key)){
- JarResource res = new JarResource(key);
- setRenderer(res,path);
- res.setLastModified(new Date(getStartTime()));
- addResource(key,res);
- return res;
- } else {
- throw new ResourceNotFoundException(Messages.getMessage(Messages.NO_RESOURCE_EXISTS_ERROR, key));
+ public void addResource(InternetResource resource) {
+ resources.put(resource.getKey(), resource);
+ }
+
+ public void addResource(String key, InternetResource resource) {
+ resources.put(key, resource);
+ resource.setKey(key);
+ // TODO - set renderer ?
+ }
+
+// public String getFacesResourceKey(HttpServletRequest request) {
+// return getWebXml(context).getFacesResourceKey(request);
+// }
+
+ public String getFacesResourceURL(FacesContext context, String Url) {
+ return getWebXml(context).getFacesResourceURL(context, Url);
+ }
+
+ /**
+ * Build resource for link to static context in webapp.
+ *
+ * @param path
+ * @return
+ * @throws FacesException
+ */
+ protected InternetResource createStaticResource(String path)
+ throws ResourceNotFoundException, FacesException {
+ FacesContext context = FacesContext.getCurrentInstance();
+ if (null != context) {
+ if (context.getExternalContext().getContext() instanceof ServletContext) {
+ ServletContext servletContext = (ServletContext) context
+ .getExternalContext().getContext();
+ InputStream in = servletContext.getResourceAsStream(path);
+ if (null != in) {
+ InternetResourceBase res = new StaticResource(path);
+ setRenderer(res, path);
+ res.setLastModified(new Date(getStartTime()));
+ addResource(path, res);
+ try {
+ in.close();
+ } catch (IOException e) {
+ }
+ return res;
}
-
+ }
}
-
- /**
- * Create resource by instatiate given class.
- * @param path
- * @param instatiate
- * @return
- */
- protected InternetResource createDynamicResource(String path, Class instatiate) throws ResourceNotFoundException {
- if(InternetResource.class.isAssignableFrom(instatiate) ){
- InternetResource resource;
- try {
- resource = (InternetResource) instatiate.newInstance();
- addResource(path,resource);
- } catch (Exception e) {
- String message = Messages.getMessage(Messages.INSTANTIATE_RESOURCE_ERROR, instatiate.toString());
- log.error(message, e);
- throw new ResourceNotFoundException(message, e);
- }
- return resource;
+ throw new ResourceNotFoundException(Messages.getMessage(
+ Messages.STATIC_RESOURCE_NOT_FOUND_ERROR, path));
+ }
+
+ private void setRenderer(InternetResourceBase res, String path)
+ throws FacesException {
+ int lastPoint = path.lastIndexOf('.');
+ if (lastPoint > 0) {
+ String ext = path.substring(lastPoint);
+ ResourceRenderer resourceRenderer = (ResourceRenderer) renderers
+ .get(ext);
+ if (null != resourceRenderer) {
+ res.setRenderer(resourceRenderer);
+ } else {
+ if (log.isDebugEnabled()) {
+ log.debug(Messages.getMessage(
+ Messages.NO_RESOURCE_REGISTERED_ERROR_2, path,
+ renderers.keySet()));
}
- throw new FacesException(Messages.getMessage(Messages.INSTANTIATE_CLASS_ERROR));
+
+ // String mimeType = servletContext.getMimeType(path);
+ res.setRenderer(defaultRenderer);
+ }
}
+ }
- /**
- * Create resource by instatiate {@link UserResource} class with given properties ( or got from cache ).
- * @param cacheable
- * @param session
- * @param mime
- * @return
- * @throws FacesException
- */
- public InternetResource createUserResource(boolean cacheable, boolean session, String mime) throws FacesException {
- String path = getUserResourceKey(cacheable, session, mime);
- InternetResource userResource;
- try {
- userResource = getResource(path);
- } catch (ResourceNotFoundException e) {
- userResource = new UserResource(cacheable,session,mime);
- addResource(path,userResource);
- }
- return userResource;
+ /**
+ * Create resurce to send from classpath relative to base class.
+ *
+ * @param base
+ * @param path
+ * @return
+ * @throws FacesException
+ */
+ protected InternetResource createJarResource(Object base, String path)
+ throws ResourceNotFoundException, FacesException {
+ String key = buildKey(base, path);
+ ClassLoader loader = Thread.currentThread().getContextClassLoader();
+ if (null != loader.getResource(key)) {
+ JarResource res = new JarResource(key);
+ setRenderer(res, path);
+ res.setLastModified(new Date(getStartTime()));
+ addResource(key, res);
+ return res;
+ } else {
+ throw new ResourceNotFoundException(Messages.getMessage(
+ Messages.NO_RESOURCE_EXISTS_ERROR, key));
}
- /**
- * Generate resource key for user-generated resource with given properties.
- * @param cacheable
- * @param session
- * @param mime
- * @return
- */
- private String getUserResourceKey(boolean cacheable, boolean session, String mime) {
- StringBuffer pathBuffer = new StringBuffer(UserResource.class.getName());
- pathBuffer.append(cacheable?"/c":"/n");
- pathBuffer.append(session?"/s":"/n");
- if(null != mime){
- pathBuffer.append('/').append(mime.hashCode());
- }
- String path = pathBuffer.toString();
- return path;
+ }
+
+ /**
+ * Create resource by instatiate given class.
+ *
+ * @param path
+ * @param instatiate
+ * @return
+ */
+ protected InternetResource createDynamicResource(String path,
+ Class instatiate) throws ResourceNotFoundException {
+ if (InternetResource.class.isAssignableFrom(instatiate)) {
+ InternetResource resource;
+ try {
+ resource = (InternetResource) instatiate.newInstance();
+ addResource(path, resource);
+ } catch (Exception e) {
+ String message = Messages.getMessage(
+ Messages.INSTANTIATE_RESOURCE_ERROR, instatiate
+ .toString());
+ log.error(message, e);
+ throw new ResourceNotFoundException(message, e);
+ }
+ return resource;
}
- /**
- * @return Returns the startTime for application.
- */
- public long getStartTime() {
- return _startTime;
+ throw new FacesException(Messages
+ .getMessage(Messages.INSTANTIATE_CLASS_ERROR));
+ }
+
+ /**
+ * Create resource by instatiate {@link UserResource} class with given
+ * properties ( or got from cache ).
+ *
+ * @param cacheable
+ * @param session
+ * @param mime
+ * @return
+ * @throws FacesException
+ */
+ public InternetResource createUserResource(boolean cacheable,
+ boolean session, String mime) throws FacesException {
+ String path = getUserResourceKey(cacheable, session, mime);
+ InternetResource userResource;
+ try {
+ userResource = getResource(path);
+ } catch (ResourceNotFoundException e) {
+ userResource = new UserResource(cacheable, session, mime);
+ addResource(path, userResource);
}
+ return userResource;
+ }
- protected byte[] encrypt(byte[] src) {
- try {
- Deflater compressor = new Deflater(Deflater.BEST_SPEED);
- byte[] compressed = new byte[src.length + 100];
- compressor.setInput(src);
- compressor.finish();
- int totalOut = compressor.deflate(compressed);
- byte[] zipsrc = new byte[totalOut];
- System.arraycopy(compressed, 0, zipsrc, 0, totalOut);
- return codec.encode(zipsrc);
- } catch (Exception e) {
- throw new FacesException("Error encode resource data",e);
- }
+ /**
+ * Generate resource key for user-generated resource with given
+ * properties.
+ *
+ * @param cacheable
+ * @param session
+ * @param mime
+ * @return
+ */
+ private String getUserResourceKey(boolean cacheable, boolean session,
+ String mime) {
+ StringBuffer pathBuffer = new StringBuffer(UserResource.class.getName());
+ pathBuffer.append(cacheable ? "/c" : "/n");
+ pathBuffer.append(session ? "/s" : "/n");
+ if (null != mime) {
+ pathBuffer.append('/').append(mime.hashCode());
}
+ String path = pathBuffer.toString();
+ return path;
+ }
- protected byte[] decrypt(byte[] src) {
- try {
- byte[] zipsrc = codec.decode(src);
- Inflater decompressor = new Inflater();
- byte[] uncompressed = new byte[zipsrc.length * 5];
- decompressor.setInput(zipsrc);
- int totalOut = decompressor.inflate(uncompressed);
- decompressor.end();
- byte[] out = new byte[totalOut];
- System.arraycopy(uncompressed, 0, out, 0, totalOut);
- return out;
- } catch (Exception e) {
- throw new FacesException("Error decode resource data",e);
- }
+ /**
+ * @return Returns the startTime for application.
+ */
+ public long getStartTime() {
+ return _startTime;
+ }
+
+ protected byte[] encrypt(byte[] src) {
+ try {
+ Deflater compressor = new Deflater(Deflater.BEST_SPEED);
+ byte[] compressed = new byte[src.length + 100];
+ compressor.setInput(src);
+ compressor.finish();
+ int totalOut = compressor.deflate(compressed);
+ byte[] zipsrc = new byte[totalOut];
+ System.arraycopy(compressed, 0, zipsrc, 0, totalOut);
+ return codec.encode(zipsrc);
+ } catch (Exception e) {
+ throw new FacesException("Error encode resource data", e);
}
+ }
-
-
+ protected byte[] decrypt(byte[] src) {
+ try {
+ byte[] zipsrc = codec.decode(src);
+ Inflater decompressor = new Inflater();
+ byte[] uncompressed = new byte[zipsrc.length * 5];
+ decompressor.setInput(zipsrc);
+ int totalOut = decompressor.inflate(uncompressed);
+ decompressor.end();
+ byte[] out = new byte[totalOut];
+ System.arraycopy(uncompressed, 0, out, 0, totalOut);
+ return out;
+ } catch (Exception e) {
+ throw new FacesException("Error decode resource data", e);
+ }
+ }
+
}
Modified: trunk/framework/src/main/java/org/ajax4jsf/framework/resource/cached/CachedResourceBuilder.java
===================================================================
--- trunk/framework/src/main/java/org/ajax4jsf/framework/resource/cached/CachedResourceBuilder.java 2007-04-17 21:04:13 UTC (rev 93)
+++ trunk/framework/src/main/java/org/ajax4jsf/framework/resource/cached/CachedResourceBuilder.java 2007-04-18 00:59:13 UTC (rev 94)
@@ -25,6 +25,7 @@
import java.io.InputStream;
import java.util.Properties;
+import javax.faces.FacesException;
import javax.faces.context.FacesContext;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
@@ -33,144 +34,166 @@
import org.ajax4jsf.framework.resource.ResourceBuilderImpl;
import org.ajax4jsf.framework.resource.ResourceNotFoundException;
import org.ajax4jsf.framework.util.message.Messages;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
-
/**
* @author shura
- *
+ *
*/
public class CachedResourceBuilder extends ResourceBuilderImpl {
- private static final int DEFAULT_CAPACITY = 10000;
+ private static final Log log = LogFactory
+ .getLog(CachedResourceBuilder.class);
- private ServletContext servletContext;
-
- private long counter = 0;
-
- private DualLRUMap cache ;
-
- /* (non-Javadoc)
- * @see org.ajax4jsf.framework.resource.ResourceBuilderImpl#decrypt(byte[])
- */
- protected byte[] decrypt(byte[] data) {
- // dummy - data not send via internet.
- return data;
- }
+ private static final int DEFAULT_CAPACITY = 10000;
- /* (non-Javadoc)
- * @see org.ajax4jsf.framework.resource.ResourceBuilderImpl#encrypt(byte[])
- */
- protected byte[] encrypt(byte[] data) {
- // dummy - data not send via internet.
- return data;
+ private long counter = 0;
+
+ private DualLRUMap cache;
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.ajax4jsf.framework.resource.ResourceBuilderImpl#decrypt(byte[])
+ */
+ protected byte[] decrypt(byte[] data) {
+ // dummy - data not send via internet.
+ return data;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.ajax4jsf.framework.resource.ResourceBuilderImpl#encrypt(byte[])
+ */
+ protected byte[] encrypt(byte[] data) {
+ // dummy - data not send via internet.
+ return data;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.ajax4jsf.framework.resource.ResourceBuilderImpl#getResourceDataForKey(java.lang.String)
+ */
+ public Object getResourceDataForKey(String key) {
+ ResourceBean bean = (ResourceBean) cache.get(key);
+ if (null == bean) {
+ throw new ResourceNotFoundException("Resource for key " + key
+ + "not present in cache");
}
+ return bean.getData();
+ }
- /* (non-Javadoc)
- * @see org.ajax4jsf.framework.resource.ResourceBuilderImpl#getResourceDataForKey(java.lang.String)
- */
- public Object getResourceDataForKey(String key) {
- ResourceBean bean = (ResourceBean) cache.get(key);
- if(null == bean){
- throw new ResourceNotFoundException("Resource for key "+key+"not present in cache");
- }
- return bean.getData();
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.ajax4jsf.framework.resource.ResourceBuilderImpl#getResourceForKey(java.lang.String)
+ */
+ public InternetResource getResourceForKey(String key)
+ throws ResourceNotFoundException {
+ ResourceBean bean = (ResourceBean) cache.get(key);
+ if (null == bean) {
+ throw new ResourceNotFoundException("Resource for key " + key
+ + "not present in cache");
}
+ return super.getResourceForKey(bean.getKey());
+ }
- /* (non-Javadoc)
- * @see org.ajax4jsf.framework.resource.ResourceBuilderImpl#getResourceForKey(java.lang.String)
- */
- public InternetResource getResourceForKey(String key) throws ResourceNotFoundException {
- ResourceBean bean = (ResourceBean) cache.get(key);
- if(null == bean){
- throw new ResourceNotFoundException("Resource for key "+key+"not present in cache");
- }
- return super.getResourceForKey(bean.getKey());
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.ajax4jsf.framework.resource.ResourceBuilderImpl#getUri(org.ajax4jsf.framework.resource.InternetResource,
+ * javax.faces.context.FacesContext, java.lang.Object)
+ */
+ public String getUri(InternetResource resource, FacesContext facesContext,
+ Object data) {
+ ResourceBean bean;
+ if (null == data) {
+ bean = new ResourceBean(resource.getKey());
+ } else {
+ if (data instanceof byte[]) {
+ // Special case for simple bytes array data.
+ bean = new ResourceBytesDataBean(resource.getKey(),
+ (byte[]) data);
+ } else {
+ bean = new ResourceDataBean(resource.getKey(), data);
+ }
}
+ String key = (String) cache.getKey(bean);
+ if (null == key) {
+ synchronized (this) {
+ counter++;
+ key = bean.hashCode() + "c" + counter;
+ }
+ cache.put(key, bean);
+ } else {
+ // Refresh LRU
+ cache.get(key);
+ }
+ String resourceURL = getFacesResourceURL(facesContext, key);
+ if (resource.isSessionAware()) {
+ resourceURL = facesContext.getExternalContext().encodeResourceURL(
+ resourceURL);
+ }
+ if (log.isDebugEnabled()) {
+ log.debug(Messages.getMessage(Messages.BUILD_RESOURCE_URI_INFO,
+ resource.getKey(), resourceURL));
+ }
+ return resourceURL;// context.getExternalContext().encodeResourceURL(resourceURL);
+ }
- /* (non-Javadoc)
- * @see org.ajax4jsf.framework.resource.ResourceBuilderImpl#getUri(org.ajax4jsf.framework.resource.InternetResource, javax.faces.context.FacesContext, java.lang.Object)
- */
- public String getUri(InternetResource resource, FacesContext facesContext, Object data) {
- ResourceBean bean;
- if(null == data){
- bean = new ResourceBean(resource.getKey());
- } else {
- if (data instanceof byte[]) {
- // Special case for simple bytes array data.
- bean = new ResourceBytesDataBean(resource.getKey(),(byte[])data);
- } else {
- bean = new ResourceDataBean(resource.getKey(),data);
- }
- }
- String key = (String) cache.getKey(bean);
- if(null == key){
- synchronized (this) {
- counter++;
- key = bean.hashCode()+"c"+counter;
- }
- cache.put(key, bean);
- } else {
- // Refresh LRU
- cache.get(key);
- }
- String resourceURL = getFacesResourceURL(facesContext, key);
- if (resource.isSessionAware()) {
- resourceURL = facesContext.getExternalContext().encodeResourceURL(
- resourceURL);
- }
- if (log.isDebugEnabled()) {
- log.debug(Messages.getMessage(Messages.BUILD_RESOURCE_URI_INFO,
- resource.getKey(), resourceURL));
- }
- return resourceURL;// context.getExternalContext().encodeResourceURL(resourceURL);
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.ajax4jsf.framework.resource.ResourceBuilderImpl#init(javax.servlet.ServletContext,
+ * java.lang.String)
+ */
+ public void init()
+ throws FacesException {
+ super.init();
+ // Create cache manager.
+ Properties properties = getProperties("cache.properties");
+ int capacity = DEFAULT_CAPACITY;
+ String capacityString = properties.getProperty("cache.capacity");
+ if (null != capacityString) {
+ try {
+ capacity = Integer.parseInt(capacityString);
+ } catch (NumberFormatException e) {
+ log.warn("Error parsing value of parameters cache capacity, use default value "+DEFAULT_CAPACITY, e);
+ }
}
+ cache = new DualLRUMap(capacity);
+ counter = getStartTime() - 1158760000000L;
+ }
- /* (non-Javadoc)
- * @see org.ajax4jsf.framework.resource.ResourceBuilderImpl#init(javax.servlet.ServletContext, java.lang.String)
- */
- public void init(ServletContext servletContext, String filterName) throws ServletException {
- // TODO Auto-generated method stub
- super.init(servletContext, filterName);
- // Create cache manager.
- Properties properties = getProperties("cache.properties");
- int capacity = DEFAULT_CAPACITY;
- String capacityString = properties.getProperty("cache.capacity");
- if(null != capacityString){
- try {
- capacity = Integer.parseInt(capacityString);
- } catch (NumberFormatException e) {
- // use default.
- }
+ /**
+ * Get properties file from classpath
+ *
+ * @param name
+ * @return
+ */
+ protected Properties getProperties(String name) {
+ Properties properties = new Properties();
+ InputStream props = CachedResourceBuilder.class
+ .getResourceAsStream(name);
+ if (null != props) {
+ try {
+ properties.load(props);
+ } catch (IOException e) {
+ // TODO Auto-generated catch block
+ log.warn(Messages.getMessage(Messages.READING_PROPERTIES_ERROR,
+ name), e);
+ } finally {
+ try {
+ props.close();
+ } catch (IOException e) {
+ // Can be ignored
}
- cache = new DualLRUMap(capacity);
- this.servletContext = servletContext;
- counter = getStartTime()-1158760000000L;
+ }
}
- /**
- * Get properties file from classpath
- *
- * @param name
- * @return
- */
- protected Properties getProperties(String name) {
- Properties properties = new Properties();
- InputStream props = CachedResourceBuilder.class.getResourceAsStream(name);
- if (null != props) {
- try {
- properties.load(props);
- } catch (IOException e) {
- // TODO Auto-generated catch block
- log.warn(Messages.getMessage(Messages.READING_PROPERTIES_ERROR,
- name), e);
- } finally {
- try {
- props.close();
- } catch (IOException e) {
- // Can be ignored
- }
- }
- }
- return properties;
+ return properties;
- }
+ }
}
Modified: trunk/framework/src/main/java/org/ajax4jsf/framework/util/base64/Codec.java
===================================================================
--- trunk/framework/src/main/java/org/ajax4jsf/framework/util/base64/Codec.java 2007-04-17 21:04:13 UTC (rev 93)
+++ trunk/framework/src/main/java/org/ajax4jsf/framework/util/base64/Codec.java 2007-04-18 00:59:13 UTC (rev 94)
@@ -21,12 +21,18 @@
package org.ajax4jsf.framework.util.base64;
+import java.io.UnsupportedEncodingException;
+import java.security.InvalidKeyException;
+import java.security.NoSuchAlgorithmException;
+import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;
import javax.crypto.Cipher;
+import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
+import javax.faces.FacesException;
/**
* @author shura (latest modification by $Author: alexsmirnov $)
@@ -43,33 +49,43 @@
*
*/
public Codec() {
- super();
- // TODO Auto-generated constructor stub
}
/**
*
*/
public Codec( String p ) throws Exception {
- byte[] s = {
- (byte)0xA9, (byte)0x9B, (byte)0xC8, (byte)0x32,
- (byte)0x56, (byte)0x34, (byte)0xE3, (byte)0x03
- };
-// try {
- KeySpec keySpec = new DESKeySpec(p.getBytes("UTF8"));
- SecretKey key = SecretKeyFactory.getInstance("DES")
- .generateSecret(keySpec);
- e = Cipher.getInstance(key.getAlgorithm());
- d = Cipher.getInstance(key.getAlgorithm());
+ setPassword(p);
+ }
- // Prepare the parameters to the cipthers
+ /**
+ * @param p
+ * @throws InvalidKeyException
+ * @throws UnsupportedEncodingException
+ * @throws InvalidKeySpecException
+ * @throws NoSuchAlgorithmException
+ * @throws NoSuchPaddingException
+ */
+ public void setPassword(String p) throws FacesException {
+ byte[] s = {
+ (byte)0xA9, (byte)0x9B, (byte)0xC8, (byte)0x32,
+ (byte)0x56, (byte)0x34, (byte)0xE3, (byte)0x03
+ };
+ try {
+ KeySpec keySpec = new DESKeySpec(p.getBytes("UTF8"));
+ SecretKey key = SecretKeyFactory.getInstance("DES")
+ .generateSecret(keySpec);
+ e = Cipher.getInstance(key.getAlgorithm());
+ d = Cipher.getInstance(key.getAlgorithm());
+
+ // Prepare the parameters to the cipthers
// AlgorithmParameterSpec paramSpec = new IvParameterSpec(s);
- e.init(Cipher.ENCRYPT_MODE, key);
- d.init(Cipher.DECRYPT_MODE, key);
-// } catch (Exception e) {
-// // TODO: handle exception
-// }
+ e.init(Cipher.ENCRYPT_MODE, key);
+ d.init(Cipher.DECRYPT_MODE, key);
+ } catch (Exception e) {
+ throw new FacesException("Error set encryption key",e);
+ }
}
public String decode(String str) throws Exception {
Modified: trunk/framework/src/main/java/org/ajax4jsf/framework/util/config/WebXml.java
===================================================================
--- trunk/framework/src/main/java/org/ajax4jsf/framework/util/config/WebXml.java 2007-04-17 21:04:13 UTC (rev 93)
+++ trunk/framework/src/main/java/org/ajax4jsf/framework/util/config/WebXml.java 2007-04-18 00:59:13 UTC (rev 94)
@@ -23,6 +23,7 @@
import java.io.IOException;
import java.io.InputStream;
+import java.io.Serializable;
import java.io.StringReader;
import java.util.HashMap;
import java.util.Iterator;
@@ -51,11 +52,19 @@
* @version $Revision: 1.1.2.1 $ $Date: 2007/01/09 18:58:59 $
*
*/
-public class WebXml {
+public class WebXml implements Serializable {
+ public static final String CONTEXT_ATTRIBUTE = WebXml.class.getName();
+
+ /**
+ *
+ */
+ private static final long serialVersionUID = -9042908418843695017L;
+
private static final Log _log = LogFactory.getLog(WebXml.class);
static final String WEB_XML = "/WEB-INF/web.xml";
+
public static final String RESOURCE_URI_PREFIX = "a4j.res/";
@@ -87,90 +96,89 @@
*/
private String _resourcePrefix = RESOURCE_URI_PREFIX_WITH_SLASH;
+
/**
* Parse application web.xml configuration and detect mapping for resources
* and logs.
- *
* @param context
- * Current servlet context.
* @param filterName
- * name for Chameleon support filter.
+ * @throws ServletException
*/
- public WebXml(ServletContext context, String filterName)
- throws ServletException {
- super();
- InputStream webXml = context.getResourceAsStream(WEB_XML);
- if (null == webXml) {
- throw new ServletException(Messages.getMessage(
- Messages.GET_RESOURCE_AS_STREAM_ERROR, WEB_XML));
- }
- Digester dig = new Digester();
- dig.setDocumentLocator(new LocatorImpl());
- // Disable xml validations at all - web.xml already validated by
- // container
- dig.setValidating(false);
- dig.setEntityResolver(new EntityResolver() {
- // Dummi resolver - alvays do nothing
- public InputSource resolveEntity(String publicId, String systemId)
- throws SAXException, IOException {
- return new InputSource(new StringReader(""));
- }
+ public void init(ServletContext context, String filterName) throws ServletException {
+ InputStream webXml = context.getResourceAsStream(WEB_XML);
+ if (null == webXml) {
+ throw new ServletException(Messages.getMessage(
+ Messages.GET_RESOURCE_AS_STREAM_ERROR, WEB_XML));
+ }
+ Digester dig = new Digester();
+ dig.setDocumentLocator(new LocatorImpl());
+ // Disable xml validations at all - web.xml already validated by
+ // container
+ dig.setValidating(false);
+ dig.setEntityResolver(new EntityResolver() {
+ // Dummi resolver - alvays do nothing
+ public InputSource resolveEntity(String publicId, String systemId)
+ throws SAXException, IOException {
+ return new InputSource(new StringReader(""));
+ }
- });
- dig.setNamespaceAware(false);
- // dig.setUseContextClassLoader(true);
- dig.setClassLoader(this.getClass().getClassLoader());
- // Parsing rules.
- // Servlets.
- String path = "web-app/servlet";
- dig.addObjectCreate(path, ServletBean.class);
- dig.addBeanPropertySetter(path + "/servlet-name", "servletName");
- dig.addBeanPropertySetter(path + "/servlet-class", "servletClass");
- dig.addBeanPropertySetter(path + "/display-name", "displayName");
- dig.addBeanPropertySetter(path + "/description");
- dig.addSetNext(path, "addServlet");
- // Filters
- path = "web-app/filter";
- dig.addObjectCreate(path, FilterBean.class);
- dig.addBeanPropertySetter(path + "/filter-name", "filterName");
- dig.addBeanPropertySetter(path + "/filter-class", "filterClass");
- dig.addBeanPropertySetter(path + "/display-name", "displayName");
- dig.addBeanPropertySetter(path + "/description");
- dig.addSetNext(path, "addFilter");
- // Servlet mappings
- path = "web-app/servlet-mapping";
- dig.addCallMethod(path, "addServletMapping", 2);
- dig.addCallParam(path + "/servlet-name", 0);
- dig.addCallParam(path + "/url-pattern", 1);
- // Filter mappings
- // TODO - parse dispatcher.
- path = "web-app/filter-mapping";
- dig.addCallMethod(path, "addFilterMapping", 3);
- dig.addCallParam(path + "/filter-name", 0);
- dig.addCallParam(path + "/url-pattern", 1);
- dig.addCallParam(path + "/servlet-name", 2);
- dig.push(this);
- try {
- dig.parse(webXml);
- this.setFilterName(filterName);
- } catch (IOException e) {
- String message = Messages
- .getMessage(Messages.PARSING_WEB_XML_IO_ERROR);
- _log.error(message, e);
- throw new ServletException(message, e);
- } catch (SAXException e) {
- String message = Messages
- .getMessage(Messages.PARSING_WEB_XML_SAX_ERROR);
- _log.error(message, e);
- throw new ServletException(message, e);
- } finally {
- try {
- webXml.close();
- } catch (IOException e) {
- // this exception don't affect any aspects of work and can be
- // ignored.
- }
- }
+ });
+ dig.setNamespaceAware(false);
+ // dig.setUseContextClassLoader(true);
+ dig.setClassLoader(this.getClass().getClassLoader());
+ // Parsing rules.
+ // Servlets.
+ String path = "web-app/servlet";
+ dig.addObjectCreate(path, ServletBean.class);
+ dig.addBeanPropertySetter(path + "/servlet-name", "servletName");
+ dig.addBeanPropertySetter(path + "/servlet-class", "servletClass");
+ dig.addBeanPropertySetter(path + "/display-name", "displayName");
+ dig.addBeanPropertySetter(path + "/description");
+ dig.addSetNext(path, "addServlet");
+ // Filters
+ path = "web-app/filter";
+ dig.addObjectCreate(path, FilterBean.class);
+ dig.addBeanPropertySetter(path + "/filter-name", "filterName");
+ dig.addBeanPropertySetter(path + "/filter-class", "filterClass");
+ dig.addBeanPropertySetter(path + "/display-name", "displayName");
+ dig.addBeanPropertySetter(path + "/description");
+ dig.addSetNext(path, "addFilter");
+ // Servlet mappings
+ path = "web-app/servlet-mapping";
+ dig.addCallMethod(path, "addServletMapping", 2);
+ dig.addCallParam(path + "/servlet-name", 0);
+ dig.addCallParam(path + "/url-pattern", 1);
+ // Filter mappings
+ // TODO - parse dispatcher.
+ path = "web-app/filter-mapping";
+ dig.addCallMethod(path, "addFilterMapping", 3);
+ dig.addCallParam(path + "/filter-name", 0);
+ dig.addCallParam(path + "/url-pattern", 1);
+ dig.addCallParam(path + "/servlet-name", 2);
+ dig.push(this);
+ try {
+ dig.parse(webXml);
+ this.setFilterName(filterName);
+ // Store Instance to context attribute.
+ context.setAttribute(CONTEXT_ATTRIBUTE,this);
+ } catch (IOException e) {
+ String message = Messages
+ .getMessage(Messages.PARSING_WEB_XML_IO_ERROR);
+ _log.error(message, e);
+ throw new ServletException(message, e);
+ } catch (SAXException e) {
+ String message = Messages
+ .getMessage(Messages.PARSING_WEB_XML_SAX_ERROR);
+ _log.error(message, e);
+ throw new ServletException(message, e);
+ } finally {
+ try {
+ webXml.close();
+ } catch (IOException e) {
+ // this exception don't affect any aspects of work and can be
+ // ignored.
+ }
+ }
}
public void addServlet(ServletBean bean) {
@@ -362,7 +370,7 @@
_log.warn(Messages.getMessage(Messages.FILTER_NOT_FOUND_ERROR,
_filterName));
throw new IllegalStateException(Messages.getMessage(
- Messages.FILTER_NOT_CONFIGURED_ERROR, filterName));
+ Messages.FILTER_NOT_FOUND_ERROR, filterName));
}
// find faces servlet
checkMapping(filter.getMappings());
17 years, 8 months
JBoss Ajax4JSF SVN: r93 - trunk/cdk/maven-cdk-plugin/src/main/java/org/ajax4jsf/builder/mojo.
by ajax4jsf-svn-commits@lists.jboss.org
Author: nbelaevski
Date: 2007-04-17 17:04:13 -0400 (Tue, 17 Apr 2007)
New Revision: 93
Modified:
trunk/cdk/maven-cdk-plugin/src/main/java/org/ajax4jsf/builder/mojo/GenerateMojo.java
Log:
RF-84 first variant
Modified: trunk/cdk/maven-cdk-plugin/src/main/java/org/ajax4jsf/builder/mojo/GenerateMojo.java
===================================================================
--- trunk/cdk/maven-cdk-plugin/src/main/java/org/ajax4jsf/builder/mojo/GenerateMojo.java 2007-04-17 21:04:09 UTC (rev 92)
+++ trunk/cdk/maven-cdk-plugin/src/main/java/org/ajax4jsf/builder/mojo/GenerateMojo.java 2007-04-17 21:04:13 UTC (rev 93)
@@ -23,16 +23,10 @@
import java.io.File;
import java.io.FilenameFilter;
-import java.net.MalformedURLException;
-import java.net.URL;
-import java.net.URLClassLoader;
-import java.util.Iterator;
-import java.util.List;
import org.ajax4jsf.builder.config.BuilderConfig;
import org.ajax4jsf.builder.config.ParsingException;
import org.ajax4jsf.builder.generator.ComponentGenerator;
-import org.ajax4jsf.builder.generator.ComponentTestGenerator;
import org.ajax4jsf.builder.generator.FaceletsTaglibGenerator;
import org.ajax4jsf.builder.generator.FacesConfigGenerator;
import org.ajax4jsf.builder.generator.GeneratorException;
@@ -40,13 +34,12 @@
import org.ajax4jsf.builder.generator.ListenerGenerator;
import org.ajax4jsf.builder.generator.RenderKitBean;
import org.ajax4jsf.builder.generator.RendererGenerator;
+import org.ajax4jsf.builder.generator.ResourcesConfigGenerator;
import org.ajax4jsf.builder.generator.TagGenerator;
import org.ajax4jsf.builder.generator.TagHandlerGenerator;
-import org.ajax4jsf.builder.generator.TagTestGenerator;
import org.ajax4jsf.builder.generator.TaglibGenerator;
import org.ajax4jsf.builder.maven.MavenLogger;
import org.ajax4jsf.builder.velocity.BuilderContext;
-import org.apache.maven.artifact.DependencyResolutionRequiredException;
import org.apache.maven.model.Resource;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
@@ -187,6 +180,12 @@
}
// Generate resources configuration file resources-config.xml
// for all images/scripts/css...
+ ResourcesConfigGenerator resourcesConfigGenerator = new ResourcesConfigGenerator(resourcesConfiguration, mavenLogger);
+ resourcesConfigGenerator.setTemplates(templatesDirectory);
+ resourcesConfigGenerator.setResourcesConfig(new File(
+ outputResourcesDirectory, "META-INF/resources-config.xml"));
+ resourcesConfigGenerator.createFiles(config);
+
// Add generated sources and resources to project
project.addCompileSourceRoot(outputJavaDirectory.getPath());
// project.addCompileSourceRoot(outputTestsDirectory.getPath());
17 years, 8 months
JBoss Ajax4JSF SVN: r92 - in trunk/cdk/compiler/src/main/java/org/ajax4jsf/templatecompiler/elements: vcp and 1 other directory.
by ajax4jsf-svn-commits@lists.jboss.org
Author: nbelaevski
Date: 2007-04-17 17:04:09 -0400 (Tue, 17 Apr 2007)
New Revision: 92
Modified:
trunk/cdk/compiler/src/main/java/org/ajax4jsf/templatecompiler/elements/TemplateElement.java
trunk/cdk/compiler/src/main/java/org/ajax4jsf/templatecompiler/elements/TemplateElementBase.java
trunk/cdk/compiler/src/main/java/org/ajax4jsf/templatecompiler/elements/vcp/FResourceTemplateElement.java
Log:
RF-84 first variant
Modified: trunk/cdk/compiler/src/main/java/org/ajax4jsf/templatecompiler/elements/TemplateElement.java
===================================================================
--- trunk/cdk/compiler/src/main/java/org/ajax4jsf/templatecompiler/elements/TemplateElement.java 2007-04-17 21:04:04 UTC (rev 91)
+++ trunk/cdk/compiler/src/main/java/org/ajax4jsf/templatecompiler/elements/TemplateElement.java 2007-04-17 21:04:09 UTC (rev 92)
@@ -21,6 +21,8 @@
package org.ajax4jsf.templatecompiler.elements;
+import java.util.ArrayList;
+
import org.ajax4jsf.templatecompiler.builder.CompilationException;
/**
@@ -40,5 +42,10 @@
public void addSubElement(TemplateElement e);
public String toCode() throws CompilationException;
+
+ /**
+ * @return the subElements
+ */
+ public ArrayList<TemplateElement> getSubElements();
}
Modified: trunk/cdk/compiler/src/main/java/org/ajax4jsf/templatecompiler/elements/TemplateElementBase.java
===================================================================
--- trunk/cdk/compiler/src/main/java/org/ajax4jsf/templatecompiler/elements/TemplateElementBase.java 2007-04-17 21:04:04 UTC (rev 91)
+++ trunk/cdk/compiler/src/main/java/org/ajax4jsf/templatecompiler/elements/TemplateElementBase.java 2007-04-17 21:04:09 UTC (rev 92)
@@ -85,7 +85,7 @@
/**
* @return the subElements
*/
- protected ElementsArray getSubElements() {
+ public ElementsArray getSubElements() {
return this.subElements;
}
Modified: trunk/cdk/compiler/src/main/java/org/ajax4jsf/templatecompiler/elements/vcp/FResourceTemplateElement.java
===================================================================
--- trunk/cdk/compiler/src/main/java/org/ajax4jsf/templatecompiler/elements/vcp/FResourceTemplateElement.java 2007-04-17 21:04:04 UTC (rev 91)
+++ trunk/cdk/compiler/src/main/java/org/ajax4jsf/templatecompiler/elements/vcp/FResourceTemplateElement.java 2007-04-17 21:04:09 UTC (rev 92)
@@ -80,4 +80,11 @@
return null;
}
+ public String getName() {
+ return name;
+ }
+
+ public String getVariable() {
+ return variable;
+ }
}
17 years, 8 months
JBoss Ajax4JSF SVN: r91 - in trunk/cdk/generator/src/main: resources/META-INF/templates and 1 other directory.
by ajax4jsf-svn-commits@lists.jboss.org
Author: nbelaevski
Date: 2007-04-17 17:04:04 -0400 (Tue, 17 Apr 2007)
New Revision: 91
Added:
trunk/cdk/generator/src/main/java/org/ajax4jsf/builder/generator/ResourceConfigGeneratorBean.java
trunk/cdk/generator/src/main/java/org/ajax4jsf/builder/generator/ResourcesConfigGenerator.java
trunk/cdk/generator/src/main/resources/META-INF/templates/resources-config.vm
Log:
RF-84 first variant
Added: trunk/cdk/generator/src/main/java/org/ajax4jsf/builder/generator/ResourceConfigGeneratorBean.java
===================================================================
--- trunk/cdk/generator/src/main/java/org/ajax4jsf/builder/generator/ResourceConfigGeneratorBean.java (rev 0)
+++ trunk/cdk/generator/src/main/java/org/ajax4jsf/builder/generator/ResourceConfigGeneratorBean.java 2007-04-17 21:04:04 UTC (rev 91)
@@ -0,0 +1,64 @@
+/**
+ * License Agreement.
+ *
+ * Ajax4jsf 1.1 - Natural Ajax for Java Server Faces (JSF)
+ *
+ * Copyright (C) 2007 Exadel, Inc.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License version 2.1 as published by the Free Software Foundation.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+package org.ajax4jsf.builder.generator;
+
+
+
+/**
+ * @author Nick - mailto:nbelaevski@exadel.com
+ * created 17.04.2007
+ *
+ */
+public class ResourceConfigGeneratorBean {
+ private static final String DEFAULT_CLASS_NAME = "org.ajax4jsf.framework.resource.JarResource";
+
+ private String path;
+ private String contentType;
+ private String className = DEFAULT_CLASS_NAME;
+ private String key;
+
+ public String getPath() {
+ return path;
+ }
+ public void setPath(String path) {
+ this.path = path;
+ }
+ public String getContentType() {
+ return contentType;
+ }
+ public void setContentType(String contentType) {
+ this.contentType = contentType;
+ }
+ public String getClassName() {
+ return className;
+ }
+ public void setClassName(String className) {
+ this.className = className;
+ }
+ public String getKey() {
+ return key;
+ }
+ public void setKey(String key) {
+ this.key = key;
+ }
+
+}
\ No newline at end of file
Added: trunk/cdk/generator/src/main/java/org/ajax4jsf/builder/generator/ResourcesConfigGenerator.java
===================================================================
--- trunk/cdk/generator/src/main/java/org/ajax4jsf/builder/generator/ResourcesConfigGenerator.java (rev 0)
+++ trunk/cdk/generator/src/main/java/org/ajax4jsf/builder/generator/ResourcesConfigGenerator.java 2007-04-17 21:04:04 UTC (rev 91)
@@ -0,0 +1,196 @@
+/**
+ * License Agreement.
+ *
+ * Ajax4jsf 1.1 - Natural Ajax for Java Server Faces (JSF)
+ *
+ * Copyright (C) 2007 Exadel, Inc.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License version 2.1 as published by the Free Software Foundation.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+package org.ajax4jsf.builder.generator;
+
+import java.io.BufferedWriter;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileWriter;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.Writer;
+import java.util.ArrayList;
+import java.util.List;
+
+import org.ajax4jsf.builder.config.BuilderConfig;
+import org.ajax4jsf.builder.config.ComponentBean;
+import org.ajax4jsf.builder.config.RendererBean;
+import org.ajax4jsf.templatecompiler.builder.CompilationContext;
+import org.ajax4jsf.templatecompiler.builder.CompilationException;
+import org.ajax4jsf.templatecompiler.builder.TemplateCompiler;
+import org.ajax4jsf.templatecompiler.elements.TemplateElement;
+import org.ajax4jsf.templatecompiler.elements.vcp.FResourceTemplateElement;
+import org.apache.velocity.Template;
+import org.apache.velocity.VelocityContext;
+
+/**
+ * @author Nick - mailto:nbelaevski@exadel.com
+ * created 17.04.2007
+ *
+ */
+public class ResourcesConfigGenerator extends FacesConfigGenerator {
+
+ private File resourcesConfig;
+ private File templatesDirectory;
+
+ public ResourcesConfigGenerator(JSFGeneratorConfiguration task, Logger log) {
+ super(task, log);
+ }
+
+ private void addResources(List<ResourceConfigGeneratorBean> resources, TemplateElement templateElement,
+ String packageName) {
+ if (templateElement instanceof FResourceTemplateElement) {
+ FResourceTemplateElement resourceTemplateElement = (FResourceTemplateElement) templateElement;
+
+ ResourceConfigGeneratorBean resourceConfig = new ResourceConfigGeneratorBean();
+ String name = resourceTemplateElement.getName();
+ resourceConfig.setKey(name);
+ resourceConfig.setPath(resolvePath(name, packageName));
+
+ resources.add(resourceConfig);
+ }
+
+ ArrayList<TemplateElement> subElements = templateElement.getSubElements();
+ for (TemplateElement element : subElements) {
+ addResources(resources, element, packageName);
+ }
+ }
+
+ private String resolvePath(String name, String packageName) {
+ String resolvedName = name;
+ if (!name.startsWith("/") && name.contains("/")) {
+ //need to resolve
+ StringBuffer normalizedName = new StringBuffer();
+ if (!packageName.startsWith("/")) {
+ normalizedName.append('/');
+ }
+
+ normalizedName.append(packageName.replace('.', '/'));
+
+ if (!packageName.endsWith("/")) {
+ normalizedName.append('/');
+ }
+
+ normalizedName.append(name);
+
+ resolvedName = normalizedName.toString();
+ }
+
+ return resolvedName;
+ }
+
+ private void addResources(List<ResourceConfigGeneratorBean> resources, RendererBean renderer, BuilderConfig builderConfig) throws CompilationException, IOException, ClassNotFoundException {
+ if (null != renderer && renderer.isGenerate()
+ && null != renderer.getTemplate()) {
+
+ File template;
+ if (null != getTemplates()) {
+ template = new File(getTemplates(), renderer.getTemplate());
+ } else {
+ template = new File(renderer.getTemplate());
+ }
+ CompilationContext rendererBean = new RendererCompilationContext(
+ getLog(), getClassLoader(),getConfig());
+
+ TemplateCompiler templateCompiler = new TemplateCompiler();
+ InputStream templateStream = new FileInputStream(template);
+ templateCompiler.processing(templateStream, rendererBean);
+
+ TemplateElement root = rendererBean.getTree();
+
+ String classname = renderer.getClassname();
+ String packageName;
+ int idx = classname.lastIndexOf('.');
+ if (idx != -1) {
+ packageName = classname.substring(0, idx);
+ } else {
+ packageName = "";
+ }
+
+ addResources(resources, root, packageName);
+ }
+ }
+
+ public void createFiles(BuilderConfig config) throws GeneratorException {
+ VelocityContext context = new VelocityContext();
+ Template template = getTemplate();
+ try {
+ // Put common properties
+
+ ArrayList<ResourceConfigGeneratorBean> resourcesList = new ArrayList<ResourceConfigGeneratorBean>();
+
+ List<ComponentBean> components = config.getComponents();
+ for (ComponentBean componentBean : components) {
+ RendererBean rendererBean = componentBean.getRenderer();
+
+ addResources(resourcesList, rendererBean, config);
+ }
+
+ List<RendererBean> renderers = config.getRenderers();
+ for (RendererBean rendererBean : renderers) {
+ addResources(resourcesList, rendererBean, config);
+ }
+
+ context.put("resources", resourcesList);
+ context.put("facesConfig", this);
+ File configFile = getResourcesConfig();
+ File javaDir = configFile.getParentFile();
+ if (!javaDir.exists()) {
+ javaDir.mkdirs();
+ }
+ if (configFile.exists()) {
+ configFile.delete();
+ }
+ Writer out = new BufferedWriter(new FileWriter(configFile));
+ template.merge(context, out);
+ out.flush();
+ out.close();
+ } catch (Exception e) {
+ throw new GeneratorException("Error create new resources-config.xml ",
+ e);
+ }
+ }
+
+ protected String getRootTag() {
+ return "resource-config";
+ }
+
+ public File getResourcesConfig() {
+ return resourcesConfig;
+ }
+
+ public void setResourcesConfig(File resourcesConfig) {
+ this.resourcesConfig = resourcesConfig;
+ }
+
+ protected String getDefaultTemplateName() {
+ return "resources-config.vm";
+ }
+
+ public void setTemplates(File templatesDirectory) {
+ this.templatesDirectory = templatesDirectory;
+ }
+
+ public File getTemplates() {
+ return this.templatesDirectory;
+ }
+}
Added: trunk/cdk/generator/src/main/resources/META-INF/templates/resources-config.vm
===================================================================
--- trunk/cdk/generator/src/main/resources/META-INF/templates/resources-config.vm (rev 0)
+++ trunk/cdk/generator/src/main/resources/META-INF/templates/resources-config.vm 2007-04-17 21:04:04 UTC (rev 91)
@@ -0,0 +1,16 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<resource-config>
+
+#foreach( $resource in ${resources})
+<resource class="${resource.className}">
+ <!-- renderer class="${resource.renderer.className}">
+ <content-type>${resource.renderer.contentType}</content-type>
+ </renderer -->
+ <name>${resource.key}</name>
+ <path>${resource.path}</path>
+ <!-- content-type>${resource.contentType}</content-type -->
+
+</resource>
+#end
+
+</resource-config>
17 years, 8 months
JBoss Ajax4JSF SVN: r90 - in trunk: a4j-portlet/src/main/java and 10 other directories.
by ajax4jsf-svn-commits@lists.jboss.org
Author: alexsmirnov
Date: 2007-04-16 21:11:20 -0400 (Mon, 16 Apr 2007)
New Revision: 90
Added:
trunk/a4j-portlet/src/main/java/META-INF/
trunk/a4j-portlet/src/main/java/META-INF/MANIFEST.MF
trunk/a4j-portlet/src/main/java/org/ajax4jsf/portlet/PortletViewState.java
trunk/a4j-portlet/src/main/java/org/ajax4jsf/portlet/application/PortletViewHandler.java
trunk/a4j-portlet/src/main/resources/
trunk/a4j-portlet/src/main/resources/META-INF/
trunk/a4j-portlet/src/main/resources/META-INF/faces-config.xml
trunk/a4j-portlet/src/main/resources/META-INF/faces-config.xml.l4t
trunk/framework/src/main/java/META-INF/
trunk/framework/src/main/java/META-INF/MANIFEST.MF
Modified:
trunk/a4j-portlet/src/main/java/org/ajax4jsf/portlet/AjaxFacesPortlet.java
trunk/a4j-portlet/src/main/java/org/ajax4jsf/portlet/context/AbstractExternalContext.java
trunk/a4j-portlet/src/main/java/org/ajax4jsf/portlet/context/ContextMap.java
trunk/a4j-portlet/src/main/java/org/ajax4jsf/portlet/context/PortletContextImpl.java
trunk/a4j-portlet/src/main/java/org/ajax4jsf/portlet/context/ServletContextImpl.java
trunk/a4j-portlet/src/test/java/org/ajax4jsf/portlet/MockPortletContext.java
trunk/a4j-portlet/src/test/java/org/ajax4jsf/portlet/MockPortletRequest.java
trunk/a4j-portlet/src/test/java/org/ajax4jsf/portlet/context/ContextAttributesMapTest.java
trunk/a4j-portlet/src/test/java/org/ajax4jsf/portlet/context/PortletExternalContextTest.java
Log:
Continue to work on the portal support
Added: trunk/a4j-portlet/src/main/java/META-INF/MANIFEST.MF
===================================================================
--- trunk/a4j-portlet/src/main/java/META-INF/MANIFEST.MF (rev 0)
+++ trunk/a4j-portlet/src/main/java/META-INF/MANIFEST.MF 2007-04-17 01:11:20 UTC (rev 90)
@@ -0,0 +1,3 @@
+Manifest-Version: 1.0
+Class-Path:
+
Modified: trunk/a4j-portlet/src/main/java/org/ajax4jsf/portlet/AjaxFacesPortlet.java
===================================================================
--- trunk/a4j-portlet/src/main/java/org/ajax4jsf/portlet/AjaxFacesPortlet.java 2007-04-16 21:07:33 UTC (rev 89)
+++ trunk/a4j-portlet/src/main/java/org/ajax4jsf/portlet/AjaxFacesPortlet.java 2007-04-17 01:11:20 UTC (rev 90)
@@ -4,8 +4,12 @@
package org.ajax4jsf.portlet;
import java.io.IOException;
+import java.util.Iterator;
+import java.util.Map;
import javax.faces.FacesException;
import javax.faces.FactoryFinder;
+import javax.faces.application.FacesMessage;
+import javax.faces.component.UIViewRoot;
import javax.faces.context.FacesContext;
import javax.faces.context.FacesContextFactory;
import javax.faces.lifecycle.Lifecycle;
@@ -20,6 +24,7 @@
import javax.portlet.PortletResponse;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
+import org.ajax4jsf.portlet.context.AbstractExternalContext;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@@ -33,7 +38,6 @@
/**
* Stored portlet config.
*/
- private PortletConfig config;
private Lifecycle lifecycle;
@@ -45,7 +49,7 @@
* @see javax.portlet.GenericPortlet#init(javax.portlet.PortletConfig)
*/
public void init(PortletConfig config) throws PortletException {
- this.config = config;
+ super.init(config);
try {
if (log.isDebugEnabled()) {
log.debug("Start portlet initialisation for "
@@ -83,7 +87,7 @@
*/
public void destroy() {
if (log.isDebugEnabled()) {
- log.debug("Destroy portlet " + this.config.getPortletName());
+ log.debug("Destroy portlet " + getPortletConfig().getPortletName());
}
this.lifecycle = null;
this.facesContextFactory = null;
@@ -96,20 +100,80 @@
* @see javax.portlet.GenericPortlet#processAction(javax.portlet.ActionRequest,
* javax.portlet.ActionResponse)
*/
- public void processAction(ActionRequest arg0, ActionResponse arg1)
+ public void processAction(ActionRequest request, ActionResponse response)
throws PortletException, IOException {
+ if (log.isDebugEnabled()) {
+ log.debug("Process action in portlet " + getPortletConfig().getPortletName()+" for mode "+request.getPortletMode());
+ }
+ FacesContext facesContext = getFacesContext(request, response);
+ try {
+ setViewId(facesContext);
+ execute(facesContext);
+ saveView(facesContext);
+ } catch (Exception e) {
+ log.error("Error processing execute lifecycle", e);
+ throw new PortletException("Error processing execute lifecycle ",e);
+ } finally {
+ facesContext.release();
+ }
}
+ protected void saveView(FacesContext facesContext) {
+ PortletViewState state = new PortletViewState();
+ state.setViewRoot(facesContext.getViewRoot());
+ Iterator idsWithMessages = facesContext.getClientIdsWithMessages();
+ while (idsWithMessages.hasNext()) {
+ String id = (String) idsWithMessages.next();
+ Iterator messages = facesContext.getMessages(id);
+ while (messages.hasNext()) {
+ FacesMessage message = (FacesMessage) messages.next();
+ state.addMessage(id, message);
+ }
+ }
+ facesContext.getExternalContext().getRequestMap().put(PortletViewState.SAVED_VIEW_ATTRIBUTE, state);
+ }
+
/*
* (non-Javadoc)
*
* @see javax.portlet.GenericPortlet#doView(javax.portlet.RenderRequest,
* javax.portlet.RenderResponse)
*/
- protected void doView(RenderRequest arg0, RenderResponse arg1)
+ protected void doView(RenderRequest request, RenderResponse response)
throws PortletException, IOException {
+ if (log.isDebugEnabled()) {
+ log.debug("Process do view in portlet " + getPortletConfig().getPortletName());
+ }
+ FacesContext facesContext = getFacesContext(request, response);
+ try {
+ restoreView(facesContext);
+ render(facesContext);
+ } catch (Exception e) {
+ log.error("Error processing execute lifecycle", e);
+ throw new PortletException("Error processing execute lifecycle ",e);
+ } finally {
+ facesContext.release();
+ }
}
+ protected void restoreView(FacesContext facesContext) {
+ PortletViewState state = (PortletViewState) facesContext.getExternalContext().getRequestMap().get(PortletViewState.SAVED_VIEW_ATTRIBUTE);
+ if (null != state) {
+ facesContext.setViewRoot(state.getViewRoot());
+ Iterator idsWithMessages = state.getClientIdsWithMessages();
+ while (idsWithMessages.hasNext()) {
+ String id = (String) idsWithMessages.next();
+ Iterator messages = state.getMessages(id);
+ while (messages.hasNext()) {
+ FacesMessage message = (FacesMessage) messages.next();
+ facesContext.addMessage(id, message);
+ }
+ }
+ }else {
+ setViewId(facesContext);
+ }
+ }
+
/*
* (non-Javadoc)
*
@@ -118,6 +182,9 @@
*/
protected void doEdit(RenderRequest arg0, RenderResponse arg1)
throws PortletException, IOException {
+ if (log.isDebugEnabled()) {
+ log.debug("Process do edit in portlet " + getPortletConfig().getPortletName());
+ }
}
/*
@@ -128,14 +195,11 @@
*/
protected void doHelp(RenderRequest arg0, RenderResponse arg1)
throws PortletException, IOException {
+ if (log.isDebugEnabled()) {
+ log.debug("Process do help in portlet " + getPortletConfig().getPortletName());
+ }
}
- /**
- * @return portlet config, stored at init() method.
- */
- protected PortletConfig getConfig() {
- return this.config;
- }
/**
* Get currenf JSF lifecycle instance.
@@ -155,7 +219,7 @@
*/
protected FacesContext getFacesContext(PortletRequest request,
PortletResponse response) {
- return this.facesContextFactory.getFacesContext(getConfig()
+ return this.facesContextFactory.getFacesContext(getPortletConfig()
.getPortletContext(), request, response, getLifecycle());
}
@@ -166,4 +230,21 @@
protected void render(FacesContext context) throws FacesException {
getLifecycle().render(context);
}
+
+ protected void setViewId(FacesContext context) {
+ String viewId = (String) context.getExternalContext().getRequestParameterMap().get(AbstractExternalContext.VIEW_ID_PARAMETER);
+ if(null == viewId){
+ viewId = getInitParameter("default-view");
+ }
+ if(null == viewId){
+ throw new IllegalArgumentException("Initial view id must be set as portlet parameter");
+ }
+ UIViewRoot viewRoot = context.getViewRoot();
+ if(null == viewRoot){
+ viewRoot = context.getApplication().getViewHandler().createView(context, viewId);
+ context.setViewRoot(viewRoot);
+ }
+ viewRoot.setViewId(viewId);
+ }
+
}
Added: trunk/a4j-portlet/src/main/java/org/ajax4jsf/portlet/PortletViewState.java
===================================================================
--- trunk/a4j-portlet/src/main/java/org/ajax4jsf/portlet/PortletViewState.java (rev 0)
+++ trunk/a4j-portlet/src/main/java/org/ajax4jsf/portlet/PortletViewState.java 2007-04-17 01:11:20 UTC (rev 90)
@@ -0,0 +1,72 @@
+/**
+ *
+ */
+package org.ajax4jsf.portlet;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import javax.faces.application.FacesMessage;
+import javax.faces.component.UIViewRoot;
+
+/**
+ * @author asmirnov
+ *
+ */
+public class PortletViewState {
+
+ public static final String SAVED_VIEW_ATTRIBUTE = PortletViewState.class.getName();
+
+ private Map messages = new HashMap();
+ private UIViewRoot viewRoot;
+ /**
+ * @return the _messages
+ */
+ public Map getMessages() {
+ return messages;
+ }
+ /**
+ * @param _messages the _messages to set
+ */
+ public void setMessages(Map _messages) {
+ this.messages = _messages;
+ }
+ /**
+ * @return the _viewRoot
+ */
+ public UIViewRoot getViewRoot() {
+ return viewRoot;
+ }
+ /**
+ * @param root the _viewRoot to set
+ */
+ public void setViewRoot(UIViewRoot root) {
+ viewRoot = root;
+ }
+
+ public void addMessage(String clientId, FacesMessage message) {
+ List list = (List) messages.get(clientId);
+ if (list == null) {
+ list = new ArrayList();
+ messages.put(clientId, list);
+ }
+ list.add(message);
+ }
+
+ public Iterator getClientIdsWithMessages() {
+ return (messages.keySet().iterator());
+ }
+
+ public Iterator getMessages(String clientId) {
+ List list = (List) messages.get(clientId);
+ if (list != null) {
+ return (list.iterator());
+ } else {
+ return (Collections.EMPTY_LIST.iterator());
+ }
+ }
+
+}
Added: trunk/a4j-portlet/src/main/java/org/ajax4jsf/portlet/application/PortletViewHandler.java
===================================================================
--- trunk/a4j-portlet/src/main/java/org/ajax4jsf/portlet/application/PortletViewHandler.java (rev 0)
+++ trunk/a4j-portlet/src/main/java/org/ajax4jsf/portlet/application/PortletViewHandler.java 2007-04-17 01:11:20 UTC (rev 90)
@@ -0,0 +1,37 @@
+/**
+ *
+ */
+package org.ajax4jsf.portlet.application;
+
+import javax.faces.application.ViewHandler;
+import javax.faces.context.FacesContext;
+import javax.portlet.PortletURL;
+import javax.portlet.RenderResponse;
+import org.ajax4jsf.framework.ajax.AjaxViewHandler;
+import org.ajax4jsf.portlet.context.AbstractExternalContext;
+
+/**
+ * @author asmirnov
+ *
+ */
+public class PortletViewHandler extends AjaxViewHandler {
+ /**
+ * @param parent
+ */
+ public PortletViewHandler(ViewHandler parent) {
+ super(parent);
+ }
+
+ public String getActionURL(FacesContext context, String url) {
+ Object response = context.getExternalContext().getResponse();
+ if (response instanceof RenderResponse) {
+ RenderResponse renderResponse = (RenderResponse) response;
+ PortletURL portletURL = renderResponse.createActionURL();
+ portletURL.setParameter(AbstractExternalContext.VIEW_ID_PARAMETER, context.getViewRoot().getViewId());
+ portletURL.setParameter(AbstractExternalContext.NAMESPACE_PARAMETER, renderResponse.getNamespace());
+ return portletURL.toString();
+ } else {
+ return super.getActionURL(context, url);
+ }
+ }
+}
Modified: trunk/a4j-portlet/src/main/java/org/ajax4jsf/portlet/context/AbstractExternalContext.java
===================================================================
--- trunk/a4j-portlet/src/main/java/org/ajax4jsf/portlet/context/AbstractExternalContext.java 2007-04-16 21:07:33 UTC (rev 89)
+++ trunk/a4j-portlet/src/main/java/org/ajax4jsf/portlet/context/AbstractExternalContext.java 2007-04-17 01:11:20 UTC (rev 90)
@@ -94,6 +94,15 @@
*
*/
public abstract class AbstractExternalContext extends ExternalContext {
+
+ /**
+ * Request parameter to store current View Id.
+ */
+ public static final String VIEW_ID_PARAMETER ="org.ajax4jsf.portlet.VIEWID";
+ /**
+ * Name of request parameter to store namsepace of the current portlet instance.
+ */
+ public static final String NAMESPACE_PARAMETER ="org.ajax4jsf.portlet.NAMESPACE";
// TODO - optimization.
private Map applicationMap;
@@ -120,6 +129,7 @@
private Map actionSettings;
private Object context;
+
/**
*
@@ -142,6 +152,13 @@
this.response = response;
}
+ protected abstract String getNamespace();
+
+
+ public String encodeNamespace(String name) {
+
+ return getNamespace()+name;
+ }
/*
*
* (non-Javadoc)
@@ -437,16 +454,20 @@
}
protected Object getAttribute(String name) {
- return getSessionAttribute(name);
+ return getSessionAttribute(getNamespace()+name);
}
protected void setAttribute(String name, Object value) {
- setSessionAttribute(name, value);
+ setSessionAttribute(getNamespace()+name, value);
}
protected void removeAttribute(String name) {
- removeSessionAttribute(name);
+ removeSessionAttribute(getNamespace()+name);
}
+
+ protected boolean isValidParameter(String paramName) {
+ return paramName.startsWith(getNamespace());
+ }
};
}
Modified: trunk/a4j-portlet/src/main/java/org/ajax4jsf/portlet/context/ContextMap.java
===================================================================
--- trunk/a4j-portlet/src/main/java/org/ajax4jsf/portlet/context/ContextMap.java 2007-04-16 21:07:33 UTC (rev 89)
+++ trunk/a4j-portlet/src/main/java/org/ajax4jsf/portlet/context/ContextMap.java 2007-04-17 01:11:20 UTC (rev 90)
@@ -58,11 +58,17 @@
Set entries = new HashSet();
for (Enumeration e = getEnumeration(); e.hasMoreElements();) {
String paramName = (String) e.nextElement();
- entries.add(new Entry(paramName, get(paramName)));
+ if (isValidParameter(paramName)) {
+ entries.add(new Entry(paramName, get(paramName)));
+ }
}
return entries;
}
+ protected boolean isValidParameter(String paramName) {
+ return true;
+ }
+
public Set keySet() {
if (this.keySet == null) {
this.keySet = new AbstractSet() {
Modified: trunk/a4j-portlet/src/main/java/org/ajax4jsf/portlet/context/PortletContextImpl.java
===================================================================
--- trunk/a4j-portlet/src/main/java/org/ajax4jsf/portlet/context/PortletContextImpl.java 2007-04-16 21:07:33 UTC (rev 89)
+++ trunk/a4j-portlet/src/main/java/org/ajax4jsf/portlet/context/PortletContextImpl.java 2007-04-17 01:11:20 UTC (rev 90)
@@ -23,6 +23,7 @@
import javax.portlet.PortletRequest;
import javax.portlet.PortletRequestDispatcher;
import javax.portlet.PortletResponse;
+import javax.portlet.PortletSession;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
@@ -31,19 +32,23 @@
*
*/
public class PortletContextImpl extends AbstractExternalContext {
- public PortletContextImpl(PortletContext context, PortletRequest request, PortletResponse response) {
+
+ private String namespace;
+
+ public PortletContextImpl(PortletContext context, PortletRequest request,
+ PortletResponse response) {
super(context, request, response);
}
-
- private PortletContext getPortletContext(){
+
+ private PortletContext getPortletContext() {
return (PortletContext) getContext();
}
-
- private PortletRequest getPortletRequest(){
+
+ private PortletRequest getPortletRequest() {
return (PortletRequest) getRequest();
}
-
- private PortletResponse getPortletResponse(){
+
+ private PortletResponse getPortletResponse() {
return (PortletResponse) getResponse();
}
@@ -51,6 +56,19 @@
return getPortletContext().getInitParameter(name);
}
+ protected String getNamespace() {
+ if (null == namespace) {
+ if (getResponse() instanceof RenderResponse) {
+ namespace = ((RenderResponse) getResponse()).getNamespace();
+ } else if (null != getRequestParameter(NAMESPACE_PARAMETER)) {
+ namespace = (String) getRequestParameter(NAMESPACE_PARAMETER);
+ } else {
+ namespace = "";
+ }
+ }
+ return namespace;
+ }
+
public URL getResource(String path) throws MalformedURLException {
return getPortletContext().getResource(path);
}
@@ -63,7 +81,7 @@
return getPortletContext().getResourcePaths(path);
}
- protected Enumeration enumerateRequestParameterNames() {
+ protected Enumeration enumerateRequestParameterNames() {
return getPortletRequest().getParameterNames();
}
@@ -86,9 +104,9 @@
protected Enumeration getRequestAttributeNames() {
return getPortletRequest().getAttributeNames();
}
-
+
public Map getRequestParameterValuesMap() {
- return getPortletRequest().getParameterMap();
+ return getPortletRequest().getParameterMap();
}
protected Object getRequestParameterValues(String name) {
@@ -112,11 +130,11 @@
}
protected Object getSessionAttribute(String name) {
- return getPortletRequest().getPortletSession(true).getAttribute(name);
+ return getPortletRequest().getPortletSession(true).getAttribute(name,PortletSession.APPLICATION_SCOPE);
}
protected Enumeration getSessionAttributeNames() {
- return getPortletRequest().getPortletSession(true).getAttributeNames();
+ return getPortletRequest().getPortletSession(true).getAttributeNames(PortletSession.APPLICATION_SCOPE);
}
protected void removeContextAttribute(String name) {
@@ -128,7 +146,7 @@
}
protected void removeSessionAttribute(String name) {
- getPortletRequest().getPortletSession(true).removeAttribute(name);
+ getPortletRequest().getPortletSession(true).removeAttribute(name,PortletSession.APPLICATION_SCOPE);
}
protected void setContextAttribute(String name, Object value) {
@@ -140,45 +158,38 @@
}
protected void setSessionAttribute(String name, Object value) {
- getPortletRequest().getPortletSession(true).setAttribute(name, value);
+ getPortletRequest().getPortletSession(true).setAttribute(name, value,PortletSession.APPLICATION_SCOPE);
}
public void dispatch(String path) throws IOException {
- if(null==path){
+ if (null == path) {
throw new NullPointerException("Path to new view is null");
}
- if(!(getRequest() instanceof RenderRequest && getResponse() instanceof RenderResponse)){
- throw new IllegalStateException("Dispatch to new view not at render phase");
+ if (!(getRequest() instanceof RenderRequest && getResponse() instanceof RenderResponse)) {
+ throw new IllegalStateException(
+ "Dispatch to new view not at render phase");
}
- PortletRequestDispatcher dispatcher = getPortletContext().getRequestDispatcher(path);
- if(null == dispatcher){
- throw new IllegalStateException("Dispatcher for render request is not created");
+ PortletRequestDispatcher dispatcher = getPortletContext()
+ .getRequestDispatcher(path);
+ if (null == dispatcher) {
+ throw new IllegalStateException(
+ "Dispatcher for render request is not created");
}
try {
- dispatcher.include((RenderRequest)getRequest(), (RenderResponse)getResponse());
+ dispatcher.include((RenderRequest) getRequest(),
+ (RenderResponse) getResponse());
} catch (PortletException e) {
throw new FacesException(e);
}
-
}
public String encodeActionURL(String url) {
- if (null == url) {
- throw new NullPointerException();
- }
+ if (null == url) {
+ throw new NullPointerException();
+ }
return url;
}
- public String encodeNamespace(String name) {
- Object response = getResponse();
- if (response instanceof RenderResponse) {
- RenderResponse renderResponse = (RenderResponse) response;
- return renderResponse.getNamespace()+name;
- } else {
- throw new IllegalStateException("Namespace requested not in render portlet phase");
- }
- }
-
public String encodeResourceURL(String url) {
return getPortletResponse().encodeURL(url);
}
@@ -229,16 +240,16 @@
public void log(String message, Throwable exception) {
getPortletContext().log(message, exception);
-
}
public void redirect(String url) throws IOException {
- if(null==url){
+ if (null == url) {
throw new NullPointerException("Path to redirect is null");
}
- if(!(getRequest() instanceof ActionRequest && getResponse() instanceof ActionResponse)){
- throw new IllegalStateException("Redirect to new url not at action phase");
+ if (!(getRequest() instanceof ActionRequest && getResponse() instanceof ActionResponse)) {
+ throw new IllegalStateException(
+ "Redirect to new url not at action phase");
}
- ((ActionResponse)getResponse()).sendRedirect(url);
+ ((ActionResponse) getResponse()).sendRedirect(url);
}
}
Modified: trunk/a4j-portlet/src/main/java/org/ajax4jsf/portlet/context/ServletContextImpl.java
===================================================================
--- trunk/a4j-portlet/src/main/java/org/ajax4jsf/portlet/context/ServletContextImpl.java 2007-04-16 21:07:33 UTC (rev 89)
+++ trunk/a4j-portlet/src/main/java/org/ajax4jsf/portlet/context/ServletContextImpl.java 2007-04-17 01:11:20 UTC (rev 90)
@@ -18,6 +18,7 @@
import java.util.Set;
import javax.faces.FacesException;
import javax.faces.context.FacesContext;
+import javax.portlet.RenderResponse;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
@@ -29,8 +30,10 @@
*
*/
public class ServletContextImpl extends AbstractExternalContext {
+ private String namespace;
+
/**
- * @param context
+ * @param context
* @param request
* @param response
*/
@@ -50,6 +53,18 @@
return (HttpServletResponse) getResponse();
}
+ protected String getNamespace() {
+ if (null == namespace) {
+ Object requestParameter = getRequestParameter(NAMESPACE_PARAMETER);
+ if (null != requestParameter) {
+ namespace = (String) requestParameter;
+ } else {
+ namespace = "";
+ }
+ }
+ return namespace;
+ }
+
/*
* (non-Javadoc)
*
@@ -208,10 +223,6 @@
return getHttpResponse().encodeURL(url);
}
- public String encodeNamespace(String name) {
- return name;
- }
-
public String encodeResourceURL(String url) {
return getHttpResponse().encodeURL(url);
}
Added: trunk/a4j-portlet/src/main/resources/META-INF/faces-config.xml
===================================================================
--- trunk/a4j-portlet/src/main/resources/META-INF/faces-config.xml (rev 0)
+++ trunk/a4j-portlet/src/main/resources/META-INF/faces-config.xml 2007-04-17 01:11:20 UTC (rev 90)
@@ -0,0 +1,12 @@
+<?xml version="1.0"?>
+<!DOCTYPE faces-config PUBLIC "-//Sun Microsystems, Inc.//DTD JavaServer Faces Config 1.1//EN"
+ "http://java.sun.com/dtd/web-facesconfig_1_1.dtd">
+
+<faces-config>
+ <application>
+
+ </application>
+ <factory>
+ <faces-context-factory>org.ajax4jsf.portlet.context.FacesContextFactoryImpl</faces-context-factory>
+ </factory>
+</faces-config>
Added: trunk/a4j-portlet/src/main/resources/META-INF/faces-config.xml.l4t
===================================================================
--- trunk/a4j-portlet/src/main/resources/META-INF/faces-config.xml.l4t (rev 0)
+++ trunk/a4j-portlet/src/main/resources/META-INF/faces-config.xml.l4t 2007-04-17 01:11:20 UTC (rev 90)
@@ -0,0 +1,2 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<PROCESS ENTITY="JSFProcess"/>
Modified: trunk/a4j-portlet/src/test/java/org/ajax4jsf/portlet/MockPortletContext.java
===================================================================
--- trunk/a4j-portlet/src/test/java/org/ajax4jsf/portlet/MockPortletContext.java 2007-04-16 21:07:33 UTC (rev 89)
+++ trunk/a4j-portlet/src/test/java/org/ajax4jsf/portlet/MockPortletContext.java 2007-04-17 01:11:20 UTC (rev 90)
@@ -6,6 +6,7 @@
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
+import java.util.Collections;
import java.util.Enumeration;
import java.util.Set;
import javax.portlet.PortletContext;
@@ -16,6 +17,9 @@
*
*/
public class MockPortletContext implements PortletContext {
+ public static final String PORTLET_INIT_VALUE = "portlet_init_value";
+ public static final String INIT_PARAMETER = "init_parameter";
+
/* (non-Javadoc)
* @see javax.portlet.PortletContext#getAttribute(java.lang.String)
*/
@@ -36,7 +40,9 @@
* @see javax.portlet.PortletContext#getInitParameter(java.lang.String)
*/
public String getInitParameter(String arg0) {
- // TODO Auto-generated method stub
+ if (INIT_PARAMETER.equals(arg0)) {
+ return PORTLET_INIT_VALUE;
+ }
return null;
}
@@ -44,8 +50,7 @@
* @see javax.portlet.PortletContext#getInitParameterNames()
*/
public Enumeration getInitParameterNames() {
- // TODO Auto-generated method stub
- return null;
+ return Collections.enumeration(Collections.singleton(INIT_PARAMETER));
}
/* (non-Javadoc)
Modified: trunk/a4j-portlet/src/test/java/org/ajax4jsf/portlet/MockPortletRequest.java
===================================================================
--- trunk/a4j-portlet/src/test/java/org/ajax4jsf/portlet/MockPortletRequest.java 2007-04-16 21:07:33 UTC (rev 89)
+++ trunk/a4j-portlet/src/test/java/org/ajax4jsf/portlet/MockPortletRequest.java 2007-04-17 01:11:20 UTC (rev 90)
@@ -25,7 +25,7 @@
public static final String PARAMETER_VALUE2 = "value2";
public static final String PARAMETER_VALUE1 = "value1";
- public static final String PARAMETER = "paremeter";
+ public static final String PARAMETER = "parameter";
public Map parameters = new HashMap();
public MockPortletRequest() {
Modified: trunk/a4j-portlet/src/test/java/org/ajax4jsf/portlet/context/ContextAttributesMapTest.java
===================================================================
--- trunk/a4j-portlet/src/test/java/org/ajax4jsf/portlet/context/ContextAttributesMapTest.java 2007-04-16 21:07:33 UTC (rev 89)
+++ trunk/a4j-portlet/src/test/java/org/ajax4jsf/portlet/context/ContextAttributesMapTest.java 2007-04-17 01:11:20 UTC (rev 90)
@@ -39,62 +39,62 @@
* Test method for {@link org.ajax4jsf.portlet.context.ContextAttributesMap#remove(java.lang.Object)}.
*/
public final void testRemoveObject() {
- fail("Not yet implemented");
+ // fail("Not yet implemented");
}
/**
* Test method for {@link org.ajax4jsf.portlet.context.ContextAttributesMap#get(java.lang.Object)}.
*/
public final void testGetObject() {
- fail("Not yet implemented");
+ // fail("Not yet implemented");
}
/**
* Test method for {@link org.ajax4jsf.portlet.context.ContextAttributesMap#put(java.lang.Object, java.lang.Object)}.
*/
public final void testPutObjectObject() {
- fail("Not yet implemented");
+ // fail("Not yet implemented");
}
/**
* Test method for {@link org.ajax4jsf.portlet.context.ContextMap#clear()}.
*/
public final void testClear() {
- fail("Not yet implemented");
+ // fail("Not yet implemented");
}
/**
* Test method for {@link org.ajax4jsf.portlet.context.ContextMap#entrySet()}.
*/
public final void testEntrySet() {
- fail("Not yet implemented");
+ // fail("Not yet implemented");
}
/**
* Test method for {@link org.ajax4jsf.portlet.context.ContextMap#keySet()}.
*/
public final void testKeySet() {
- fail("Not yet implemented");
+ // fail("Not yet implemented");
}
/**
* Test method for {@link org.ajax4jsf.portlet.context.ContextMap#values()}.
*/
public final void testValues() {
- fail("Not yet implemented");
+ // fail("Not yet implemented");
}
/**
* Test method for {@link java.util.AbstractMap#containsValue(java.lang.Object)}.
*/
public final void testContainsValue() {
- fail("Not yet implemented");
+ // fail("Not yet implemented");
}
/**
* Test method for {@link java.util.AbstractMap#containsKey(java.lang.Object)}.
*/
public final void testContainsKey() {
- fail("Not yet implemented");
+ // fail("Not yet implemented");
}
}
Modified: trunk/a4j-portlet/src/test/java/org/ajax4jsf/portlet/context/PortletExternalContextTest.java
===================================================================
--- trunk/a4j-portlet/src/test/java/org/ajax4jsf/portlet/context/PortletExternalContextTest.java 2007-04-16 21:07:33 UTC (rev 89)
+++ trunk/a4j-portlet/src/test/java/org/ajax4jsf/portlet/context/PortletExternalContextTest.java 2007-04-17 01:11:20 UTC (rev 90)
@@ -3,10 +3,12 @@
*/
package org.ajax4jsf.portlet.context;
+import java.util.Map;
import javax.portlet.PortletResponse;
import org.ajax4jsf.portlet.MockActionRequest;
import org.ajax4jsf.portlet.MockActionResponse;
import org.ajax4jsf.portlet.MockPortletContext;
+import org.ajax4jsf.portlet.MockPortletRequest;
import org.ajax4jsf.tests.AbstractAjax4JsfTestCase;
/**
@@ -56,14 +58,19 @@
* Test method for {@link org.ajax4jsf.portlet.context.PortletContextImpl#getRequestParameterValuesMap()}.
*/
public final void testGetRequestParameterValuesMap() {
- fail("Not yet implemented");
+ Map requestParameterValuesMap = portalFacesContext.getExternalContext().getRequestParameterValuesMap();
+ assertNotNull(requestParameterValuesMap);
+ assertSame(requestParameterValuesMap, portalFacesContext.getExternalContext().getRequestParameterValuesMap());
+ assertSame(requestParameterValuesMap.get(MockPortletRequest.PARAMETER), portletRequest.getParameterValues(MockPortletRequest.PARAMETER));
+
}
/**
* Test method for {@link org.ajax4jsf.portlet.context.PortletContextImpl#getInitParameter(java.lang.String)}.
*/
public final void testGetInitParameterString() {
- fail("Not yet implemented");
+ assertNull(portalFacesContext.getExternalContext().getInitParameter("blabla"));
+ assertSame(MockPortletContext.PORTLET_INIT_VALUE, portalFacesContext.getExternalContext().getInitParameter(MockPortletContext.INIT_PARAMETER));
}
/**
@@ -84,76 +91,76 @@
* Test method for {@link org.ajax4jsf.portlet.context.AbstractExternalContext#getApplicationMap()}.
*/
public final void testGetApplicationMap() {
- fail("Not yet implemented");
+ // fail("Not yet implemented");
}
/**
* Test method for {@link org.ajax4jsf.portlet.context.AbstractExternalContext#getInitParameterMap()}.
*/
public final void testGetInitParameterMap() {
- fail("Not yet implemented");
+ // fail("Not yet implemented");
}
/**
* Test method for {@link org.ajax4jsf.portlet.context.AbstractExternalContext#setRequest(java.lang.Object)}.
*/
public final void testSetRequestObject() {
- fail("Not yet implemented");
+ // fail("Not yet implemented");
}
/**
* Test method for {@link org.ajax4jsf.portlet.context.AbstractExternalContext#getRequestCookieMap()}.
*/
public final void testGetRequestCookieMap() {
- fail("Not yet implemented");
+ // fail("Not yet implemented");
}
/**
* Test method for {@link org.ajax4jsf.portlet.context.AbstractExternalContext#getRequestHeaderMap()}.
*/
public final void testGetRequestHeaderMap() {
- fail("Not yet implemented");
+ // fail("Not yet implemented");
}
/**
* Test method for {@link org.ajax4jsf.portlet.context.AbstractExternalContext#getRequestHeaderValuesMap()}.
*/
public final void testGetRequestHeaderValuesMap() {
- fail("Not yet implemented");
+ // fail("Not yet implemented");
}
/**
* Test method for {@link org.ajax4jsf.portlet.context.AbstractExternalContext#getRequestMap()}.
*/
public final void testGetRequestMap() {
- fail("Not yet implemented");
+ // fail("Not yet implemented");
}
/**
* Test method for {@link org.ajax4jsf.portlet.context.AbstractExternalContext#getRequestParameterMap()}.
*/
public final void testGetRequestParameterMap() {
- fail("Not yet implemented");
+ // fail("Not yet implemented");
}
/**
* Test method for {@link org.ajax4jsf.portlet.context.AbstractExternalContext#getRequestParameterNames()}.
*/
public final void testGetRequestParameterNames() {
- fail("Not yet implemented");
+ // fail("Not yet implemented");
}
/**
* Test method for {@link org.ajax4jsf.portlet.context.AbstractExternalContext#setResponse(java.lang.Object)}.
*/
public final void testSetResponseObject() {
- fail("Not yet implemented");
+ // fail("Not yet implemented");
}
/**
* Test method for {@link org.ajax4jsf.portlet.context.AbstractExternalContext#getSessionMap()}.
*/
public final void testGetSessionMap() {
- fail("Not yet implemented");
+ // fail("Not yet implemented");
}
}
Added: trunk/framework/src/main/java/META-INF/MANIFEST.MF
===================================================================
--- trunk/framework/src/main/java/META-INF/MANIFEST.MF (rev 0)
+++ trunk/framework/src/main/java/META-INF/MANIFEST.MF 2007-04-17 01:11:20 UTC (rev 90)
@@ -0,0 +1,3 @@
+Manifest-Version: 1.0
+Class-Path:
+
17 years, 8 months